Embedded Machine LearningPhD course

Session 3 · 90 minutes · lecture · page 1 of 2

Classical versus deep learning: models, architectures and their cost

A self-contained primer on machine learning for those who need it, then the two model families side by side: classical models with their inference cost, neural networks built up from a single neuron, and the efficient architectures designed for small devices. Compression continues on page 2.

Duration90 min, with a short break — this page and page 2
PrerequisitesSessions 1–2; derivatives and matrix products
SlidesPDF · HTML
Page 2Compression
Learning outcomes
  • Explain supervised learning as loss minimisation, and the roles of training, validation and test data.
  • Recognise under- and overfitting, and explain gradient descent and the effect of the learning rate and of feature scaling.
  • Evaluate a classifier with a confusion matrix, precision, recall and calibration, under class imbalance.
  • Give inference-time cost models (memory, operations) for logistic regression, SVMs, k-NN, trees and ensembles, and choose among them.
  • Build a neural network from neurons and layers; count the parameters, MACs and activation memory of dense and convolutional layers.
  • Explain why depthwise-separable convolutions, inverted residuals and compound scaling are efficient — and when they are not.
  • Decide, for a stated task and budget, between a classical and a deep model, with reasons.
Timing plan · 90 minutes (both pages)
  1. 0–5Where we are in the pipeline; the question of the session: which model, and how small can it be made?
  2. 5–18Primer: learning as loss minimisation; splits; overfitting; gradient descent (interactive).
  3. 18–25Measuring a classifier: confusion matrix, threshold under imbalance (interactive), calibration.
  4. 25–37Classical models and their inference cost: the regime question, SVMs, trees and forests.
  5. 37–45Neural networks from one neuron; convolution; parameters versus activations.
  6. 45–50Break.
  7. 50–58Depthwise-separable convolution, efficient architecture families, NAS in one picture; classical or deep?
  8. 58–74Compression I — quantization: number formats, the affine map, integer-only inference, calibration (interactive).
  9. 74–84Compression II — pruning and when sparsity pays (interactive); distillation and temperature (interactive).
  10. 84–90A compression recipe; link to presentation topics A–C.
In one sentence

A model is a parameterised function fitted to examples; on a small device the question is never only how accurate it is, but how many bytes its parameters and intermediate results occupy and how many operations it costs per decision — and both model families can be made to win on that question.

Part AA machine-learning primer

If you have trained models before, skim this part and go to Part B. If you have not, read it carefully: it is written for engineers and scientists who know calculus and linear algebra but have not studied machine learning.

3.1Learning from examples

Machine learning Supervised labelled pairs (x, y) Unsupervised x only Self-supervised labels made from x Reinforcement reward from actions classification keywords, falls, ECG regression battery life left clustering group machine states dim. reduction PCA before a tiny MLP anomaly detection AE on vibration pre-training masked / contrastive then fine-tune few labels needed control policies drone, HVAC, motor on-device: rare sample-hungry, risky Almost every deployed embedded model today is supervised classification; anomaly detection is the main unsupervised exception.
Fig 3.1The main families of machine learning, each with an embedded example. They differ in what the training signal is: a human-provided label (supervised), structure in the inputs alone (unsupervised), a label manufactured from the input itself (self-supervised), or a reward obtained by acting (reinforcement). The inference-time cost depends on the model, not the paradigm — but the paradigm decides how much labelled data you must collect, which is often the most expensive part of an embedded project.

In supervised learning we are given a training set of N examples {(xi, yi)}: inputs (feature vectors, windows, spectrograms) and the correct outputs (labels). We choose a model family f(x; θ) and a loss function ℓ(ŷ, y) that measures how bad a prediction ŷ is when the truth is y. Training means solving

θ* = argmin_θ (1/N) Σᵢ ℓ( f(xᵢ; θ), yᵢ ) + λ · R(θ)

The first term is the average loss on the training data (the empirical risk); the second is an optional regulariser that prefers simpler parameter values (for example R(θ) = ‖θ‖², "weight decay"), weighted by a hyper-parameter λ chosen by the engineer, not learned.

Two losses cover most of this course:

  • Regression (predict a number): mean squared error, ℓ = (ŷ − y)².
  • Classification (predict one of C classes): the model outputs C scores ("logits") z1…C, turned into probabilities by the softmax pc = ezc / Σk ezk, and the loss is the cross-entropy ℓ = −log py — small when the model puts high probability on the correct class. (The distillation section on page 2 reuses the softmax with a "temperature".)

Unsupervised learning drops the labels and looks for structure — clusters, low-dimensional directions (PCA in Session 2), or a model of "normal" data against which anomalies stand out. Self-supervised learning manufactures labels from the data itself (predict a masked part of the input) and is how large models are pre-trained before being fine-tuned with few labels. Reinforcement learning learns from rewards obtained by acting; it is rare on embedded devices because it needs many, sometimes unsafe, trials.

3.2Generalisation and honest evaluation

Minimising the training loss is easy; the goal is low loss on new data. A model with enough capacity can memorise its training set — including the noise in it — and do badly on anything else. This is overfitting; its opposite, a model too simple to capture the real pattern, is underfitting.

degree 1 — underfit train error 0.118 test error 0.173 degree 4 — about right train error 0.034 test error 0.035 degree 9 — overfit train error 0.022 test error > 10 (off the chart) teal: 12 training points · faint: 40 test points · dashed: the true function · copper: the fitted model
Fig 3.2Under- and overfitting with the simplest possible model family. Training error falls monotonically as the polynomial degree rises; test error falls and then explodes, because the high-degree model spends its capacity on the noise in twelve points. The same U-shape governs neural networks, and it is why every reported number must come from data the model was not fitted on. Model compression interacts with this directly: a smaller model has less capacity to overfit, which is one reason pruned or distilled models sometimes generalise slightly better.

Which model generalises well from limited data depends on its inductive bias: the assumptions built into the model family before it sees any data — that the decision boundary is linear, that nearby inputs have similar outputs, that a pattern means the same thing wherever it occurs in an image. A good inductive bias for the task is worth a great deal of data, which is why a convolutional network learns images from far fewer examples than a fully connected one, and why hand-designed features can let a tiny classical model compete.

Because training error is an optimistic estimate of real-world error, data is divided before any modelling starts. The model's parameters are fitted on the training set; every choice the engineer makes — features, model family, hyper-parameters, when to stop training, which checkpoint to deploy, how far to compress — is made by looking at the validation set; the test set is used once, at the end, to report the number. With small datasets, k-fold cross-validation rotates the validation role across the data so that every example is used for both fitting and validation.

Hold-out split train 70 % validation 15 % test 15 % fit parameters on train · choose hyper-parameters on validation · touch test once, at the end 5-fold cross-validation fold 1 fold 2 fold 3 fold 4 fold 5 every example is validated exactly once; report mean ± spread over folds Grouped (subject-wise) split — mandatory for windowed sensor data train: subjects A–D test: subjects E–F Overlapping windows from one recording are near-duplicates: a random split leaks them across the line.
Fig 3.3How data is divided so that the reported accuracy means something. The test set estimates performance on data the model has never influenced; the validation set absorbs all the choices you make along the way. For sensor data cut into overlapping windows, a random split is a trap: adjacent windows share most of their samples, so the "test" accuracy measures memorisation. Split by subject, device or recording session instead.

The trade-off between under- and overfitting has a classical formalisation, the bias–variance decomposition, which appears with the tree ensembles in Part B (Fig 3.11). For now the practical rules are: more data reduces overfitting, and so do regularisation, early stopping and data augmentation.

3.3Optimisation: gradient descent

For a model with millions of parameters there is no closed-form solution to the training problem. Instead we start from random parameters and repeatedly move them a small step in the direction that reduces the loss fastest — against the gradient ∇θL, the vector of partial derivatives of the loss with respect to each parameter:

θ ← θ − η · ∇_θ L(θ)

The step size η is the learning rate, the single most important hyper-parameter in deep learning. In practice the gradient is estimated on a small random mini-batch of examples rather than the whole training set (stochastic gradient descent, SGD), which makes each step cheap and adds a useful amount of noise; adaptive variants such as Adam scale the step per parameter. One pass over the training set is an epoch; training typically takes tens to hundreds of epochs.

minimum start loss contours: steep in w₂, shallow in w₁ 0 10 20 30 40 10⁻⁴ 10⁻² 1 10² iteration loss (log) η = 0.02 too small η = 0.14 good η = 0.168 too large
Fig 3.4Gradient descent — the engine under almost all of machine learning. Each step moves the parameters against the gradient, scaled by the learning rate η. On this elongated bowl the largest stable η is set by the steepest direction (here 2/12 ≈ 0.167): just below it the iterates zig-zag across the valley, above it they diverge, and far below it they barely move along the shallow direction. Feature normalisation (Session 2) makes the bowl rounder and training faster for exactly this reason.
InteractiveGradient descent — learning rate and conditioning
stability limit 2/κ–
final loss–
steps to loss < 10⁻³–
…

Loss L(w) = ½(w₁² + κ·w₂²), starting at (−3, 0.5). κ is the ratio of the steepest to the shallowest curvature; standardising features (Session 2) pushes it towards 1.

The widget makes two points that matter later in the course. First, the learning rate has a hard upper limit set by the steepest direction of the loss surface; beyond it, training diverges. Second, when the surface is much steeper in some directions than others (a large condition number κ), progress in the shallow directions is slow. Unscaled input features are one cause of a large κ — which is why the normalisation of Session 2 makes training faster, not just more accurate. Quantization-aware training (page 2) is gradient descent through a rounding function, with its own complications.

3.4Measuring a classifier

predicted event no event actual event no event 40 TP true positive 10 FN missed event 60 FP false alarm 890 TN true negative recall (sensitivity) TP / (TP + FN) 40 / 50 = 0.80 precision TP / (TP + FP) 40 / 100 = 0.40 F1 2PR / (P + R) 0.53 specificity TN / (TN + FP) 890 / 950 = 0.94 accuracy (TP + TN) / all 930 / 1000 = 0.93 A detector that always says "no event" scores accuracy 0.95 — better than this one, and useless.
Fig 3.5Reading a classifier's errors. With 50 events in 1000 windows, accuracy is dominated by the easy negatives and is almost meaningless; precision ("when it fires, is it right?") and recall ("of the real events, how many did it catch?") describe what a user experiences. Which error is worse is an application decision — a missed fall versus a false alarm — and it is made by moving the decision threshold, which is the subject of the interactive figure below.

A classifier that outputs a score is turned into a decision by a threshold. Moving the threshold trades false alarms against missed events, and how good a trade is available depends on how well the classes are separated and — crucially for embedded detection tasks — on how rare the events are. Precision depends on prevalence; recall does not. A detector evaluated on a balanced test set and deployed where events are a hundred times rarer will see its precision collapse without any change to the model.

InteractiveDecision threshold — precision and recall under class imbalance
TP / 1000–
FP / 1000–
FN / 1000–
recall–
precision–
accuracy–
F1–
…

Scores of negatives ~ N(0, 1), positives ~ N(d′, 1). Curves are scaled by prevalence, so their areas are the expected counts. The detector fires to the right of the threshold.

Sweeping the threshold over all values traces two standard curves. The ROC curve plots recall (the true-positive rate) against the false-positive rate FP/(FP+TN); the area under it, AUC, is the probability that a random positive scores higher than a random negative, and is 0.5 for guessing and 1 for a perfect ranking. The precision–recall curve plots precision against recall and, unlike the ROC curve, reacts to class imbalance. The widget's d′ ("d-prime") is the distance between the two class means in units of their standard deviation — a one-number summary of how separable the scores are. Finally, a classifier is calibrated if, among all inputs to which it assigns probability 0.8, about 80 % are positive; a reliability diagram plots the predicted against the observed frequency, and the expected calibration error is the average gap between them. The section below develops these ideas.

3.5Calibration and the right metric

A model's score is not a probability unless it was trained or post-processed to be one. SVM decision values certainly are not; boosted ensembles are typically over-confident; random forests are under-confident near the extremes. Two standard remedies: Platt scaling fits a one-dimensional logistic regression p = σ(as + b) to the scores on held-out data; isotonic regression fits a non-decreasing step function, which is more flexible and needs more data. Measure the result with a reliability diagram and the expected calibration error, not with accuracy.

Calibration is not a cosmetic step in this course: the cascade of §1.8 requires a threshold with a known operating point, and thresholds are only transferable across deployments if the scores are calibrated.

0 0.5 1 0 0.5 1 predicted probability observed frequency boosted ensemble pushes scores to 0 and 1 random forest averaging pulls them to 0.5 Neither is wrong about ranking. Both are wrong about probability. A cascade threshold set on an uncalibrated score does not transfer between deployments. Fix with Platt scaling or isotonic regression on held-out data — then re-measure.
Fig 3.6A reliability diagram. A perfectly calibrated model lies on the diagonal: of all the windows it scores 0.3, about 30 % should be positive. Boosted ensembles bow below it, forests bow above it, and both still rank correctly — which is why accuracy and AUC will not reveal the problem. Calibration matters here because every cascade in this course thresholds a score, and a threshold is only portable across devices and deployments if the score means the same thing everywhere.

Metrics for always-on detection. Accuracy is meaningless when the positive class occupies 0.1 % of windows. Use the precision–recall curve rather than the ROC curve (the ROC's false-positive rate is diluted by the enormous negative class), and report the operating point in application terms: false alarms per hour at a stated recall is the standard in keyword spotting and acoustic event detection, because it is the quantity the user experiences.

0 0.5 1 0 0.5 1 false-positive rate true-positive rate AUC ≈ 0.968 FPR 7.8 % ROC — looks excellent 0 0.5 1 0 0.5 1 recall precision chance = 1 % precision 10 % at 90 % recall precision–recall — tells the truth 1 % prevalence · 300 positives among 30 300 windows · synthetic Gaussian scores An FPR of 7.8 % sounds small — it is 2335 false alarms for 270 true detections.
Fig 3.7Why always-on detection is never reported as accuracy or AUC. Both panels describe the identical detector on the identical data. The ROC curve divides false positives by the enormous negative count, which dilutes them into invisibility; the precision–recall curve does not. At the operating point with 90 % recall this detector raises about 9 false alarms for every true one (precision 10 %) — an unusable product, although its AUC is 0.97 and its accuracy, 92 %, sounds respectable. A detector that never fires would score 99 %.

Part BClassical models under constraints

"Classical" here means everything that is not a deep neural network: linear models, kernel methods, nearest neighbours, decision trees and their ensembles. On microcontrollers they remain widely deployed, and for good reasons.

3.6The regime question

Classical models win when at least one of these holds:

  • Little data. With a few hundred labelled windows, a regularised linear model or a small forest generalises better than a network you cannot regularise into submission.
  • Extreme memory limits. A depth-6 boosted ensemble of 30 trees fits in a few kilobytes of flash and needs almost no RAM.
  • Deterministic, data-independent latency. A tree's latency varies with the path taken; a linear model's does not vary at all. In hard real-time contexts this matters more than mean latency.
  • Interpretability or certification. Medical and automotive certification regimes are far more comfortable with a model whose decision can be printed as a rule.
  • Good handcrafted features already exist. If domain physics gives you the right 20 features, the representation-learning advantage of a network evaporates.

They lose when the raw input is high-dimensional and the useful features are unknown — images, raw audio, and anything where the relevant structure is compositional.

logistic regression train accuracy 55 % k-NN, k = 5 train accuracy 98 % decision tree, depth 4 train accuracy 100 % RBF SVM train accuracy 99 % Same data, same features, four different inductive biases. The tree's boxes are cheap at inference — a handful of comparisons — but they can only ever be boxes. The RBF SVM draws the right shape and pays for it with stored support vectors. Choosing a model family is choosing which shapes are cheap to express.
Fig 3.8Inductive bias made visible. No amount of tuning will let logistic regression separate these classes, because the true boundary is not a line in this feature space — though it becomes one if you add the feature x²+y², which is exactly the point of the kernel trick. Note also what the picture does not show: the tree costs about four comparisons per prediction, the SVM costs one kernel evaluation per stored support vector, and the picture treats them as equals.

3.7Inference-time cost models depth

For D features, C classes, N training samples:

ModelInference arithmeticParameter memoryWorking RAMEmbedded remark
Logistic regressionC·D MACsC·(D+1)O(C)Trivially quantizable; the reference baseline
Gaussian naive BayesC·D mul + add (log domain)2·C·DO(C)Robust with tiny data; independence assumption rarely true
k-NN (brute force)N·D MACsN·DO(k)No training, prohibitive memory; needs condensation or product quantization
Linear SVMD MACs per binary classifier (×C one-vs-rest, ×C(C−1)/2 one-vs-one)D+1O(1)Same cost as logistic regression for one-vs-rest, different loss
Kernel SVM (RBF)nSV·D MACs + nSV expnSV·DO(nSV)Cost grows with dataset size — the key failure mode
Decision tree, depth dd comparisons~2d nodesO(1)Compiles to nested if; nanoseconds per inference
Random forest, T treesT·d comparisonsT·2d nodesO(1)Embarrassingly parallel; thresholds quantize to int8 well
Gradient-boosted stumps, T roundsT comparisons + T adds~3TO(1)Often the best accuracy-per-byte on tabular sensor features

Table 3.1 — Inference cost of classical models. Note the structural difference from neural networks: two of these families cost comparisons, not multiplications, and therefore do not benefit from a MAC accelerator at all. A device chosen for its NPU may run a forest no faster than a device without one.

The point of Table 3.1

The dominant term differs by family: D for linear models, N for instance-based ones, nSV for kernel machines, and T·d for ensembles. Choosing a family is choosing which of your problem's dimensions you are willing to let the inference cost depend on. This is the same style of reasoning we apply to neural layers in §3.12.

3.8Support vector machines, properly

From "widest street" to the dual

For separable data with labels yi ∈ {−1,+1}, a hyperplane wTx + b = 0 has geometric margin 1/‖w‖ after the canonical scaling yi(wTxi+b) ≥ 1. Maximising the margin is therefore

minimise ½‖w‖² subject to y_i (wᵀx_i + b) ≥ 1 for all i

Non-separable data get slack variables and the soft-margin form, which is equivalent to minimising the hinge loss with L2 regularisation:

min over w ½‖w‖² + C · Σ_i max(0, 1 − y_i(wᵀx_i + b))

Introducing Lagrange multipliers αi and eliminating w gives the dual, in which the data appear only through inner products:

max over α Σ_i α_i − ½ Σ_i Σ_j α_i α_j y_i y_j ⟨x_i, x_j⟩ subject to 0 ≤ α_i ≤ C, Σ_i α_i y_i = 0

At the optimum w = Σi αi yi xi, and only points with αi > 0 — the support vectors — contribute.

The kernel trick. Because the data enter only as inner products, replacing ⟨xi,xj⟩ with a kernel k(xi,xj) = ⟨φ(xi),φ(xj)⟩ fits a linear model in a feature space we never construct. Any symmetric positive semi-definite k (Mercer's condition) corresponds to some φ. The RBF kernel k(x,z) = exp(−γ‖x−z‖²) corresponds to an infinite-dimensional φ — which is exactly why we do not build it.

The embedded catch. Prediction is f(x) = Σi∈SV αi yi k(xi, x) + b. Every support vector must be stored and evaluated at inference time. For noisy problems the number of support vectors grows roughly linearly with the training-set size, so a kernel SVM trained on 50 000 windows can end up with thousands of stored D-dimensional vectors — a model larger than the CNN it was supposed to replace. Students who have only used scikit-learn on small data are usually surprised by this.

-3 0 3 -3 0 3 linear SVM · 68 points · 3 support vectors margin = 2/‖w‖ Only the circled points enter the solution. Delete any other point and the boundary does not move. Inference cost: linear kernel → D MACs RBF kernel → n_SV · D MACs and n_SV grows with the size of the training set.
Fig 3.9The max-margin solution, fitted rather than sketched. Three of the sixty-eight points carry the entire decision function; the rest have αi = 0 and could be deleted without changing anything. That sparsity is the beautiful part of the SVM — and, with a non-linear kernel, the fatal part: prediction requires evaluating the kernel against every stored support vector, so on a noisy problem the model grows with the dataset instead of with the task.
exact kernel SVM — cost O(n_SV · D) x k(x, sv₁)k(x, sv₂) k(x, sv₃)k(x, sv_m) ⋮ Σ αᵢyᵢ· memory and time grow with the training set random-feature approximation — cost O(D · R) x z(x) = √(2/R)· cos(Ωᵀx + b) wᵀz(x) Ω drawn once from the kernel's Fourier transform; store a seed, not a matrix E[z(x)ᵀz(y)] = k(x,y) one fixed-size linear model, dataset-independent
Fig 3.10The fix for kernel-SVM inference cost. Random Fourier features (Rahimi & Recht, 2007) construct an explicit finite map z whose inner products approximate the kernel in expectation, converting a model whose size grows with the training set into a fixed R-dimensional linear model. On a microcontroller, Ω need not even be stored: regenerate it from a seed, or use a sign-random (±1) projection.

3.9Trees, forests and boosting

A decision tree recursively partitions the feature space by axis-aligned splits chosen to maximise impurity reduction. With class proportions pc in a node, the two standard impurities are

Gini(S) = 1 − Σ_c p_c² Entropy(S) = − Σ_c p_c log₂ p_c

and a split's quality is the parent impurity minus the sample-weighted mean of the children's. Gini is cheaper and behaves almost identically; entropy is preferred when you want the information-theoretic interpretation. Trees are high-variance: small data perturbations change the top split and thus everything below it.

Bagging and random forests reduce that variance by averaging trees trained on bootstrap resamples with a random feature subset at each split. The averaging is what reduces variance; the feature subsampling is what decorrelates the trees so the averaging actually helps.

Boosting as functional gradient descent

Gradient boosting builds an additive model Fm(x) = Fm−1(x) + ν·hm(x). At each round it computes the negative gradient of the loss with respect to the current predictions,

r_i = − ∂L(y_i, F(x_i)) / ∂F(x_i) evaluated at F = F_{m−1}

and fits the weak learner hm to those pseudo-residuals. Squared loss makes ri the ordinary residual; logistic loss makes it yi − pi. AdaBoost is the special case of exponential loss, expressed as sample reweighting. The shrinkage ν ∈ (0,1] is the learning rate and trades rounds against generalisation.

Foundations · the bias–variance decomposition, and why compression sometimes helps accuracy

For squared loss, the expected error of a model at a point decomposes exactly:

E[(y − ŷ)²] = ( E[ŷ] − f(x) )² + Var[ŷ] + σ² bias² variance irreducible

Bias is the error you would still make with infinite data, because your model class cannot represent the truth. Variance is how much the fitted model moves when you resample the training set. σ² is label noise, and nothing removes it.

Capacity trades one against the other, and the total is U-shaped. This is the quantitative reason a smaller model is not automatically a worse model: if you were to the right of the minimum — which a large network trained on a few hundred labelled windows almost always is — then every compression technique on page 2 is moving you towards the optimum, not away from it. Compression and regularisation are the same operation seen from two directions.

(The modern caveat: very over-parameterised networks trained to interpolation can show a second descent beyond the classical peak. The classical picture is still the right mental model at the model sizes this course cares about.)

1 3 5 7 9 0 total error variance bias² irreducible noise sweet spot model capacity → expected squared error E[(y − ŷ)²] = bias² + variance + σ² Embedded constraints push you left — a problem only if you were right of the minimum. For small datasets the compressed model is often the better model, not merely the feasible one.
Fig 3.11The decomposition that makes compression less painful than it sounds. Shrinking a model moves you left along this axis. If the original model sat to the right of the minimum — as over-parameterised models trained on a few hundred labelled windows usually do — then pruning, quantization and distillation can improve generalisation while also making the model fit. That is not a lucky accident; it is regularisation arriving under another name.

Why this matters on an MCU. A boosted ensemble of shallow trees compiles into straight-line comparison code with the thresholds as immediates. There is no matrix, no accumulator, no arena — inference is tens of comparisons and adds, often under a microsecond, with a completely flat memory profile. For tabular sensor features this is frequently both the most accurate and the cheapest option, and it is the reason libraries that emit C code from a trained ensemble are a staple of industrial embedded ML.

Part CNeural networks, from one neuron

A neural network is a composition of simple parameterised functions. This part builds it up from the smallest unit and counts its cost at every step, because the counting is what the rest of the course is about.

3.10Neurons, layers and backpropagation

x₁ w₁ x₂ w₂ x₃ w₃ Σ + b φ y one neuron: y = φ(w·x + b) cost: n MACs + 1 add + 1 activation parameters: n weights + 1 bias input hidden 1 hidden 2 output multilayer perceptron (fully connected) params = (4·5+5) + (5·4+4) + (4·3+3) = 64 · MACs = 52
Fig 3.12The building block of every neural network. A neuron multiplies its inputs by learned weights, adds a bias and passes the sum through a non-linear activation φ; a layer is many neurons sharing the same inputs, which is a matrix–vector product. Stacking layers gives a multilayer perceptron. Everything in the cost analysis later in this chapter is bookkeeping on this picture: one weight is one parameter to store and one multiply–accumulate to execute.

A fully connected (dense) layer with n inputs and m outputs computes y = φ(Wx + b), with a weight matrix W of size m×n, a bias vector b and an element-wise activation φ. Its cost is exact and worth memorising:

parameters = m·n + m MACs per inference = m·n activations = n inputs + m outputs

Without the non-linearity φ, any stack of layers would collapse into a single matrix multiplication and could only represent linear functions. With it, a network with even one hidden layer can approximate any continuous function on a bounded domain given enough units (the universal approximation theorem); depth makes many functions far cheaper to represent than width alone.

sigmoid exp → lookup table tanh exp → lookup table ReLU one compare: free hard-swish piecewise linear: cheap Element-wise. ReLU and ReLU6 fold into the clamp that ends an int8 layer.
Fig 3.13Activation functions supply the non-linearity without which a deep network would collapse into a single linear map. Their inference cost differs sharply on embedded hardware: sigmoid and tanh need an exponential, implemented as a lookup table in integer arithmetic; ReLU is a single comparison and can be fused into the clamp that ends every quantized layer; hard-swish was designed for MobileNetV3 as a piecewise-linear approximation of the smooth swish function precisely so that it would be cheap on phones.

How the weights are learned: backpropagation

Training a network is gradient descent on its loss. The gradient with respect to millions of weights is computed efficiently by backpropagation, which is the chain rule of calculus applied layer by layer from the output back to the input. The forward pass computes and stores every layer's activations; the backward pass multiplies by each layer's local derivative and reuses those stored activations to obtain the weight gradients. Two consequences matter for embedded systems. Training costs roughly three times the arithmetic of inference per example; and it needs the activations of every layer at once, so its memory footprint is many times that of inference — the reason on-device training is a research problem (Session 4) rather than a configuration option.

3.11Convolutional networks

For signals with spatial or temporal structure — images, spectrograms, multi-axis IMU windows — a dense layer is wasteful: it learns a separate weight for every input position, although a useful pattern (an edge, an onset, a harmonic) looks the same wherever it occurs. A convolutional layer instead slides a small learned kernel (for example 3×3) across the input and applies the same weights at every position. This weight sharing cuts parameters by orders of magnitude and builds in translation equivariance: a pattern shifted in the input produces the same response, shifted.

A convolutional network stacks such layers, interleaved with non-linearities and with downsampling (stride or pooling) that halves the spatial size while the number of channels grows. Early layers respond to local, simple patterns; later layers combine them into larger, more abstract ones. The network ends with global average pooling and a small dense classifier.

input 96×96×1 conv1 48×48×8 conv2 24×24×16 conv3 12×12×32 conv4 6×6×64 GAP+FC 1×1×64 stride-2 3×3 convolutions: space shrinks 2× per stage, channels double 9.0k 0 18.0k 72 9.0k 1.1k 4.5k 4.5k 2.2k 18.0k 64 640 output activation bytes (int8) parameters (= weight bytes, int8) activations peak at the front, parameters at the back — the asymmetry that decides SRAM versus flash
Fig 3.14How a convolutional network trades space for channels. Each stage halves the spatial resolution and doubles the number of feature maps, building from edges to parts to objects. The bar chart shows the consequence for an embedded deployment of this toy network: the largest activation tensor (18 kB) sits right after the first layer, while almost all of the 24.9 k parameters sit in the last two. SRAM is sized by the front of the network, flash by the back — the asymmetry Session 1 introduced and Session 4 exploits.

Four more building blocks

  • Stride and pooling. A convolution with stride 2 evaluates the kernel at every second position, halving each spatial dimension; a pooling layer does the same with a fixed operation (maximum or average over a 2×2 window). Both cut the activation size by 4× per step. Global average pooling at the end of the network averages each channel over all positions, leaving one number per channel.
  • Batch normalisation (BN). During training, BN standardises each channel's activations over the mini-batch and then rescales them with two learned parameters; it makes deep networks much easier to train. At inference it is a fixed per-channel scale and shift, which can be folded into the preceding convolution's weights and bias at no cost (developed below).
  • Residual (skip) connections. A block's input is added to its output, y = x + F(x), so the block only has to learn a correction. Residual connections are what made networks of tens to hundreds of layers trainable. Their embedded cost is memory: the input tensor must stay alive until the addition, which raises peak SRAM.
  • Depthwise-separable convolution. A factorisation of the standard convolution into a per-channel spatial filter and a 1×1 channel mixer; it is the basis of every efficient architecture and gets its own section below.
One word, three meanings

"Kernel" means three different things in this course. In an SVM it is a similarity function between two inputs (Part B). In a convolutional layer it is the small array of learned weights that slides over the input. In systems language (Session 4) it is an optimised low-level routine — "the int8 convolution kernel" of a library. Context always disambiguates, but it is worth knowing that the word is overloaded.

The figure is the most important cost fact about CNNs on microcontrollers, already met in Session 1: activations are largest at the front of the network, parameters at the back. Flash is sized by the parameters; SRAM by the largest pair of consecutive activation tensors. The next section makes the arithmetic precise.

3.12The three currencies

Every layer has three costs and they do not correlate:

  • Parameters — bytes of flash, and the thing model-size headlines report. Dominated by the final dense layers and by 1×1 convolutions with many channels.
  • MACs — arithmetic work, the thing FLOP counts report. Dominated by early convolutions at high spatial resolution.
  • Bytes moved — traffic between memory levels, the thing that actually determines latency and energy (Session 1, Fig 1.7). Dominated by whichever layer has poor operand reuse.

A network can be simultaneously parameter-light, MAC-light and slow. Recognising this is the central idea of this part of the chapter.

input 6×6×C_in each window: k²·C_in multiply–accumulates kernel k=3 one kernel per output channel output 4×4×C_out 16 windows × C_out MACs = H·W·k²·C_in·C_out params = k² · C_in · C_out activations = H · W · C_out Every convolution is this picture with different numbers.
Fig 3.15The three costs of a convolution, read off one picture. The copper window is one dot product of length k²·Cin; it is evaluated once per output position and once per output channel. Notice what changes when you stride or pad: the output grid shrinks or grows, which changes MACs and activations but leaves the parameter count untouched — the commonest source of confusion when a model "gets smaller" but not faster.
Foundations · what exactly is a “FLOP”?

The literature is inconsistent here, and it is a common source of mistakes. A multiply–accumulate (MAC, or MAdd) is one multiply plus one add. Some papers count that as 1 FLOP, others as 2. So a network described as “300 M FLOPs” may mean 300 M MACs or 150 M. When comparing two papers, check whether their numbers for a shared reference model — MobileNetV2 at 300 M MAdds is the usual one — agree; if they differ by exactly 2×, you have found the convention, not a result.

Three further traps. Counted versus measured: a MAC count is arithmetic on paper; a latency is a measurement with a device, a compiler and a clock attached. Batch size: almost all embedded inference is batch 1, where reuse is at its worst — throughput figures quoted at batch 64 are irrelevant to you. What is included: some counts omit batch norm, activations, pooling and the entire feature front end, which on a small model can be a third of the real work.

LayerParametersMACsOutput activations
Dense, Din→DoutDin·Dout + DoutDin·DoutDout
Conv 2-D, k×k, Cin→Cout, out H×Wk²·Cin·Cout + CoutH·W·k²·Cin·CoutH·W·Cout
Depthwise conv, k×kk²·CinH·W·k²·CinH·W·Cin
Pointwise (1×1) convCin·CoutH·W·Cin·CoutH·W·Cout
Grouped conv, g groupsk²·Cin·Cout/gH·W·k²·Cin·Cout/gH·W·Cout
Dilated conv, rate rsame as convsame as convsame as conv
Max / average pooling0~H·W·C·k² comparesH·W·C
Batch norm (inference)2·C stored0 after foldingin place
Residual add0H·W·C addsholds the skip tensor live

Table 3.2 — Layer cost formulas. Learn these; the rest of the course assumes them. Note that a dilated convolution costs exactly what an ordinary convolution costs while covering a larger receptive field — which is why it is the standard trick for cheap temporal context.

3.13Depthwise separable convolution depth

The reduction factor

A standard convolution mixes information across space and across channels in one operation. The separable form splits it: a depthwise convolution filters each channel independently, then a 1×1 convolution mixes channels.

standard : H·W·k²·C_in·C_out MACs depthwise : H·W·k²·C_in MACs pointwise : H·W·C_in·C_out MACs ratio = (k²·C_in + C_in·C_out) / (k²·C_in·C_out) = 1/C_out + 1/k²

With k = 3 and Cout = 128 the ratio is 1/128 + 1/9 ≈ 0.119 — an 8.4× reduction in arithmetic. The same factor applies to parameters.

But: measured speedups on real hardware are routinely 2–4×, not 8×. The reason is in §4.3.

standard 3×3 conv — one kernel spans all inputs C_in maps k×k×C_in C_out maps H·W·k²·C_in·C_out MACs depthwise separable — two cheaper stages k×k×1, one per channel 1×1×C_in H·W·k²·C_in + H·W·C_in·C_out MACs ratio = 1/C_out + 1/k² ≈ 1/9 for 3×3 The arithmetic falls by ~9×. The bytes moved fall by far less — see the roofline. this gap between counted work and measured time is the central lesson of the session
Fig 3.16Factorising a convolution into a spatial stage and a channel-mixing stage. The factorisation assumes that cross-channel and cross-spatial correlations can be modelled separately — an assumption that costs a little accuracy and buys an order of magnitude in arithmetic.

3.14Normalisation and activations at inference time

Folding batch normalisation into a convolution

At inference, batch normalisation applies fixed statistics:

y = γ · (x − μ) / √(σ² + ε) + β

If x = W ∗ a + b is the preceding convolution, substitute and collect terms:

y = W' ∗ a + b' with W' = γW / √(σ²+ε) b' = γ(b − μ)/√(σ²+ε) + β

The normalisation disappears into modified weights and biases: zero inference cost, one fewer pass over the activations. Every deployment toolchain does this automatically, and the fold is mandatory before quantization — an unfolded BN would need a separate floating-point scale per channel at runtime, and the fold is what lets per-channel weight scales absorb it instead (§3.22).

Note the corollary: layer norm, group norm and instance norm cannot be folded, because their statistics depend on the input at runtime. Architectures that use them pay a real inference cost on constrained hardware — one reason batch norm persists in embedded vision long after the research community moved on.

Activations. ReLU is free and quantizes perfectly (it is exactly representable and its output range is bounded below). ReLU6 — min(max(0,x),6) — was adopted in MobileNet precisely to bound the activation range so that low-precision arithmetic has a predictable dynamic range. swish = x·σ(x) improves accuracy but needs a sigmoid; MobileNetV3 replaces it with hard-swish, x·ReLU6(x+3)/6, which is piecewise linear, cheap in integer arithmetic, and nearly as accurate. This is a clean example of a design decision made by the target hardware rather than by the loss curve.

3.15Sequence models on constrained hardware

Sensor data arrive as streams, and three families of model can consume a stream: recurrent networks, which carry a state from step to step; convolutional networks over time (1-D CNNs and temporal convolutional networks), which look at a fixed window; and attention-based transformers, which compare every element of a window with every other. The recurrent idea is the simplest to draw.

recurrent cell, unrolled in time cell same W, U x₁ y₁ h₁ cell same W, U x₂ y₂ h₂ cell same W, U x₃ y₃ h₃ cell same W, U x₄ y₄ h_t = tanh(W·x_t + U·h_{t−1} + b): memory cost = one hidden state, regardless of sequence length
Fig 3.17A recurrent network processes a stream one sample (or frame) at a time, carrying a hidden state h forward. The same weights are reused at every step, so the parameter count is independent of the sequence length and the working memory is only the state — attractive for streaming sensors. The price is sequential dependence: step t cannot start before step t−1 finishes, which limits parallel hardware, and training through long sequences is hard. LSTMs and GRUs add gates to make that training stable.
ModelParams (hidden n, input m)Cost per stepStreamingEdge verdict
Vanilla RNNn(m+n)+nn(m+n) MACsNatural, O(n) stateCheap; unstable to train
LSTM4[n(m+n)+n]4n(m+n) MACsNatural, O(2n) stateReliable; 4× the cost; sequential
GRU3[n(m+n)+n]3n(m+n) MACsNatural, O(n) stateUsually the right RNN for MCUs
TCN / dilated 1-D convk·C²·L layersparallel over timeRing buffer of receptive fieldPreferred: parallel, bounded state
Self-attention, length T4d² per layerO(T²d) per layerKV cache grows with TQuadratic term and growing cache are hostile to MCUs
State-space (S4 / Mamba style)O(d²)O(Td) with fixed stateConstant-size recurrent stateActive research; attractive for long streams

Table 3.3 — Sequence models compared on the axes that matter at the edge. The decisive property is not accuracy per parameter but whether inference can be made streaming with bounded state: an always-on device processes an unbounded stream and cannot afford a cache that grows with time.

Streaming inference deserves emphasis. A convolutional model applied to overlapping windows recomputes most of its early layers on every window. A streaming implementation keeps a ring buffer per layer and computes only the new columns, reducing work by roughly the overlap factor. This is standard practice in production keyword spotters and is exactly the kind of systems optimisation that never appears in an accuracy table.

Receptive field. For a stack of convolutions with kernel sizes ki, strides si and dilations di, the receptive field grows as Ri = Ri−1 + (ki−1)·di·Πj<isj. Check it: a model whose receptive field is shorter than the event it must recognise cannot work, and no amount of training will reveal the reason.

0 2 4 6 8 10 0 64 128 192 256 plain 3×3 3×3 + stride 2 3×3 dilated ×2 layer index receptive field (samples) R_i = R_{i−1} + (k_i − 1) · d_i · Π s_j A receptive field shorter than the event cannot detect it. At 16 kHz with a 128-sample hop, 10 dilated layers already span about 2 seconds of audio.
Fig 3.18Three ways to buy temporal context, at identical parameter cost per layer. Dilation is nearly free — the kernel has the same number of weights and the same MAC count as an undilated one — which is why dilated convolutional stacks displaced recurrent networks for streaming audio. Check this arithmetic before training: if your ten-layer network spans 200 ms and the event you want lasts 600 ms, no amount of data will fix it.

3.16Classical or deep? A decision guide

10 10² 10³ 10⁴ 10⁵ 10⁶ labelled training examples (log) test accuracy crossover: task-dependent features + SVM / trees deep network on raw input Choose classical when · labels are few or costly · good features are known · the budget is a few kB · you must explain decisions Choose deep when · data is plentiful · signals are raw, high-dim. · (images, audio, multi-axis) · an NPU or SIMD path exists Schematic, not measured: the shape is typical, the numbers are not.
Fig 3.19The usual shape of the classical-versus-deep trade-off. With little labelled data, a classical model on well-designed features is both more accurate and far cheaper; deep networks learn their own features and overtake once data is plentiful — but the crossover point depends entirely on the task, and on an embedded device the budget may end the comparison before the data does. Schematic: the curves illustrate a pattern, not a measurement.

There is no universal answer, but there is a reliable procedure. Start with the cheapest model that could work — a tree ensemble or logistic regression on a dozen time-domain or spectral features — and measure it on a subject-wise split. Move to a neural network only if that baseline misses the target, and then start with the smallest architecture of the families below. Record, for every candidate, accuracy and flash, peak SRAM, MACs and measured latency: the decision is made on the Pareto front of those, not on accuracy alone.

SituationUsually favoursWhy
Few labelled examples (hundreds)classicalfewer parameters to estimate; strong priors in the features
Good domain features known (e.g. heart-rate variability, band energies)classicalthe features already do the representation learning
Raw, high-dimensional input (images, audio, multi-channel)deeplearned features beat hand-crafted ones when data suffice
Budget of a few kB and a few thousand operationsclassicaltrees and linear models scale down further than any CNN
Target has an NPU or a mature int8 CNN librarydeephardware support changes the cost ranking
Decisions must be explained or certifiedclassical (or a small, inspectable network)auditability
Inputs drift and the model must adapt on the deviceeither — open questionsee on-device learning, Session 4

Table 3.4 — A first decision guide. "Usually" matters: each row is a prior to be tested on the validation set, not a rule.

Part DEfficient architectures and architecture search

Designing the network to be cheap from the start is usually more effective than shrinking a network that was not. This part explains the design principles behind the architecture families used on phones and microcontrollers, and how their design was automated. Presentation topic C covers the primary papers.

3.17Five design principles, each earned

  1. Factorise expensive operations. Depthwise separable convolution replaces one joint spatial-and-channel mixing with two cheap ones (§3.13). Everything in this part is a variation on that move.
  2. Keep tensors small where they are large. Peak activation memory occurs early (§1.6), so downsample aggressively in the stem. MCU-targeted networks often use a strided stem with very few channels for exactly this reason.
  3. Spend parameters where they are cheap and MACs where they are cheap — different places. Late layers are parameter-heavy and compute-light; early layers the reverse.
  4. Respect memory access cost. Equal channel widths, few branches, few element-wise operations (§3.19).
  5. Choose operators the target can execute. Hard-swish over swish; ReLU6 for bounded ranges; no layer norm without hardware support; only operators the vendor compiler supports (§4.14).

3.18The families and their mechanisms

FamilyStructural mechanismReported headlineWhere it breaks
SqueezeNet (2016)Fire module: a 1×1 "squeeze" reduces channels, then a mixed 1×1/3×3 "expand"AlexNet-level accuracy with 50× fewer parameters, <0.5 MB compressedParameters ≠ MACs: it is not correspondingly fast
MobileNetV1 (2017)Depthwise separable convolution throughout; width multiplier α and resolution multiplier ρ as explicit knobs~8–9× fewer MACs than an equivalent dense CNNLow arithmetic intensity in depthwise layers (§4.3)
MobileNetV2 (2018)Inverted residual with linear bottleneck: expand → depthwise → project, skip connecting the narrow endsBetter accuracy/MAC than V1; smaller peak activationExpansion ratio 6 conflicts with guideline G1
ShuffleNet V1/V2 (2017/18)Pointwise group convolution + channel shuffle; V2 replaces this with channel split and concatenation to obey its own four guidelinesState-of-the-art speed/accuracy on mobile ARM at fixed FLOPsChannel shuffle is memory traffic on hardware without a cheap permute
MobileNetV3 (2019)Platform-aware NAS + NetAdapt layer-wise tuning, squeeze-and-excitation, hard-swish, hand-redesigned head and stemV3-Large: 3.2 % more accurate than V2 at 20 % lower latencySE and hard-swish complicate int8 deployment
EfficientNet (2019)Compound scaling of depth, width and resolution from one balanced base modelLarge accuracy gains per FLOP across a whole familyOptimised for FLOPs and GPU latency, not for SRAM
EfficientNet-LiteThe same, minus squeeze-and-excitation and swish; ReLU6 throughout; fixed stem/headQuantization-friendly, deployable on TFLite/EdgeTPUGives up some accuracy for deployability — a deliberate trade
MicroNets (2021)Differentiable NAS over MCU-feasible spaces, exploiting the empirical finding that latency varies linearly with op count within a fixed search spaceState of the art at the time on the three tasks it targeted (visual wake words, keyword spotting, anomaly detection)The linearity holds within a space, not across spaces
MCUNet (2020–21)TinyNAS (memory-constrained search space) co-designed with TinyEngine (memory-scheduling runtime); V2 adds patch-based inferenceImageNet-scale accuracy on a commodity MCU; >90 % on Visual Wake Words in 32 kB SRAMTightly coupled to its own runtime — see §4.16
MobileViT / EdgeNeXt (2022)Hybrid: convolutions for local structure, a restricted form of attention for global contextMobileViT: 78.4 % ImageNet top-1 at ~6 M parametersAttention still costs memory bandwidth; not MCU-scale

Table 3.5 — Efficient architecture families. Read the last column as the important one: every family is efficient under an assumption, and deployment failures are usually assumption violations rather than implementation bugs.

50 M 100 M 500 M 1 G 5 G 15 G 50 55 60 65 70 75 80 0.25 MobileNetV1 0.5 MobileNetV1 MobileNetV1 MobileNetV2 ShuffleNetV2 1× ShuffleNetV2 2× MnasNet-A1 MobileNetV3-Small MobileNetV3-Large EfficientNet-B0 GoogLeNet VGG-16 ResNet-50 multiply–adds per inference, log scale ImageNet top-1 accuracy (%) bubble area ∝ parameter count · grey = pre-2016 · copper = efficiency-designed Same accuracy, 19× fewer MAdds: ResNet-50 4.1 G MnasNet-A1 315 M VGG-16 needs 138 M parameters for 71.5 %; MobileNetV3-Large needs 5.4 M for 75.2 %. Five years of architecture work bought roughly an order of magnitude, at constant accuracy. Note the axis convention problem: these papers count MAdds, FLOPs and "ops" and do not always agree. Always check which one a number is before comparing across papers.
Fig 3.20The efficiency frontier, from published numbers. Sources: MobileNets (Howard et al. 2017, Tables 6 and 8), MobileNetV3 (Howard et al. 2019, Table 3), ShuffleNet V2 (Ma et al. 2018, Table 8), EfficientNet (Tan & Le 2019, Table 2). The dashed copper line is the frontier traced by the efficiency-designed families. Two lessons: the frontier moved about an order of magnitude to the left between 2015 and 2019 at constant accuracy, and bubble size shows that parameter count and MAdd count are almost independent — VGG-16 is enormous in both, ResNet-50 is compute-heavy but parameter-light for its era, and MobileNetV3-Large is small in both.
Classical residual bottleneck wide · 256 ch1×1 reduce · 64 3×3 · 641×1 expand · 256 the skip holds a wide tensor live peak memory ∝ 256 channels Inverted residual, linear bottleneck narrow · 24 ch1×1 expand · 144 3×3 depthwise · 1441×1 project · 24 (linear) the skip holds a narrow tensor live peak memory ∝ 24 channels; the wide tensor is transient Inversion is a memory argument, not an accuracy argument.
Fig 3.21Why the residual was inverted. In the classical form the residual path carries the wide tensor, so a wide activation must stay live across the whole block. Inverting it puts the skip on the narrow tensors and confines the expanded tensor to the inside of the block, where a runtime can process it in pieces. The final projection is linear — no ReLU — because a ReLU applied in a low-dimensional space destroys information that cannot be recovered, which MobileNetV2 demonstrates empirically.

Squeeze-and-excitation, in one paragraph

An SE block computes a global average per channel, passes the resulting C-vector through a small two-layer bottleneck MLP with a sigmoid output, and multiplies each channel by its gate. It is channel-wise attention: cheap in MACs, effective in accuracy, and awkward in deployment because it introduces a global reduction (a synchronisation point that breaks streaming and patch-based execution) and a sigmoid on a path that must be quantized. This is why the Lite variants of efficient architectures remove it.

EfficientNet's compound scaling

Depth, width and resolution are not independent: a deeper network needs more resolution to have anything to look at, and a wider one needs more depth to combine it. EfficientNet parameterises all three by a single coefficient φ:

depth d = α^φ width w = β^φ resolution r = γ^φ subject to α · β² · γ² ≈ 2 , α, β, γ ≥ 1

The constraint exists because FLOPs scale linearly in depth but quadratically in width and in resolution; the product is fixed at 2 so that each unit increase of φ doubles the FLOPs. The constants are found by a small grid search on the base model and then reused for the whole family — a genuinely economical idea. Note what it optimises: FLOPs. On a device where peak SRAM binds, raising resolution is far more expensive than the constraint implies, which is exactly why MCU-targeted searches (MicroNets, TinyNAS) use a memory constraint instead.

cost of scaling one dimension by a factor φ depth d = α^φ linear in φ each extra layer adds its own MACs width w = β^φ quadratic C_in and C_out both grow resolution r = γ^φ quadratic H and W both grow α · β² · γ² ≈ 2 One unit of φ therefore doubles the FLOPs, whichever mix of the three you choose. Note what is being held constant: FLOPs — not SRAM. Raising resolution is far more expensive on an MCU.
Fig 3.22Where EfficientNet's constraint comes from. Depth enters the cost linearly, width and resolution quadratically, so fixing α·β²·γ² ≈ 2 makes one unit of the compound coefficient double the arithmetic regardless of how the budget is split. The constraint is correct and useful — for a FLOP budget. On a microcontroller the binding budget is peak activation memory, which grows with H·W·C, so resolution is disproportionately expensive and the same constraint gives the wrong answer. That is precisely why MCU-targeted searches use a memory constraint instead.

3.19ShuffleNet V2's four guidelines depth

Ma et al. (2018) measured rather than counted, and distilled four rules. They are the most useful practical result in efficient-architecture design and they follow directly from §4.3.

G1 — equal channel widths minimise memory access cost

For a 1×1 convolution on an h×w map with c₁ input and c₂ output channels, the arithmetic is B = hwc₁c₂ and the memory traffic is

MAC = hw(c₁ + c₂) + c₁c₂

By the arithmetic–geometric mean inequality, c₁ + c₂ ≥ 2√(c₁c₂), hence

MAC ≥ 2√(hw·B) + B/hw

with equality when c₁ = c₂. So for a fixed arithmetic budget, memory traffic is minimised by keeping the channel count constant through the block. Bottleneck blocks with aggressive expansion ratios violate this and pay for it in wall-clock time.

  • G2 — excessive group convolution increases memory access cost. Grouping reduces arithmetic for a fixed channel width, which lets you widen the layer, which increases traffic. There is an optimum group count and it is not "as many as possible".
  • G3 — network fragmentation reduces parallelism. Many small parallel branches (as produced by some NAS methods) look cheap in FLOPs and run poorly, because each branch has kernel-launch and scheduling overhead and none of them saturates the machine.
  • G4 — element-wise operations are not negligible. ReLU, tensor addition, and depthwise convolutions themselves have near-zero FLOPs and substantial memory traffic. In the paper's profiling of ResNet-like blocks, element-wise operations account for a material share of runtime despite being invisible in a FLOP count.

3.20Neural architecture search, decomposed depth

Following Elsken et al.'s survey, every NAS method is three choices.

Search space what can be built cell · macro · MCU-feasible Search strategy RL · evolution · gradient random search (the baseline) Performance estimation supernet weight sharing · early stop · predictor Hardware cost model measured latency LUT · SRAM · energy The hardware box is what turns NAS into embedded ML. Without it you get an accurate model; with it you get a deployable one.
Fig 3.23The three-plus-one components of NAS. The search space determines what is findable and encodes most of the human prior — a fact that makes strong random-search baselines embarrassing and informative. Performance estimation is where the compute is spent, and hardware-aware cost models are what distinguish embedded NAS from NAS in general.
  • Search space. Cell-based spaces search one repeated block; macro spaces search the whole network including widths and resolutions. For MCUs the space itself must be constrained — TinyNAS's contribution is largely that it first chooses a search space whose members fit the device's SRAM and flash, and only then searches within it. Searching a space whose members cannot fit is wasted compute.
  • Search strategy. Reinforcement learning (NASNet, MnasNet), evolutionary search, Bayesian optimisation, and differentiable relaxations (DARTS, ProxylessNAS) in which the architecture is a continuous mixture of candidate operations optimised by gradient descent alongside the weights.
  • Performance estimation. Training every candidate is infeasible, so: train a single over-parameterised supernet whose sub-networks share weights and evaluate sub-networks directly; or train briefly and extrapolate; or fit a predictor from architecture encoding to accuracy. Each shortcut introduces a ranking bias, and whether supernet rankings correlate with true rankings is an active and unresolved question.

Making hardware cost differentiable

MnasNet uses measured on-device latency inside a multi-objective reward. ProxylessNAS goes further: it builds a latency model as a sum of per-operation measured latencies, which makes expected latency a differentiable function of the architecture-mixing probabilities, so latency enters the loss directly rather than as a reward signal. It also solves the memory problem of differentiable NAS by binarising the paths so only one candidate operation is resident at a time. The result is a network specialised to one hardware target — and the paper's own experiments show that networks specialised for a GPU, a CPU and a mobile phone genuinely differ, which is the empirical justification for this entire part.

Once-for-All attacks the resulting cost problem: if you need a different model per device, do you rerun the search per device? OFA trains one supernet with progressive shrinking — supporting varying depth, width, kernel size and resolution — from which specialised sub-networks are extracted without further training, reported as more than 1019 sub-networks from a single training run. This decouples the one-off training cost from the per-device deployment cost, which is the right structure for a product line with a dozen hardware variants.

Halfway through Session 3

Choose the model family by data, features and budget, not by fashion; count parameters, activations and MACs for every candidate; and prefer architectures whose operations your hardware actually executes efficiently. Page 2 takes the chosen model and makes it smaller still.