EfficientNet: scaling a network within a compute budget
EfficientNet
Separate compound-scaling intuition from integer configurations; calculate B0–B2 costs and run an MBConv-SE block.
efficientnetFollow the data
You can spend a larger compute budget in at least three ways: add layers, add channels, or read larger images. These choices solve different problems. More pixels can preserve detail, but the model must still combine that detail usefully. More channels provide additional features at each layer, while extra layers add transformations. EfficientNet studies how to coordinate the three.
The proposal has two parts. First choose a baseline architecture, EfficientNet-B0, through the authors’ accuracy/compute search. Then scale its depth, width and resolution together. The scaling rule is a recipe for a family of candidate networks, not a proof that accuracy must increase for every dataset or budget. Tan and Le, 2019,§3–4
Before reading benchmark numbers, try an arithmetic prediction. Double a standard convolution’s input and output channels while keeping its spatial size fixed: the weight count and MACs rise about fourfold. Double both image sides while holding channels fixed: output positions rise about fourfold. Doubling both channels and image sides can therefore cost about sixteen times as much. Small-looking configuration changes can consume a large budget.
Definitions and calculations
Let scale depth, width and each image side. Treat layer counts and channels as continuous for this first approximation, keep kernel types fixed, and suppose ordinary channel-mixing convolutions dominate. Then:
The powers have different origins. Depth multiplies how many times we execute a layer. Width changes both its input and output channel axes. Resolution changes two spatial axes. This is a cost approximation, not an accuracy formula. A depthwise term is proportional to width rather than width squared; stems, classifiers, SE and stride rounding add further deviations.
The paper parameterizes these choices with a resource coefficient :
Its search reports . Their product in the constraint is 1.92027, close to two but not equal to it. Raising the product to gives an approximate compute multiplier. The paper explicitly notes rounding effects. These constants were selected for the studied baseline and procedure; they are not universal laws of visual recognition. Equation 3 and two-step search
Actual networks need integer channels and repeats. The fixed official implementation rounds a target channel count to a multiple of 8, then adds8 if rounding down would remove more than 10%. It rounds the number of stage repeats upward. A depth factor of 1.1 turns repeat counts 1,2,3,4 into 2,3,4,5; a tiny continuous change can add a complete block. Official implementation, fixed2020 commit
The same source specifies named configurations explicitly:
| Model | Width | Depth | Input side | Classifier dropout setting |
|---|---|---|---|---|
| B0 | 1.0 | 1.0 | 224 | 0.2 |
| B1 | 1.0 | 1.1 | 240 | 0.2 |
| B2 | 1.1 | 1.2 | 260 | 0.3 |
| B7 | 2.0 | 3.1 | 600 | 0.5 |
Use this table when reproducing those named versions. Plugging into the idealized formula is not an exact recipe for B1. The code version is pinned and includes later additions; this article uses only the stated B0–B7 configuration entries, not every model in that repository.
Run the small model
B0’s main operator is MBConv with squeeze-and-excitation, abbreviated SE. In the implementation read here, an optional1×1 expansion is followed by depthwise convolution, a channel gate, and a linear1×1 projection. Expansion and depthwise outputs pass through BN and Swish; projection has BN but no activation. A matching stride-one block can add its input. This differs from simply taking a MobileNetV2 block unchanged: the activation and SE matter. Official builder and MBConv code
SE first averages each expanded channel over space. A small pair of learned projections turns this summary into one sigmoid gate per expanded channel, then multiplies the whole feature map by that gate. If has channels, write:
The notation uses column vectors; the NumPy program uses equivalent row-vector products. In the pinned code, the SE hidden width is based on the block’s input width , not its expanded width : . For input 8 channels and expansion6, the gate works on 48 channels but its hidden width is 2. Using12 would build a different model. If both excitation weights and bias are zero, every gate equals0.5, not zero.
Below, plan counts the specified B0/B1/B2 architectures without allocating their activations. mbconv actually runs one small MBConv-SE block. It uses original NumPy code, deterministic random weights, unit-statistic inference BN with epsilon0.001, and symmetric padding. At expansion1 the expansion convolution is omitted. Training dropout and stochastic depth are not executed.
"""Original cost planner and one small EfficientNet-style MBConv-SE block.
No full B0 training/inference. Unit-statistic inference BN; symmetric padding.
"""
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 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 sigmoid(x):
return np.exp(-np.logaddexp(0,-np.asarray(x,dtype=float)))
def swish(x):
return x*sigmoid(x)
def round_channels(channels,width=1.,divisor=8):
channels,divisor=positive(channels),positive(divisor)
if not np.isfinite(width) or width<=0:
raise ValueError('width must be positive and finite')
raw=channels*width
result=max(divisor,int(raw+divisor/2)//divisor*divisor)
return result+divisor if result<.9*raw else result
def repeats(count,depth=1.):
count=positive(count)
if not np.isfinite(depth) or depth<=0:
raise ValueError('depth must be positive and finite')
return math.ceil(count*depth)
# (kernel, expansion, output channels, repeat count, first-block stride)
STAGES=((3,1,16,1,1),(3,6,24,2,2),(5,6,40,2,2),(3,6,80,3,2),
(5,6,112,3,1),(5,6,192,4,2),(3,6,320,1,1))
def plan(width=1.,depth=1.,resolution=224,classes=1000):
resolution,classes=positive(resolution),positive(classes)
c=round_channels(32,width);side=(resolution+1)//2
params=3*3*3*c+2*c;macs=side*side*3*3*3*c
stages=[]
for k,t,out,n,stride in STAGES:
out=round_channels(out,width);n=repeats(n,depth)
for j in range(n):
e=t*c;next_side=(side+(stride if j==0 else 1)-1)//(stride if j==0 else 1)
if t!=1:
params+=c*e+2*e;macs+=side*side*c*e
params+=k*k*e+2*e;macs+=next_side*next_side*k*k*e
reduced=max(1,int(c*.25)) # Relative to block INPUT, not expanded width.
params+=2*e*reduced+reduced+e;macs+=2*e*reduced
params+=e*out+2*out;macs+=next_side*next_side*e*out
c,side=out,next_side
stages.append((c,n,side))
head=round_channels(1280,width)
params+=c*head+2*head+head*classes+classes
macs+=side*side*c*head+head*classes
return dict(stages=stages,blocks=sum(s[1] for s in stages),parameters=params,macs=macs)
def make_block(cin,cout,expansion=6,kernel=3,seed=5):
cin,cout,expansion,kernel=map(positive,(cin,cout,expansion,kernel))
if kernel%2!=1:raise ValueError('odd kernel required')
rng=np.random.default_rng(seed);e=cin*expansion;r=max(1,int(cin*.25))
return dict(expand=None if expansion==1 else rng.normal(0,.1,(cin,e)),
dw=rng.normal(0,.1,(kernel,kernel,e)),project=rng.normal(0,.1,(e,cout)),
reduce=rng.normal(0,.1,(e,r)),reduce_bias=np.zeros(r),
excite=rng.normal(0,.1,(r,e)),excite_bias=np.zeros(e))
def se(x,reduce,reduce_bias,excite,excite_bias):
x=image(x);pooled=x.mean(axis=(0,1))
hidden=swish(pooled@reduce+reduce_bias)
return x*sigmoid(hidden@excite+excite_bias)
def mbconv(x,weights,stride=1):
x=image(x);z=x
if weights['expand'] is not None:
z=swish(pointwise(z,weights['expand'])/np.sqrt(1+1e-3))
z=swish(depthwise(z,weights['dw'],stride)/np.sqrt(1+1e-3))
z=se(z,weights['reduce'],weights['reduce_bias'],weights['excite'],weights['excite_bias'])
y=pointwise(z,weights['project'])/np.sqrt(1+1e-3)
return x+y if stride==1 and x.shape[2]==y.shape[2] else y
if __name__=='__main__':
for name,args in [('B0',(1.,1.,224)),('B1',(1.,1.1,240)),('B2',(1.1,1.2,260))]:
p=plan(*args);print(name,{k:p[k] for k in ('blocks','parameters','macs')})
print('continuous phi=1 cost factor:',round(1.2*1.1**2*1.15**2,6))
x=np.arange(5*5*4,dtype=float).reshape(5,5,4)/100
w=make_block(4,4,2);print('small block shape:',mbconv(x,w).shape)
print('SE width:',w['reduce'].shape[1])
With Python3.12.4 and NumPy1.26.4:
B0 {'blocks': 16, 'parameters': 5288548, 'macs': 385814752}
B1 {'blocks': 23, 'parameters': 7794184, 'macs': 686802832}
B2 {'blocks': 23, 'parameters': 9109994, 'macs': 993561872}
continuous phi=1 cost factor: 1.92027
small block shape: (5, 5, 4)
SE width: 1
The parameter count includes BN affine terms, SE weights/biases and classifier bias; convolution biases and BN running buffers are excluded. MACs include convolution, SE projections and the classifier, but exclude BN, activation, pooling, gating multiplies and residual addition. B0 has 5,288,548 parameters under these conventions. The planner obtains385,814,752 MACs; this is an explicit arithmetic ledger, not a full FLOP count or measured latency.
What the model does not establish
More computation can be wasted on uninformative pixels or overfitting. The scaling equations do not know the label noise, dataset size, transfer-learning setup or deployment bottleneck. The paper’s search objective uses accuracy and a FLOPS budget; the authors explicitly distinguish it from optimizing latency for a particular device. EfficientNet§4
The B0 table in the paper and a later official implementation are different kinds of evidence. The paper explains the design, while the pinned block strings specify precise strides and repeat counts. Here, those strings give first-block strides1,2,2,2,1,2,1 for the seven MBConv stages. Only the first block in each stage downsamples; later repeats use stride one. Do not infer stride from neighboring rows without checking the actual definition.
Our small block is not a trained EfficientNet. It omits batch-statistic estimation, optimization, augmentation, pretrained weights and stochastic regularization. Its symmetric padding can have different alignment from TensorFlow SAME at even dimensions with stride two. The shape/MAC planner follows the rounded output sizes, but that does not make the numerical forward pass bit-identical to the official model.
Nor does parameter size specify peak memory. Higher resolution expands intermediate activations even when weights do not change. A narrow but deep network may launch many small operators. Use model evaluation to separate accuracy, MACs, peak memory and latency; use MobileNet to inspect the underlying factorized operators.
Exercises with answers
1. Predict a continuous cost multiplier
Answer: With d=2,w=1.5,r=1, ordinary convolution cost scales approximately by 2×1.5²=4.5. This is not a predicted accuracy improvement, and depthwise terms obey another width dependence.
2. Round channels and repeats
Answer: A target24×1.1=26.4 rounds to 24 channels, which is within the 10% safeguard. A base repeat count2 scaled by 1.1 rounds upward to 3. Integer models cannot vary continuously.
3. Which width defines the SE bottleneck?
Answer: With input 8 channels and expansion6, expanded width is 48 but the fixed implementation uses a hidden width max(1,floor(8/4))=2. The output gate still has 48 entries, one per expanded channel.
4. Why can B1 differ from an exact doubling?
Answer: The named configuration uses width 1.0,depth1.1 and input 240. Stage repeats are rounded upward, and different operators scale differently. Use the declared configuration and operation ledger; neither its name nor phi=1 guarantees exactly twice B0 MACs.
Sources and next steps
Read the original scaling formulation and equation 3, then the baseline/search discussion in§4. Treat the reported coefficients as the result of that experiment, not an explanation of every later model family. ICML2019 paper
The second source is the TensorFlow TPU repository at commita2d5e429b9c57e0e63e6230f05046e4c0e4318f7, dated 2020-12-15. The checked locations are efficientnet_builder.py for named configurations, stage strings and defaults, and efficientnet_model.py for rounding, SE and projection/shortcut ordering. Its Apache-2.0 license was checked; the NumPy teaching implementation is original, with no upstream code execution or redistribution. Fixed source tree
For a project, hold the data split and evaluation protocol fixed while changing one dimension and then a coordinated combination. Report the actual integer architecture and measured resources alongside accuracy. A smooth formula becomes useful engineering only after those discrete choices are visible.
Make a prediction, then check
The SE hidden width uses input8 channels and expansion6. What hidden width does the pinned code select?
Learning objectives
- Derive approximate depth-width-resolution costs and identify assumptions.
- Construct integer configurations using declared rounding rules.
- Compute and test MBConv-SE behavior separately from benchmark claims.
Prerequisites & connections
Explore related knowledge →References
- EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks — ICML2019 scaling method
Mingxing Tan; Quoc V. Le · 2019 - TensorFlow TPU EfficientNet — fixed commit a2d5e429 (2020-12-15)
TensorFlow Authors · 2020
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 independent parameter shape enumeration, integer width/repeat rules, B0 stage output shapes, SE hand calculation/input-based hidden width, zero-residual behavior and Swish finite differences. 9 article checks; frozen official code configuration differs from idealized phi recipe, MACs not latency.
- 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:
- EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks — ICML2019 scaling method · ICML2019 PDF physical pages3–5, sections3–4, equation3 and table1 visually checked.
- TensorFlow TPU EfficientNet — fixed commit a2d5e429 (2020-12-15) · Pinned a2d5e429 (2020-12-15): builder lines35–49 and172–203; model lines106–133, SE construction/call and MBConv projection/skip passages.
Related topics