AI Wiki中文/EN

DenseNet: retaining and reusing earlier features

DenseNet

Follow dense connections, derive growth and BC costs, and run a small NumPy classifier.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Follow the data

A layer has already found an edge. Must every later layer learn to describe that edge again? DenseNet gives later layers direct access to earlier feature maps, so a new layer can spend its output channels on additional features. Whether it actually learns useful additions is a training question; the access is an architectural fact.

Try a small example. Start with three channels, then let each of three transformations produce two new channels. The states contain 3, 5, 7 and 9 channels. The second transformation reads all five available channels, not just the two most recently produced. None of this means “a fully connected layer”: the transformations can still be spatial convolutions.

The original design groups these connections into dense blocks. Within one block, height and width stay fixed so the maps can be concatenated along the channel axis. A transition between blocks changes their size. This is the central construction of Huang and colleagues’ CVPR2017 paper. DenseNet method

Compare a drawer with labeled compartments to a sum. Concatenation preserves separate coordinates; addition combines corresponding coordinates. The analogy ends there: concatenated features may be redundant, and the next learned convolution can discard them.

Definitions and calculations

Let the block input be x0x_0 with m0m_0 channels. Transformation HlH_l produces kk channels at the same spatial resolution. Brackets mean channel concatenation, not a sum:

xl=Hl([x0,x1,…,xl−1]),ml=m0+(l−1)k.\begin{aligned}x_l&=H_l([x_0,x_1,\ldots,x_{l-1}]),\\m_l&=m_0+(l-1)k.\end{aligned}

After LL transformations, the state has m0+Lkm_0+Lk channels. The growth rate kk counts newly produced channels per transformation; it is not the total block width. With the input counted as an earlier state, the number of direct state-to-transformation connections is 1+2+⋯+L=L(L+1)/21+2+\cdots+L=L(L+1)/2. This counts graph edges, not parameters or distinct physical tensor copies.

In the basic version, HlH_l is BN, ReLU, then a padded 3×33\times3 convolution. DenseNet-B inserts a 1×11\times1 convolution producing 4k4k channels before that spatial convolution, with BN and ReLU before each convolution. DenseNet-C reduces the channels between blocks; BC combines both choices. If the outgoing state has mm channels, the transition produces ⌊θm⌋\lfloor\theta m\rfloor, with 0<θ≤10<\theta\le1, then applies 2×22\times2 average pooling. The paper uses θ=0.5\theta=0.5 in its compressed experiments. Method, equation 2 and BC definitions

Why add a bottleneck? Ignore BN and biases for this comparison. A basic layer with mm input channels uses 9mk9mk convolution weights. The BC layer uses m(4k)m(4k) in its pointwise convolution and 9(4k)k9(4k)k in its spatial convolution:

Pbasic=9mk,PBC=4mk+36k2,PBC<Pbasic  ⟺  m>7.2k.\begin{aligned}P_{\mathrm{basic}}&=9mk,\\P_{\mathrm{BC}}&=4mk+36k^2,\\P_{\mathrm{BC}}<P_{\mathrm{basic}}&\iff m>7.2k.\end{aligned}

For k=2,m=3k=2,m=3, the counts are 54 and168: this “bottleneck” expands the intermediate representation and costs more. At m=32m=32, the counts become576 and400. The name does not guarantee a saving in every layer. At fixed output size, convolution MACs equal the weight count times the number of output positions; BN, activation and memory movement are separate costs.

The retained-input slice of a block is especially easy to analyze. Write its whole state as S(x)=[x,G(x)]S(x)=[x,G(x)] and partition the incoming derivative accordingly:

JS(x)=[IJG(x)],∇xL=gold+JG(x)⊤gnew.\begin{aligned}J_S(x)&=\begin{bmatrix}I\\J_G(x)\end{bmatrix},\\\nabla_x\mathcal L&=g_{\mathrm{old}}+J_G(x)^\top g_{\mathrm{new}}.\end{aligned}

There is a direct identity path. Its contribution can nevertheless be zero, or cancel another contribution. A transition can also remove information. This equation explains an available route for derivatives; it does not prove that every gradient in a trained network remains large.

Run the small model

The program below uses NumPy1.26.4 and Python3.12.4. It executes an original miniature classifier: a 3×3 stem, two BC transformations, one transition, two more BC transformations, final normalization, global average pooling and a three-class head. The input is a single HWC image. BN runs in inference mode with supplied zero means and unit variances; gamma and beta are initialized to one and zero. No data are used to fit them.

The separate imagenet_plan function counts the paper’s four-block configurations; it does not execute them. For the 121 configuration it obtains block widths256,512, 1024, 1024. The depth count includes the stem, two convolutions per BC transformation, three transitions and the classifier:121. Its7,978,856 parameters include BN affine terms and the classifier bias, exclude BN running-statistic buffers, and assume bias-free convolutions. The2,834,161,664 MACs include only convolution and linear products. These are our calculations under stated conventions, not a timing result.

"""Original NumPy DenseNet teaching preflight; not a trained DenseNet-121.

HWC single-image inputs, cross-correlation, bias-free convolutions,
inference BN with supplied zero means/unit variances, and floor pooling.
The classifier executes two small BC blocks; imagenet_plan only counts
paper configurations and does not allocate or run those full models.
"""
import math
import numpy as np


def positive(n):
    if isinstance(n, (bool, np.bool_)) or not isinstance(n, (int, np.integer)) or n < 1:
        raise ValueError('expected a positive integer')
    return int(n)


def image(x):
    x = np.asarray(x, dtype=float)
    if x.ndim != 3 or min(x.shape) < 1 or not np.isfinite(x).all():
        raise ValueError('expected finite nonempty HWC input')
    return x


def conv(x, w):
    x, w = image(x), np.asarray(w, dtype=float)
    if (w.ndim != 4 or min(w.shape) < 1 or w.shape[0] != w.shape[1]
            or w.shape[0] % 2 != 1 or w.shape[2] != x.shape[2]
            or not np.isfinite(w).all()):
        raise ValueError('expected finite odd square KH-KW-Cin-Cout weights')
    k, _, _, out = w.shape
    z = np.pad(x, ((k//2, k//2), (k//2, k//2), (0, 0)))
    y = np.empty((*x.shape[:2], out))
    for i in range(x.shape[0]):
        for j in range(x.shape[1]):
            y[i, j] = np.einsum('abc,abcd->d', z[i:i+k, j:j+k], w)
    return y


def bn_relu(x, gamma, beta, mean, variance, eps=1e-5):
    x = image(x)
    vectors = [np.asarray(v, dtype=float) for v in (gamma, beta, mean, variance)]
    if any(v.shape != (x.shape[2],) or not np.isfinite(v).all() for v in vectors):
        raise ValueError('BN vectors must match channels')
    if not np.isfinite(eps) or eps <= 0 or (vectors[3] < 0).any():
        raise ValueError('invalid BN variance or epsilon')
    g, b, mu, var = vectors
    return np.maximum(g * (x-mu) / np.sqrt(var+eps) + b, 0)


def avg_pool(x):
    x = image(x)
    h, w, c = x.shape
    if min(h, w) < 2:
        raise ValueError('pooling needs at least 2 by 2')
    return x[:h//2*2, :w//2*2].reshape(h//2, 2, w//2, 2, c).mean(axis=(1, 3))


def compressed(channels, theta):
    channels = positive(channels)
    if not np.isfinite(theta) or not 0 < theta <= 1:
        raise ValueError('compression must be in (0, 1]')
    result = math.floor(channels * theta)
    if result == 0:
        raise ValueError('compression would remove every channel')
    return result


def block(x, layers):
    state = image(x).copy()
    for first, second, norm1, norm2 in layers:
        added = conv(bn_relu(conv(bn_relu(state, *norm1), first), *norm2), second)
        state = np.concatenate((state, added), axis=2)
    return state


def transition(x, w, norm):
    if np.asarray(w).ndim != 4 or w.shape[:2] != (1, 1):
        raise ValueError('transition convolution must be 1 by 1')
    return avg_pool(conv(bn_relu(x, *norm), w))


def make_layers(channels, count, growth, rng):
    channels, count, growth = map(positive, (channels, count, growth))
    layers = []
    for i in range(count):
        m, b = channels + i*growth, 4*growth
        layers.append((rng.normal(0, .1, (1, 1, m, b)),
                       rng.normal(0, .1, (3, 3, b, growth)),
                       norm(m), norm(b)))
    return layers


def norm(channels):
    channels = positive(channels)
    return (np.ones(channels), np.zeros(channels), np.zeros(channels), np.ones(channels))


def imagenet_plan(counts=(6, 12, 24, 16), growth=32, theta=.5, classes=1000):
    counts = tuple(positive(n) for n in counts)
    growth, classes = positive(growth), positive(classes)
    if len(counts) != 4:
        raise ValueError('this ImageNet plan requires four blocks')
    m = 2*growth
    compressed(m, theta)
    # Stem conv and BN affine parameters. Running means/variances are buffers.
    params, macs, side = 7*7*3*m + 2*m, 112*112*7*7*3*m, 56
    widths = []
    for j, count in enumerate(counts):
        for _ in range(count):
            b = 4*growth
            weights = m*b + 9*b*growth
            params += weights + 2*m + 2*b
            macs += side*side*weights
            m += growth
        widths.append(m)
        if j < 3:
            out = compressed(m, theta)
            params += 2*m + m*out
            macs += side*side*m*out
            m, side = out, side//2
    params += 2*m + m*classes + classes
    macs += m*classes
    return dict(widths=widths, depth=1+2*sum(counts)+3+1,
                parameters=params, convolution_and_linear_macs=macs)


def tiny_classifier(x, seed=9):
    x = image(x)
    if x.shape[2] != 3 or min(x.shape[:2]) < 2:
        raise ValueError('classifier expects RGB input with sides at least 2')
    rng = np.random.default_rng(seed)
    state = conv(x, rng.normal(0, .1, (3, 3, 3, 4)))
    state = block(state, make_layers(4, 2, 2, rng))
    state = transition(state, rng.normal(0, .1, (1, 1, 8, 4)), norm(8))
    state = block(state, make_layers(4, 2, 2, rng))
    features = bn_relu(state, *norm(8)).mean(axis=(0, 1))
    scores = features @ rng.normal(0, .1, (8, 3))
    probabilities = np.exp(scores-scores.max())
    return probabilities/probabilities.sum()


if __name__ == '__main__':
    print(imagenet_plan())
    x = np.arange(8*8*3, dtype=float).reshape(8, 8, 3)/(8*8*3)
    print('tiny probabilities:', np.round(tiny_classifier(x), 6).tolist())

Running it produces:

{'widths': [256, 512, 1024, 1024], 'depth': 121, 'parameters': 7978856, 'convolution_and_linear_macs': 2834161664}
tiny probabilities: [0.330595, 0.33332, 0.336085]

Change the random seed and the probabilities change. Zero input gives a uniform distribution because this initialization has no additive offsets. Neither observation measures recognition accuracy. The tests also construct layers that produce the exact state [x,2x,6x][x,2x,6x]: the second new feature can only be obtained by reading the first new feature. This checks the connection mechanism more directly than a plausible-looking classifier output.

What the model does not establish

Dense connectivity is local to a block. Concatenating different spatial shapes is undefined without an additional alignment rule; the transition avoids that problem by ending one block before downsampling. Its projection and pooling generally prevent recovering the original state exactly.

Parameter efficiency and memory efficiency are different questions. With fixed spatial area AA, a block’s final unique state holds A(m0+Lk)A(m_0+Lk) numbers. A naive implementation that creates a fresh concatenated state at every step cumulatively copies a number proportional to A∑l=1L(m0+lk)A\sum_{l=1}^L(m_0+lk). That sum grows quadratically in LL at fixed kk, although the final state grows linearly. It is not a formula for peak training memory: temporary arrays, gradients, saved activations and memory reuse change that quantity.

D2L’s block lesson makes concatenation and transitions easy to follow, but its basic block has no4k bottleneck. Mixing that implementation with a BC parameter count would compare different models. Our code follows the BC construction while deliberately omitting training, data preprocessing, augmentation and optimization.

Compare ResNet for addition, Inception for parallel branches and MobileNet for factorized convolution. None is uniformly best. Specify accuracy, data, memory, batch size and deployment hardware before choosing an architecture.

Exercises with answers

1. Three new maps per layer

Answer: With5 input channels and4 transformations of growth3, the final state has 17 channels. The fourth transformation reads14 channels, then adds3.

2. When is the bottleneck smaller?

Answer: For m=32 and k=2, basic and BC convolution weights are 576 and400. For m=3 they are 54 and168. The inequality is m>7.2k; include BN separately if counting trainable parameters.

3. Does direct access guarantee a nonzero gradient?

Answer: No. A downstream objective may ignore all retained coordinates, making their direct derivative zero. Contributions from different routes can also cancel; a projection can discard coordinates.

4. Compress a seven-channel state

Answer: At theta=.5, a transition produces 3 channels. A5×5 state becomes 2×2 under the program’s floor pooling. The omitted edge and channel projection prevent assuming lossless recovery; test another pooling convention separately.

Sources and next steps

Read the original paper’s equation 2, growth-rate paragraph, BC definitions and table 1 together. Table 1 describes ImageNet configurations; its layer counts should not be transferred to the miniature two-block program. The parameter table here is independently computed with explicit BN and bias conventions. Huang et al., 2017

Then use D2L§8.7.2–8.7.4 to track actual tensors through a simpler dense block and transition. The useful comparison is the order of operations and channel shapes, not an assumption that all implementations named DenseNet are identical. D2L1.0.3

For a further experiment, record both the final state size and total concatenation-copy volume as L increases. Keep these separate from peak resident memory and measured latency. This turns “feature reuse” into quantities that can be inspected.

Make a prediction, then check

A block starts with5 channels and adds3 channels in each of4 transformations. How many channels remain before transition?

Choose one answer

Learning objectives

  • Compute channel growth and transition compression.
  • Compare basic and BC parameter costs under explicit assumptions.
  • Distinguish preserved feature paths from gradient and memory guarantees.

Prerequisites & connections

Explore related knowledge →

References

  1. Densely Connected Convolutional Networks — CVPR2017 method
    Gao Huang; Zhuang Liu; Laurens van der Maaten; Kilian Q. Weinberger · 2017
  2. Dive into Deep Learning1.0.3 — DenseNet blocks and transitions
    Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: bounded original method passages and fixed official code, explicit NumPy teaching models, independent numerical references, boundary cases and corresponding bilingual reasoning. Not independent human or second-agent review; no full training or deployment benchmark reproduction.

  • Single-agent authored technical review; runnable example, exact or literal reference checks, explicit assumptions and matching bilingual equations/exercises. Automated execution and rendering results recorded separately.
  • Verified retained signed coordinates and finite-difference identity path, cross-layer dependency [x,2x,6x], literal convolution, BN/pooling, independent stage parameter ledger and bottleneck counterexample. 8 article checks; no training reproduction.
  • Both languages compared section by section for claims, caveats, definitions, examples, formulas and four answer explanations. English spacing edited only outside code, mathematics, tags and link destinations before freezing.
  • Complete bilingual prose and corresponding exercises promoted with formal status and SHA binding. Algorithm tests read formal MDX; historical essays claim no executable program or computational tests.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
  • Visual phone review found long compound equations extended beyond the initial visible math area. Reformatted the same equations into aligned lines in both languages; values, claims, examples, code and reference targets unchanged. Frozen originals retained; final files rechecked and SHA rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.