AI Wiki中文/EN

MobileNet: factorized filters and linear bottlenecks

MobileNet

Derive V1 costs, inspect V2 inverted residuals, and test what nonlinearities retain or discard.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Follow the data

Suppose a convolution receives four channels and must produce eight. A3×3 filter for every input/output pair needs 288 weights. What if each input channel first gets its own spatial filter, and a separate matrix mixes the resulting channels? The count becomes 36+32=68. The saving is real; the two operators are not equally expressive.

This separation is the starting point of MobileNetV1. A depthwise convolution filters each channel independently. A pointwise1×1 convolution mixes channels at each spatial position. The V1 block places BN and ReLU after both convolutions. Howard et al., 2017,§3.1–3.2

MobileNetV2 asks a different question: where should the network be narrow, and where can it afford nonlinear transformations? It expands a narrow representation, filters the wider intermediate tensor, then projects back to a narrow output without a final activation. When sizes agree, the shortcut connects those narrow endpoints. This is an inverted residual block. Sandler et al., 2018

This article covers the V1 and V2 mechanisms. The family name is not a claim that later versions have identical blocks, activations or search procedures.

Definitions and calculations

Let M,NM,N be the input and output channel counts, KK an odd spatial kernel size, and AA the number of output positions. Ignore bias, BN, activation and padding overhead. A dense convolution has one K×KK\times K filter for every channel pair. A multiplier-one depthwise convolution has one such filter per input channel; its following pointwise convolution has an M×NM\times N matrix:

Pdense=K2MN,Psep=K2M+MN,MACsepMACdense=1N+1K2.\begin{aligned}P_{\mathrm{dense}}&=K^2MN,\\P_{\mathrm{sep}}&=K^2M+MN,\\\frac{\mathrm{MAC}_{\mathrm{sep}}}{\mathrm{MAC}_{\mathrm{dense}}}&=\frac1N+\frac1{K^2}.\end{aligned}

MAC means one multiply-accumulate. For the opening example on 8×8 outputs, the counts are 18,432 and4,352 MACs. A depthwise layer with multiplier greater than one follows a different count; that is not the operator used here. The original V1 paper gives the multiplier-one decomposition and arithmetic. V1 equations2–5

A cost reduction usually comes with a constraint. If there is no nonlinearity between the factors, their effective dense kernel is:

Wa,b,m,n=Da,b,mPm,n.W_{a,b,m,n}=D_{a,b,m}P_{m,n}.

For any fixed input channel mm, reshape its spatial/output slice into a K2×NK^2\times N matrix. It is an outer product, so its rank is at most one. A dense kernel can have higher rank. Stacking blocks can build richer functions, but a single multiplier-one separable layer cannot represent every dense kernel. Furthermore, V1 inserts a nonlinearity: a negative depthwise response is clipped before the pointwise matrix can use it. The effective linear-kernel equation no longer describes that whole block.

V1’s width multiplier α\alpha scales internal input and output channels; its resolution multiplier ρ\rho changes spatial sizes. Before integer rounding, the internal-layer cost becomes:

MAC(α,ρ)=Aρ2(K2αM+α2MN).\mathrm{MAC}(\alpha,\rho)=A\rho^2\left(K^2\alpha M+\alpha^2MN\right).

Only the pointwise term scales quadratically with width. Halving the opening example’s channels changes68 weights to 26, not17. Input RGB channels, the classifier and rounding also require separate treatment in a full network. The V1 paper describes approximate width/resolution trade-offs, not an exact universal quadratic law. V1§3.3–3.4

For V2, let the expanded width be E=tME=tM, input area AiA_i and output area AoA_o. The expansion happens before depthwise downsampling. With an explicit expansion convolution, its three convolution costs are:

PV2=ME+K2E+EN,MACV2=AiME+Ao(K2E+EN).\begin{aligned}P_{\mathrm{V2}}&=ME+K^2E+EN,\\\mathrm{MAC}_{\mathrm{V2}}&=A_iME+A_o(K^2E+EN).\end{aligned}

At stride one, the areas agree. At stride two, charging every term at the smaller output area would undercount expansion. The expansion and depthwise stages use ReLU6; the projection has BN but no activation. A shortcut is used here only for stride one and matching channel counts. BN at inference is an affine transformation; “linear bottleneck” refers to omitting the elementwise nonlinear activation, not forbidding BN offsets. V2 table 1 and figure 4

Run the small model

A scalar example makes the bottleneck issue visible. ReLU maps both−2 and−1 to zero. Expanding a scalar to two coordinates can retain its sign:

z(x)=[max⁡(x,0),max⁡(−x,0)],x=z1(x)−z2(x).z(x)=[\max(x,0),\max(-x,0)],\qquad x=z_1(x)-z_2(x).

This is an exact constructed example, not a guarantee about a learned expansion. With ReLU6 the same reconstruction holds only on the interval[−6,6]; saturation loses larger magnitudes. The V2 paper motivates its design using low-dimensional activation structure, so its information-preservation discussion should keep those assumptions. A linear projection can still lose information through insufficient rank.

The complete program below runs individual V1 and V2 blocks in NumPy1.26.4. It uses HWC tensors, symmetric zero padding and explicit inference BN statistics. For even image sizes at stride two, this padding need not align with a framework’s asymmetric SAME convention. It always includes the supplied V2 expansion matrix; it does not claim an optimized full-network treatment of an expansion ratio of one. No original classifier training, quantization or device timing is reproduced.

"""Original NumPy blocks; symmetric padding, single-image HWC, inference BN."""
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 depthwise(x, w, stride=1):
    x, w, stride = image(x), np.asarray(w, dtype=float), positive(stride)
    if (w.ndim != 3 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 odd square KH-KW-C weights')
    k = w.shape[0]
    z = np.pad(x, ((k//2,k//2),(k//2,k//2),(0,0)))
    y = np.empty(((x.shape[0]+stride-1)//stride, (x.shape[1]+stride-1)//stride, x.shape[2]))
    for i in range(y.shape[0]):
        for j in range(y.shape[1]):
            y[i,j] = (z[i*stride:i*stride+k,j*stride:j*stride+k]*w).sum(axis=(0,1))
    return y


def pointwise(x, w):
    x, w = image(x), np.asarray(w, dtype=float)
    if w.ndim != 2 or min(w.shape) < 1 or w.shape[0] != x.shape[2] or not np.isfinite(w).all():
        raise ValueError('pointwise weights must have shape Cin-Cout')
    return x @ w


def bn(x, norm):
    x = image(x)
    g,b,m,v = [np.asarray(a,dtype=float) for a in norm]
    if any(a.shape != (x.shape[2],) or not np.isfinite(a).all() for a in (g,b,m,v)) or (v < 0).any():
        raise ValueError('invalid inference BN vectors')
    return g*(x-m)/np.sqrt(v+1e-5)+b


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


def v1(x, dw, pw, norms, stride=1):
    z=np.maximum(bn(depthwise(x,dw,stride),norms[0]),0)
    return np.maximum(bn(pointwise(z,pw),norms[1]),0)


def v2(x, weights, norms, stride=1):
    x=image(x)
    expansion, dw, projection = weights
    z=np.clip(bn(pointwise(x,expansion),norms[0]),0,6)
    z=np.clip(bn(depthwise(z,dw,stride),norms[1]),0,6)
    y=bn(pointwise(z,projection),norms[2])
    # No ReLU after projection or after the narrow shortcut addition.
    return x+y if stride==1 and x.shape[2]==y.shape[2] else y


def costs(h,w,cin,cout,k=3,expansion=6,stride=1):
    h,w,cin,cout,k,expansion,stride=map(positive,(h,w,cin,cout,k,expansion,stride))
    ho,wo=(h+stride-1)//stride,(w+stride-1)//stride
    e=expansion*cin
    standard=k*k*cin*cout
    separable=k*k*cin+cin*cout
    inverted=cin*e+k*k*e+e*cout
    return dict(standard_weights=standard,separable_weights=separable,
                standard_macs=ho*wo*standard,separable_macs=ho*wo*separable,
                inverted_weights=inverted,
                inverted_macs=h*w*cin*e+ho*wo*(k*k*e+e*cout))


if __name__=='__main__':
    print('layer costs:',costs(8,8,4,8,expansion=2))
    rng=np.random.default_rng(3);x=rng.normal(0,1,(5,5,4))
    weights=(rng.normal(0,.1,(4,8)),rng.normal(0,.1,(3,3,8)),rng.normal(0,.1,(8,4)))
    norms=(norm(8),norm(8),norm(4))
    print('V2 stride-1/2 shapes:',v2(x,weights,norms).shape,v2(x,weights,norms,2).shape)
    print('V1 block shape:',v1(x,np.ones((3,3,4)),np.ones((4,8)),[norm(4),norm(8)]).shape)
    z=np.linspace(-3,3,7);pair=np.stack((np.maximum(z,0),np.maximum(-z,0)),axis=1)
    print('signed reconstruction:',(pair[:,0]-pair[:,1]).tolist())

Expected output:

layer costs: {'standard_weights': 288, 'separable_weights': 68, 'standard_macs': 18432, 'separable_macs': 4352, 'inverted_weights': 168, 'inverted_macs': 10752}
V2 stride-1/2 shapes: (5, 5, 4) (3, 3, 4)
V1 block shape: (5, 5, 8)
signed reconstruction: [-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0]

The two shapes come from the same5×5 input: stride one retains the 5×5 spatial grid, while stride two yields3×3. In a zero-residual test with matching channels, V2 returns the original signed input exactly. There is no final ReLU to clip it. At stride two the shortcut is absent, so a zero residual branch returns zeros.

What the model does not establish

Fewer MACs need not mean proportionally less latency. A device must load activations, launch kernels and move intermediate results between operators. A1×1 matrix multiply and a small depthwise convolution can make very different use of the same hardware. Report measured batch size, precision, runtime, input shape and warm-up policy before making a speed claim. The V1 paper itself distinguishes arithmetic count from efficient implementation. V1§3.2

The V1 source table labels its last1024-channel depthwise layer with stride two while continuing to show7×7 tensors. That table alone is insufficient to choose an exact full-network implementation. The examples here isolate the verified operators and declare their padding. No whole V1 model is silently reconstructed from the inconsistency.

Likewise, V2’s information-flow motivation is not a theorem that all narrow projections are lossless. The signed reconstruction above is a counterexample to “ReLU must always destroy information,” while its saturation outside the chosen interval disproves a universal preservation claim. A useful architecture explanation needs both sides of that boundary.

For subsequent study, EfficientNet combines an MBConv-related operator with other design choices and scaling rules. Model evaluation supplies the comparison protocol. Specify a real baseline rather than attributing every mobile-model improvement to one block.

Exercises with answers

1. Calculate the factorization saving

Answer: For K=3,M=4,N=8, a dense kernel has 288 weights; multiplier-one depthwise plus pointwise has 36+32=68. On64 output positions the MACs are 18,432 and4,352, excluding BN and activation.

2. Can one separable layer represent every dense kernel?

Answer: No. Without the intermediate activation, each fixed-input-channel spatial/output matrix has rank at most one. Two independent spatial patterns for two outputs can have rank two and violate that constraint.

3. What remains when the residual branch is zero?

Answer: A matching stride-one V2 block returns its signed input. A stride-two block has no identity shortcut in this construction and returns zero. Adding a final ReLU would change the first result for negative coordinates.

4. Correct a stride-two cost estimate

Answer: For a 5×5 input, M=4,N=8,t=2,K=3 and symmetric padding, expansion costs 25×4×8=800 MACs. The3×3 output depthwise/projection stages cost9×(9×8+8×8)=1,224. Total2,024; using output area for expansion would undercount it.

Sources and next steps

The V1 reference used here is arXiv v1. Read its decomposition, BN/ReLU order and multiplier formulas, keeping the table inconsistency separate from the valid operator arithmetic. MobileNets, 2017

For V2, read the bottleneck construction, table 1 and figure 4 before interpreting its manifold discussion. The small program tests the operator order, signed outputs, shortcut condition and expansion cost; it does not test the paper’s mobile benchmarks. MobileNetV2,CVPR2018

As a practical extension, time standard and separable operators on the same device and tensor shape after warm-up. Keep the arithmetic comparison even if the timing order surprises you: the discrepancy is evidence about the implementation, not a reason to change the formula.

Make a prediction, then check

What happens after the projection in the V2 block described here?

Choose one answer

Learning objectives

  • Derive depthwise and pointwise parameter/MAC counts.
  • Explain the rank restriction and the role of nonlinearities.
  • Test V2 projection, shortcut and stride behavior.

Prerequisites & connections

Explore related knowledge →

References

  1. MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications — arXiv v1
    Andrew G. Howard; Menglong Zhu; Bo Chen; Dmitry Kalenichenko; Weijun Wang; Tobias Weyand; Marco Andreetto; Hartwig Adam · 2017
  2. MobileNetV2: Inverted Residuals and Linear Bottlenecks — CVPR2018 method
    Mark Sandler; Andrew Howard; Menglong Zhu; Andrey Zhmoginov; Liang-Chieh Chen · 2018

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 literal depthwise stride, dense-kernel factorization and rank counterexample, intervening-ReLU failure, negative projection, zero-residual shortcut, input-area expansion cost and signed reconstruction limits. 9 article checks; explicit symmetric padding, no full V1/V2 classifier or mobile timing.
  • 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.