Sub topic 2
Choosing an efficient architecture for your device
This chapter assumes you can train or fine-tune a CNN in PyTorch or TensorFlow. It also assumes you know what a convolution, a channel, and a float32 tensor are. The chapter covers how to shortlist architectures for a phone or edge board, which numbers to trust, and which mistakes cause the most wasted effort.
Start from the budget, not the model
The previous chapter set out the limits of edge inference. Before you look at any architecture, turn those limits into numbers for your product:
- Latency budget: for example, 33 ms per frame for a 30 fps camera preview. If the model shares the frame budget with preprocessing and drawing, it gets less.
- Memory budget: model file size, plus the peak activation memory while it runs. Both count against the app's memory limit.
- Accuracy floor: the lowest metric (top-1, mAP, mIoU) the feature can tolerate on your data.
- Operator support: the operators your target runtime and accelerator can run. This is covered in later chapters.
An architecture is a candidate only if it can plausibly meet all four. Choosing the most accurate model that fits is a good rule, but only after you have measured the fit.
Why efficient architectures are efficient
Most mobile-oriented CNNs rely on the same few ideas.
Depthwise separable convolutions
A standard 3x3 convolution mixes spatial and channel information in one step. A depthwise separable convolution splits this into two steps:
- A depthwise 3x3 convolution filters each channel on its own.
- A pointwise 1x1 convolution mixes channels.
For kernel size K, Cin input channels and Cout output channels, the cost relative to a standard convolution is about 1/Cout + 1/K². With K=3 and Cout=128, that is roughly 0.12, so the layer needs about 8x fewer multiply-accumulates (MACs). This is the core of MobileNet.
Inverted residuals and linear bottlenecks
MobileNetV2 expands the channels with a 1x1 convolution, applies the depthwise convolution in the wide space, then projects back to a narrow tensor. The skip connections link the narrow tensors, which keeps stored activations small.
Squeeze-and-excitation and new activations
MobileNetV3 and EfficientNet add squeeze-and-excitation (SE) blocks, which reweight channels using a global pooled summary. They also use hard-swish or swish activations. These improve accuracy per MAC. They can also be awkward on some accelerators and for quantization, as covered below.
Scaling knobs
Most families let you trade accuracy for cost in two ways:
- Width multiplier: scales the channel count, for example MobileNet at 0.5x, 0.75x or 1.0x.
- Input resolution: a 160x160 input costs about half the MACs of 224x224, since cost scales with pixel count.
Resolution is often the cheapest knob. It can hurt small-object detection badly, though.
Compare candidates
The figures below are approximate ImageNet-1k numbers at 224x224 from commonly published models. Your own task will give different accuracy.
| Model | Params | MACs | ImageNet top-1 | Notes |
|---|---|---|---|---|
| MobileNetV3-Small | ~2.5M | ~56M | ~67% | Very cheap. Uses hard-swish and SE. |
| ShuffleNetV2 1.0x | ~2.3M | ~146M | ~69% | Designed around memory access cost. |
| MobileNetV2 | ~3.5M | ~300M | ~72% | Simple operators. Quantizes well. |
| MobileNetV3-Large | ~5.5M | ~220M | ~74% | Strong default for phones. |
| EfficientNet-B0 | ~5.3M | ~390M | ~77% | Accurate. Uses swish and SE. |
| ResNet-50 | ~25.6M | ~4.1G | ~76% | Server baseline. Shown for scale. |
Two things stand out. MobileNetV3-Large has fewer MACs than MobileNetV2 and is more accurate. EfficientNet-B0 is more accurate again but costs more.
MACs are not latency
The common mistake is ranking models by MACs or parameter count. Latency depends on several other factors:
- Memory traffic. Depthwise layers do little arithmetic per byte moved, so they are often memory-bound. A model with fewer MACs can be slower than one with more.
- Operator support. If an accelerator lacks an operator, the runtime falls back to the CPU. Data then moves between processors, which can erase the accelerator's gain.
- Activation size. The peak tensor size, usually in early high-resolution layers, sets the working memory. Parameter count does not show it.
- Quantization behavior. Some blocks lose more accuracy than others when converted to int8.
- Hardware specifics. Some NPUs run standard and 1x1 convolutions very fast but depthwise convolutions poorly.
The efficient model for one device may not be efficient on another. Treat published latency tables as a way to shortlist models, and measure on the target device.
import time
import torch
import torchvision.models as models
candidates = {
"mobilenet_v3_small": models.mobilenet_v3_small,
"mobilenet_v3_large": models.mobilenet_v3_large,
"mobilenet_v2": models.mobilenet_v2,
"shufflenet_v2_x1_0": models.shufflenet_v2_x1_0,
"efficientnet_b0": models.efficientnet_b0,
"resnet50": models.resnet50,
}
torch.set_num_threads(4)
x = torch.randn(1, 3, 224, 224)
for name, ctor in candidates.items():
model = ctor(weights=None).eval() # random weights: fine for cost, not accuracy
params_m = sum(p.numel() for p in model.parameters()) / 1e6
times = []
with torch.inference_mode():
for _ in range(5): # warm-up
model(x)
for _ in range(30):
start = time.perf_counter()
model(x)
times.append((time.perf_counter() - start) * 1000)
times.sort()
print(f"{name:20s} {params_m:5.1f}M params median {times[len(times) // 2]:7.1f} ms")This script runs on a desktop CPU in float32 PyTorch. Use it for a quick first look, but expect the ranking to change on a phone with an int8 model and a delegate. Later chapters cover on-device benchmarking properly.
Choose by task
Classification
Start with MobileNetV3-Large or EfficientNet-Lite-style models, and drop to MobileNetV3-Small when the budget is tight. You will usually fine-tune from ImageNet weights, so check that the framework provides them.
Detection
A detector is a backbone plus a head, and the head matters. Common mobile choices are SSD with a MobileNet backbone, EfficientDet-Lite, and small YOLO variants. Check these points:
- Whether post-processing such as non-maximum suppression (NMS) is inside the exported graph. Many runtimes handle it poorly, so you may need to run it in app code.
- The input resolution. Detection usually needs more than 224x224, such as 320 or 640, so cost rises quickly.
- The license. Some popular detector code carries copyleft terms that may not suit a shipped app.
Segmentation
Lightweight options include DeepLabV3 or LR-ASPP heads on a MobileNet backbone. The output is often at full resolution, so the final upsampling and the output tensor size can dominate memory.
Transformers and hybrids
MobileViT, EfficientFormer and small vision transformers can be accurate. Attention uses operators such as batched matrix multiplies, softmax, layer normalization and GELU. These are less widely supported than convolutions on mobile accelerators and are more sensitive to int8 quantization. Pure CNNs remain the lowest-risk choice for a first deployment. Try a hybrid when you have measured that it wins on your device.
Design for quantization and delegates
You will probably quantize the model, so choose with that in mind:
- ReLU and ReLU6 quantize more cleanly than swish and hard-swish, because they have bounded or simple ranges.
- EfficientNet-Lite exists because the standard EfficientNet's SE blocks and swish activations hurt mobile accelerator support and quantization. The Lite variants remove them.
- Unusual operators, such as custom activations or dynamic shapes, are the usual cause of CPU fallback. Prefer architectures built from standard convolutions, pooling and simple elementwise operations.
Check the operator list of a candidate against your runtime before you spend time on fine-tuning.
A selection workflow
In words:
- Write the budgets as numbers.
- Shortlist two or three architectures from different families, so that one family's quirks do not decide the result.
- Export the pretrained weights and measure latency on the device with the real runtime. At this point accuracy on your task does not matter yet.
- Fine-tune only the models that meet the latency budget.
- Quantize, then check accuracy on your own validation set.
- If accuracy falls short, pick a larger model or revisit the quantization method.
Common errors
- Ranking by MACs or parameters. Use them to shortlist only.
- Trusting the ImageNet number. A model that is 3 points better on ImageNet may be no better on your data. Evaluate on your own validation set.
- Benchmarking on a desktop. Memory bandwidth, thread behavior and instruction sets differ. Results do not transfer.
- Cutting resolution without checking the data. Small objects and fine texture disappear first.
- Ignoring peak memory. A model with a small file can still run out of memory because of large early activations.
- Mixing up model variants. "MobileNetV3" and "EfficientNet" have several variants with different operators. Name the exact variant in your notes.
- Picking the newest model. New architectures often use operators that mobile runtimes do not support yet.
Exercise
Model A has 300M MACs and runs in 25 ms on your phone's CPU. Model B has 220M MACs but runs in 31 ms. Give two plausible reasons, and say what you would check first.
Show answer
Plausible reasons: Model B uses more memory-bound layers (for example depthwise convolutions and SE blocks), so it moves more data per MAC. It may also use operators such as hard-swish that the runtime executes slowly or does not fuse, or its activations may be larger. Check first by profiling both models per operator on the device, looking for layers that dominate the time, then confirm the exact runtime, thread count and delegate are identical for both runs.
Exercise
You need a detector that runs at 30 fps on an NPU, and your shortlist includes a standard EfficientNet-based model and an EfficientNet-Lite-based one. Which do you try first, and why?
Show answer
Try the EfficientNet-Lite-based model first. It removes squeeze-and-excitation and swish, which are the parts most likely to be unsupported or to quantize badly on mobile accelerators, so it is more likely to run fully on the NPU without CPU fallback. Confirm this by exporting and running both on the device.