Efficient architectures: count the work, then measure the device
高效神经架构
Compare dense and depthwise-separable convolution exactly, identify its rank constraint and separate operation counts from latency.
efficient-architecturesStart with the problem
A model can have few weights yet move large activation tensors through memory. Another can use more arithmetic but run faster because its operations fit the accelerator well. An efficient architecture has to meet a task and a hardware budget; parameter count alone is not enough.
MobileNets separates spatial filtering from channel mixing. MobileNetV2 uses expanded internal representations with narrow linear bottlenecks. EfficientNet coordinates depth, width and resolution. These are distinct design choices. We will calculate one block exactly and use it to explain why arithmetic savings come with assumptions.
Definitions and derivation
Assume stride one, same-sized spatial output, no biases, and one depthwise filter per input channel. A dense k-by-k convolution mixes every input channel into every output channel. A separable block first filters channels independently, then applies a 1×1 channel map:
P counts weight slots. Multiplying each weight count by the number of output positions gives nominal multiply–accumulate counts M, with one MAC counted as one multiplication plus accumulation. Different FLOP conventions can count this as roughly two operations. The ratio is not necessarily below one: with a single output channel and k=3, the separable block costs 10/9 as much arithmetic.
Without a nonlinearity between its two operations, the separable block is equivalent to a constrained dense kernel:
For each input channel, all output spatial filters are scalar multiples of one spatial pattern. A dense kernel whose spatial-by-output matrix has rank two cannot be represented by this one-filter factorization. A larger depthwise multiplier changes that constraint. Adding nonlinearities also changes the function class and destroys the simple linear-kernel equivalence. The original MobileNet includes normalization and activations; our equality applies only to the stated linear block.
Compound scaling considers a different resource question. For regular convolutions, increasing depth, channel width and input resolution has approximately this effect:
EfficientNet chooses coefficients with αβ²γ² approximately two, so increasing φ by one roughly doubles the convolutional work. Rounding channel counts, operator mixtures and implementation costs make this a proxy rather than an exact runtime law. A fixed parameter budget does not control the resolution-dependent activation cost.
Run the calculation
The complete Python 3.12 / NumPy 1.26.4 program applies both forms to a 5×5 image with two channels and three output channels. It explicitly constructs the equivalent dense kernel and counts scalar MAC terms in the loops. Kernels use the cross-correlation convention common in neural-network libraries.
import numpy as np
def separable_and_dense(x, depthwise, pointwise):
x, d, p = [np.asarray(v, dtype=float) for v in (x, depthwise, pointwise)]
if x.ndim != 3 or d.ndim != 3 or p.ndim != 2 or not all(1 <= v <= 8 for v in x.shape) or d.shape[:2] not in ((1, 1), (3, 3)) or d.shape[2] != x.shape[2] or p.shape[0] != x.shape[2] or not 1 <= p.shape[1] <= 8:
raise ValueError('Use small HWC inputs, a 1x1 or 3x3 depthwise filter and a matching channel map.')
if not all(np.isfinite(v).all() for v in (x, d, p)):
raise ValueError('All arrays must be finite.')
h, w, cin = x.shape; size = d.shape[0]; cout = p.shape[1]
padded = np.pad(x, ((size//2, size//2), (size//2, size//2), (0, 0)))
middle = np.zeros_like(x); sparse_out = np.zeros((h, w, cout)); dense_out = np.zeros_like(sparse_out)
kernel = d[:, :, :, None] * p[None, None, :, :]
separable_macs = dense_macs = 0
for y in range(h):
for z in range(w):
patch = padded[y:y+size, z:z+size]
for c in range(cin):
middle[y, z, c] = np.sum(patch[:, :, c] * d[:, :, c]); separable_macs += size*size
for c in range(cout):
sparse_out[y, z, c] = middle[y, z] @ p[:, c]; separable_macs += cin
dense_out[y, z, c] = np.sum(patch * kernel[:, :, :, c]); dense_macs += patch.size
return sparse_out, dense_out, kernel, (separable_macs, dense_macs), (d.size+p.size, kernel.size)
def example():
x = np.arange(50, dtype=float).reshape(5, 5, 2)
d = np.zeros((3, 3, 2)); d[1,1,0] = 2; d[0,1,0] = 1; d[1,0,1] = -1; d[1,2,1] = 1
p = np.array([[1,2,-1],[0,1,3]], dtype=float)
return x, d, p
if __name__ == '__main__':
result = separable_and_dense(*example())
print('center output', result[0][2,2].tolist(), 'maximum discrepancy', float(np.max(np.abs(result[0]-result[1]))))
print('separable / dense MACs', result[3], 'weight slots', result[4])
x, d, p = example(); single = separable_and_dense(x,d,p[:,:1])
print('one output channel: separable / dense MACs', single[3])
not_separable = np.zeros((9,2)); not_separable[0,0] = 1; not_separable[1,1] = 1
print('single-input spatial/output matrix rank', int(np.linalg.matrix_rank(not_separable)),
'singular values', np.linalg.svd(not_separable,compute_uv=False).tolist())
Actual output:
center output [62.0, 128.0, -50.0] maximum discrepancy 0.0
separable / dense MACs (600, 1350) weight slots (24, 54)
one output channel: separable / dense MACs (500, 450)
single-input spatial/output matrix rank 2 singular values [1.0, 1.0]
The center output is (62,128,−50) in both implementations. The separable block uses 24 weight slots and 600 nominal MACs versus 54 and 1350. With only one output channel, it instead uses 500 MACs versus 450. The rank-two matrix at the end is a counterexample to unrestricted representational equivalence.
The intermediate depthwise activation has 50 values here. Its allocation and traffic are absent from a weight-count comparison; a fused kernel might handle them differently. This CPU reference is designed for inspection and is not a MobileNet benchmark or a speed-optimized implementation.
When the method fails
Grouping, bottlenecks and separable filters constrain how information moves. MobileNetV2’s inverted residual connects narrow representations while nonlinear processing happens in a wider internal space; its linear projection should not be summarized as “remove all activations.” The intended balance depends on accuracy and resource constraints.
Measure batch size, input resolution, precision, device, kernel availability, memory peak and end-to-end latency. Tiny per-channel operations can have poor utilization, and repeated small launches can dominate their arithmetic. Quantization, pruning and architecture changes are separate interventions and should be compared separately. A low-MAC candidate still needs a trained-model evaluation; the block equality here establishes neither accuracy nor energy savings.
Exercises with answers
- For k=3 and three output channels, what is the MAC ratio?
Answer 1: 1/3+1/9=4/9, matching 600/1350.
- Why does the one-output-channel example cost more?
Answer 2: The depthwise pass already performs the required spatial filtering, and the pointwise pass adds extra work.
- Can a rank-two spatial/output matrix be represented by one depthwise filter for that input channel?
Answer 3: No. Its factorized matrix has rank at most one.
- Does halving parameter count prove lower latency?
Answer 4: No. Activation traffic, operator shape, fusion and hardware utilization also affect latency.
Sources and next steps
MobileNet’s physical page 3 supplies the depthwise/pointwise cost decomposition. MobileNetV2’s physical page 3 motivates linear bottlenecks and inverted residuals. EfficientNet’s physical page 5 gives compound scaling and notes the difference between FLOPs and a hardware-specific latency target. The exact arrays, operation counter and rank counterexample are original. Continue with convolution and neural architecture search.
Make a prediction, then check
What does the depthwise/pointwise equivalence require in this example?
Learning objectives
- Compute parameter and MAC counts with explicit operator assumptions.
- Explain representational constraints and why latency requires measurement.
Prerequisites & connections
Explore related knowledge →References
- MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications — arXiv v1
Andrew G. Howard et al. · 2017 - MobileNetV2: Inverted Residuals and Linear Bottlenecks
Mark Sandler; Andrew Howard; Menglong Zhu; Andrey Zhmoginov; Liang-Chieh Chen · 2018 - EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks
Mingxing Tan; Quoc V. Le · 2019
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.
- Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
- Four focused CPython 3.12.4 tests passed per chapter, including independent finite differences, literal calculations, recurrence and convolution comparisons, permutation symmetry, closed-form limits and expressive counterexamples. All eight programs use NumPy 1.26.4. CPU teaching calculations, not framework or GPU benchmarks.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
Source locations checked:
- MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications — arXiv v1 · Physical page 3, Section 3.1 Equations 3–5: depthwise/pointwise filtering and nominal cost ratio; nonlinear MobileNet block distinguished.
- MobileNetV2: Inverted Residuals and Linear Bottlenecks · Physical page 3, Figures 2–3 and Sections 3.2–3.3: linear bottlenecks and inverted residual motivation.
- EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks · Physical page 5, Section 3.3 Equation 3: depth/width/resolution scaling and FLOPs versus hardware latency.
Related topics