A tiny search space already holds 3.2 × 1011 networks. A search tries a few hundred of them and returns one that fits your budget.
Learn how a program can design a neural network for you: what it may choose from, how it tries designs, and how it knows which one is good.
Set a latency budget, then pick how to search. Compare what each method finds with the best design that exists. Then we build, piece by piece, the layers, blocks, spaces and strategies behind it.
You need what a convolution layer does and a little Python. We build the rest from zero.
Based on Lecture 7 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. Lecture 7 slides are on the course page.
Illustrative: a made-up space of 6 layers with 4 choices each (4,096 networks). Latency and accuracy come from a toy formula, not from real training. The 3.2 × 1011 in the lede is the lecture's count for a NASNet-style cell (Chapter 5).
Chapter 0
See why picking a network by hand cannot keep up with the number of choices, and meet the plan for this lecture
You build the camera app of a phone. It needs a network that labels what the camera sees, in a few milliseconds on the phone's chip. A known design is too slow. A narrower one is faster but less accurate. Each guess costs hours of training.
Neural architecture search (NAS) lets a program make those guesses. An architecture is the plan of a network: which layers, how wide, how they connect. The program tries many plans and keeps the best one that fits your budget.
The lecture's second slide names the trade. Three costs pull against one benefit: storage (the bytes of the weights), latency (the time for one answer) and energy, against accuracy. On tiny devices, memory for the numbers computed along the way is a fourth cost (Chapter 7).
The lecture lists five knobs: layers, channels, kernel size, connections and input resolution. Every combination is a different network. Take a small case. Call the number of layers L and the number of operations each layer may pick m.
N equals m to the L, which is 6 to the 20, about 3.7 times 10 to the 15.
Each layer picks one of m operations, whatever the other layers pick. So multiply m by itself L times. The product is N.
With m = 6 and L = 20, N = 3.66 × 1015. At a toy price of one GPU-hour per network, that is about 4 × 1011 GPU-years.
Each bar is a power of ten. The long bar is the whole space. The short marks are what a person and a cluster can try in a year. Drag both sliders.
Illustrative: one GPU-hour per network, 1,000 GPUs running for a year (8.8 million GPU-hours), and 1,000 designs tried by hand in a year. Real training takes longer, which makes the gap larger.
Even modest settings put the space many powers of ten past the cluster's mark. So a search cannot visit every design. It must choose which few to try.
The person writes the rules: which operations exist, how many layers, what budget. The program searches inside them. If a building block is missing from the rules, no search can find it. That is why the lecture covers spaces before strategies.
Chapter 1
Learn the five layer types and the one formula, multiply-accumulates, that prices each of them
A chip does one job again and again: it multiplies two numbers and adds the result to a running total. That step is one MAC (multiply-accumulate), about two floating point operations. The lecture counts MACs for a batch of one and ignores the bias.
A fully connected (linear) layer feeds every input to every output. The input has shape (n, ci), the weights (co, ci), the output (n, co). Each output is a dot product of length ci, so the layer costs co · ci MACs.
A convolution slides a small window, the kernel, over a stack of channels (2D maps of numbers). Input (n, ci, hi, wi) and weights (co, ci, kh, kw) give output (n, co, ho, wo).
h-o equals h-i plus 2 p minus k-h, all over s, plus 1.
Add p rows of zeros on each side of the input. Count the places a kernel of height k-h fits, stepping s rows at a time. That count is h-o, rounded down.
h-i = 56, p = 1, k-h = 3, s = 1: (56 + 2 − 3) / 1 + 1 = 56, so the size stays. With s = 2 it is 28.5, so 28.
MACs equal c-o times c-i times k-h times k-w times h-o times w-o.
For each output channel c-o and each output position, do one dot product of c-i times k-h times k-w terms. Multiply all the counts.
A 3 by 3 layer, 64 channels, 56 by 56 map: 64 · 64 · 9 · 56 · 56 = 115,605,504 MACs.
| Layer | MACs, batch of 1, bias ignored |
|---|---|
| Linear | co · ci |
| Convolution | co · ci · kh · kw · ho · wo |
| Grouped convolution | co · ci · kh · kw · ho · wo / g |
| Depthwise convolution | co · kh · kw · ho · wo |
| 1×1 convolution | co · ci · ho · wo |
All four at the same shape:
Depthwise is 64 times cheaper, because the saving equals ci. Try c = 256 below: the standard bar grows with c squared, the depthwise bar with c.
Each bar is MACs for one layer at the shape you set. The standard bar is the reference. Drag any slider.
The formulas are the lecture's, with stride 1 and padding that keeps the size. The device rounds groups to a divisor of c so the layer stays valid.
pythondef macs(kind, ci, co, k, ho, wo, g=1): if kind == "linear": return co * ci if kind == "conv": return co * ci * k * k * ho * wo if kind == "grouped": return co * ci * k * k * ho * wo // g if kind == "depthwise": return co * k * k * ho * wo # g = ci = co if kind == "1x1": return co * ci * ho * wo print(macs("conv", 64, 64, 3, 56, 56)) # 115605504 print(macs("depthwise", 64, 64, 3, 56, 56)) # 1806336
Symptom: a network with far fewer MACs runs no faster on the phone. Cause: a depthwise layer does little arithmetic for each byte it reads, so the chip waits for memory. Fix: treat MACs as a first price, then measure latency on the device. Chapter 9 puts latency into the search.
Chapter 2
Cut a block's cost by 8.5 times with 1×1 layers, then cut it again by splitting channels into groups
A 3 × 3 convolution with 2048 channels in and out does 2048 × 2048 × 9 = 37.7 million MACs at every pixel. ResNet keeps most of its strength for 8.5 times less. A search can later pick this design, so we count it.
The ResNet50 bottleneck block has three layers: wide, narrow, wide again.
A residual connection adds the block's input to its output, like a shortcut road beside a winding one. The add needs the output shape to equal the input shape, (B, 2048, H, W). So the blocks stack freely.
Count MACs per pixel. H × W scales every line the same way.
512 times 512 times 144, over 512 times 512 times 17, is about 8.5.
Divide the plain cost by the block cost. The 512 times 512 cancels, so the saving is 144 over 17.
37,748,736 / 4,456,448 = 8.47, which the slide rounds to 8.5. The weights shrink by the same 8.5, because here weights and MACs per pixel are the same product.
ResNeXt replaces the 3×3 with a grouped 3×3. The lecture shows this equals a multi-path block: many thin parallel paths whose outputs add up. So the number of paths is a knob a search can turn. In its figure, a block squeezes 256 channels to 128 and runs the 3×3 with g = 32, so 147,456 MACs per pixel fall to 4,608.
Top: one plain 3×3 layer on 2048 channels. Bottom: the bottleneck, as squeeze, convolve and expand. Set the inner width and the groups.
The 2048 in and out and the 512 default are the lecture's ResNet50 numbers. Costs are MACs per pixel from the lecture's formulas. Accuracy is not modelled here.
At 512 the bar shows the 8.5 times saving. At an inner width of 2048, the block costs more than the plain layer. More groups shrink the middle segment, but the two 1×1 segments stay. They are the next target.
pythondef bottleneck_macs(c_out=2048, c_mid=512, g=1): squeeze = c_out * c_mid # 1x1 conv3 = c_mid * c_mid * 9 // g # 3x3, grouped expand = c_mid * c_out # 1x1 return squeeze + conv3 + expand # per pixel plain = 2048 * 2048 * 9 print(plain / bottleneck_macs()) # 8.47, the lecture's 8.5x
Symptom: the block is cheap, but the network loses accuracy. Cause: the 3×3 layer sees only c_mid channels, so it has less room for patterns. Measure: the accuracy of narrow-middle networks against wider ones at the same depth. Fix: make the inner width a choice in the search space.
Chapter 3
Follow the mobile blocks from MobileNet to ShuffleNet, see why cheap blocks still strain memory, and price an attention block
A depthwise layer is 64 times cheaper than a standard one. Why not use it everywhere? Because it never mixes channels: each channel stays in its own lane. The mobile blocks fix that, one trick at a time.
| Block | The trick | MACs per pixel, width N |
|---|---|---|
| MobileNet: depthwise-separable | A depthwise 3×3 captures space, one channel at a time. A 1×1 then fuses information across channels. | 9N + N² |
| MobileNetV2: inverted bottleneck | A 1×1 expands N channels to 6N, a depthwise 3×3 works on 6N, a 1×1 projects back to N. Narrow, wide, narrow. | 6N(2N + 9) |
| ShuffleNet | The 1×1 layers become grouped 1×1 layers. A channel shuffle deals the channels across groups like cards, at zero MACs. | 9N + N²/g |
At N = 64 the separable block costs 576 + 4,096 = 4,672 MACs per pixel, against 36,864 for a standard 3×3. MobileNetV2 widens the middle because a depthwise layer has little capacity, and its cost grows only linearly. At N = 160 the block costs 960 × 329 MACs per pixel.
Cheap in MACs is not cheap in memory. Activations are the intermediate tensors a block must hold, and the inverted bottleneck holds one 6N channels wide at every pixel. The slide's figures:
| Setting | Parameters | Activation |
|---|---|---|
| Inference, 8-bit, batch 1: MobileNetV2-0.75 against ResNet-18 | 4.6 times fewer | 1.8 times less (peak) |
| Training, 32-bit, batch 16: MobileNetV2-1.4 against ResNet-50 | 4.3 times fewer (24 MB against 102 MB) | 1.1 times less (626 MB against 707 MB) |
Formulas per pixel: standard 9N², separable 9N + N², grouped separable 9N + N²/4, inverted tN(2N + 9). The device counts the widest tensor in channels per pixel, a proxy for activation memory. The real figures are in the table above.
At the defaults the inverted bottleneck costs 315,840 MACs per pixel, more than a standard 3×3 at 230,400. In the widest-tensor view it holds 6 times more channels. Set the expansion to 1 and the width falls back to N.
The tour ends with the Transformer's multi-head self-attention. Every token (a word, or an image patch) looks at every other token. The lecture's steps:
For N tokens of width d, the four projections cost 4Nd². The score matrix Q KT costs N²d, and weighting V costs another N²d. The slide writes O(N²d + N²d) ≈ O(N²): the cost grows with the square of the length.
The grid is one head's N×N attention map, shrunk to fit. The bars compare the projections with the map. Drag the number of tokens.
Illustrative sizes. 196 tokens is a 14 by 14 grid of image patches. MACs are 4Nd² for the projections and 2N²d for scores plus weighting, summed over all heads.
The two costs meet at N = 2d. Above it, the attention map dominates, and it stores N × N numbers per head.
pythonimport torch.nn as nn def inverted_bottleneck(n, t=6): # in (B, n, H, W) -> out (B, n, H, W) m = n * t return nn.Sequential( nn.Conv2d(n, m, 1), nn.BatchNorm2d(m), nn.ReLU6(), # expand: (B, m, H, W) nn.Conv2d(m, m, 3, padding=1, groups=m), nn.BatchNorm2d(m), nn.ReLU6(), # depthwise nn.Conv2d(m, n, 1), nn.BatchNorm2d(n)) # project, no ReLU
The last projection has no ReLU, a linear bottleneck, so the narrow tensor keeps its information.
Symptom: a block that looks cheap runs out of memory on the device. Measure: the widest tensor, N × t channels, times the map size. Fix: put the memory limit into the search space, as Chapter 7 does.
Chapter 4
Run the three-part loop of search space, search strategy and performance estimate, one round at a time
Ten engineers each tune one knob: layers, channels, kernels, connections, resolution. None of them sees all five at once. The lecture's picture replaces the people with a program. That is the move from manual design to automatic design.
Does it pay? The lecture plots known networks by cost, in billions of MACs, against ImageNet top-1 accuracy. The found nets (NASNet, AmoebaNet, DARTS, ProxylessNAS, MobileNetV3, EfficientNet, Once-for-All) sit above the handcrafted ones (ResNet, DenseNet, MobileNetV1 and V2, ShuffleNet) at the same cost.
The goal of NAS is the best network in a search space for an objective, such as accuracy or efficiency. Every method has three parts:
The strategy sends an architecture A to the estimator. The estimator returns a score. The strategy uses it to choose better next time. When the trial budget runs out, the best network found is the answer.
You rarely want accuracy alone. You want accuracy under a limit on latency, energy or memory. A hard constraint throws out any network over the limit. A soft penalty subtracts latency from the score, so a slow network loses points but can still win. Chapter 9 uses a penalty, and Chapter 10 a cutoff.
A toy run with a budget of 18 ms and made-up numbers:
A candidate wins only if it fits the budget and scores best among those that fit.
Illustrative: the 4,096 network toy space of the hero, a budget of 18 ms, and an estimator that returns the toy accuracy at once. A real estimator trains the network, which is the slow part.
Press Ten rounds a few times with each strategy. Random search spreads its tries over the whole space: it explores. Mutating the best keeps its tries near a good point: it exploits. Every strategy mixes the two.
pythondef nas(space, strategy, estimate, budget_ms, trials): best, best_acc = None, -1 history = [] # (arch, acc, ms) of every trial for _ in range(trials): arch = strategy.propose(space, history) # e.g. [0, 2, 1, 3, 0, 1], one op per layer acc, ms = estimate(arch) # the expensive call history.append((arch, acc, ms)) if ms <= budget_ms and acc > best_acc: # must fit AND score best best, best_acc = arch, acc return best
Symptom: a search planned for a day takes a season. Measure: trials times the cost of one estimate. At a toy 4 GPU-hours per estimate, 1,000 trials cost 4,000 GPU-hours. Fix: a cheaper estimator, such as shared weights or a predictor, the topic of NAS II.
Chapter 5
Build a network from one repeated cell, then derive how many cells the NASNet recipe can make
A mason does not design every brick. He designs one and repeats it. A search space is the set of candidate networks, and the lecture names two kinds: cell-level (this chapter) and network-level (Chapter 6).
NASNet (Zoph et al., CVPR 2018) fixes the skeleton of the network and searches only two small cells. A person sets how many cells and in what order. The search fills their insides.
A cell has B blocks, and B is 5 in the paper. A hidden state is a feature map a block can read, such as the output of an earlier cell. A controller builds each block with five picks, each from its own softmax:
So the controller has 5B softmax layers: 25 for B = 5. The cell outputs the concatenation of the hidden states that no block used.
Each input pick has 2 candidate hidden states. Call the number of candidate operations M, the number of ways to combine N, and the number of blocks B. The picks are independent, so their counts multiply.
The size of S equals 2 times 2 times M times M times N, all to the power B, which is 4 to the B, times M to the 2B, times N to the B.
Multiply the options of the five picks to get the choices for one block. Multiply that by itself once per block. The result is the size of S.
The lecture's M = 5, N = 2 and B = 5 give 4 × 25 × 2 = 200 choices per block, and 2005 = 3.2 × 1011 cells. At a toy 1 GPU-hour each, a thousand GPUs need about 36,500 years.
The five chips are the picks of one block. Their product is the choices per block. The bar is the count over B blocks, in powers of ten.
The formula is the lecture's, with two candidate inputs per pick. Time uses a toy 1 GPU-hour per cell and 1,000 GPUs. A cell that may also read earlier blocks of its own cell has more input choices and a larger space.
Set M = 13 and the count passes 1015, though the cell is tiny. One cell shrank the space, but it is still far beyond any exhaustive search.
pythonfrom itertools import product def cell_count(M, N, B): return (2 * 2 * M * M * N) ** B # the lecture's formula # check one block by brute force: input a, input b, op a, op b, combine M, N = 5, 2 one = len(list(product(range(2), range(2), range(M), range(M), range(N)))) print(one, cell_count(M, N, 5)) # 200 320000000000 print(cell_count(M, N, 5) / (1000 * 8766)) # about 36,500 years on 1,000 GPUs
Symptom: the best cell is good, but early and late stages cannot differ. Measure: every Normal Cell in the final network is a copy of one design. Fix: let each stage choose on its own, the network-level space of Chapter 6.
Chapter 6
Pick one option on each dimension of a whole-network space and count how many networks it holds
A cell search copies one design everywhere. But early stages work on large maps with few channels, and late stages on small maps with many. A network-level space lets each stage choose for itself. The lecture varies five dimensions, the first three on the Once-for-All (OFA) network.
| Dimension | What it sets | The lecture's options |
|---|---|---|
| Depth | Blocks in each of 4 stages | [1, 2, 3], [2, 3, 4], [3, 5, 7, 9], [1, 2, 3] |
| Resolution | Side of the input image, 3 channels | 128, 160, 192, 224, 256 |
| Width | Channels at 5 points | [48, 64, 96], [192, 256, 384], [384, 512, 768], [640, 1024, 1600], [1280, 2048, 3200] |
| Kernel size | The kernel of each depthwise layer | 3×3, 5×5, 7×7 (ProxylessNAS) |
| Topology | Which layers connect | A path across the Auto-DeepLab grid |
Choices multiply, as in Chapter 5. Depth gives 3 × 3 × 4 × 3 = 108, width gives 35 = 243, and resolution gives 5. That is 108 × 243 × 5 = 131,220 networks from short lists.
ProxylessNAS labels each mobile block with its expansion and kernel, such as MB6 5×5. One layer with expansion {3, 6} and kernel {3, 5, 7} has 6 options, so 20 layers give the 620 of Chapter 0. The lecture shows the network it found for a phone and the one for a CPU. Different hardware, different blocks.
Auto-DeepLab, built for segmentation, draws a grid: layers 1 to L across, downsampling rates 1 to 32 down. A path across the grid is a network. DeepLabv3, Conv-Deconv and Stacked Hourglass are three particular paths.
Depth adds cost in a line. Width and resolution add cost with their squares: channels sit on both sides of a convolution, and a map has H × W pixels. So 224 to 256 pixels costs 1.3 times more, and double the width costs 4 times more. A search can trade them under one budget.
Each column is a stage. Each block in a column is one bottleneck block. The square on the left is the input image, drawn to scale.
The option lists are the lecture's OFA lists. The space count treats every choice as independent. The relative cost is illustrative: it scales with resolution squared, with depth, and with width squared.
Try the smallest setting everywhere, then the largest. Every network between them is one point in the same space. In OFA one trained supernet serves them all, which Part II explains.
pythonimport math, random SPACE = { "depth": [[1,2,3], [2,3,4], [3,5,7,9], [1,2,3]], "width": [[48,64,96], [192,256,384], [384,512,768], [640,1024,1600], [1280,2048,3200]], "res": [128, 160, 192, 224, 256], } def sample(): return {k: ([random.choice(o) for o in v] if k != "res" else random.choice(v)) for k, v in SPACE.items()} size = math.prod(len(o) for o in SPACE["depth"]) * math.prod(len(o) for o in SPACE["width"]) * len(SPACE["res"]) print(size) # 131220 print(sample()) # one network: depths, widths, resolution
Symptom: the search ends no better than a baseline. Measure: where the winner sits in each list. At an edge, such as the largest width, the best answer may lie outside the space. Fix: widen that list, and accept that each new option multiplies the count.
Chapter 7
See why a microcontroller adds a memory wall, and how choosing the space beats any clever search inside a bad one
Dig for water in a dry field and the best machine finds nothing. Dig by a stream and a spoon works. The lecture says it plainly: search space design is crucial for NAS performance.
A phone must meet a latency limit and an energy limit. A microcontroller (MCU), a tiny computer on one chip, adds a third: memory. The lecture's numbers:
| Machine | Memory | Storage |
|---|---|---|
| Cloud GPU (NVIDIA V100) | 16 GB | TB to PB |
| Phone (iPhone 11) | 4 GB, which is 4 times less | more than 64 GB |
| Microcontroller (STM32F746) | 320 kB, which is about 12,500 times less than the phone by division (the slide's arrow says 3,100 times) | 1 MB, which is 64,000 times less than the phone |
| Model | Memory | Storage |
|---|---|---|
| ResNet-50 | 7.2 MB | 102 MB |
| MobileNetV2 | 6.8 MB | 13.6 MB |
| MobileNetV2, 8-bit integers | 1.7 MB | 3.4 MB |
Even the 8-bit model is five times over the 320 kB memory. So the search space must start from the wall.
TinyNAS, from MCUNet (Lin et al., NeurIPS 2020), splits the work:
Candidate spaces scale width and input resolution, with names like w0.5-r144: width multiplier 0.5, input 144 pixels. Training a network from each is too slow. So the lecture uses a proxy with three links: more FLOPs, more capacity, more likely high accuracy.
Sample networks from a space, keep those under the memory limit, and plot the cumulative distribution of their FLOPs. A curve further right is a better space. At the 80 percent line, the lecture marks a bad space at 32.3 M FLOPs and a good one at 50.3 M.
The chosen space reaches 78.7 percent, against 74.7 ± 1.9 for a random space and 77.0 for a huge one. ResNet-18 at 224 pixels reaches 80.3 percent but runs out of memory. Higher mean FLOPs track higher final accuracy.
Each cell shows the mean FLOPs of the toy networks in that space that fit the limit. Grey cells have almost none that fit. Tap a cell for details, or let the device pick.
Illustrative: toy formulas, memory = 0.008 · width · resolution² · expansion kB and FLOPs = 0.00035 · width² · resolution² · expansion · depth M, over 400 seeded random networks per space. The real method uses the MCUNet search space and real memory profiles.
At 64 kB most spaces are grey, and the best is small. At 512 kB the best moves up and to the right. The best space depends on the device, so TinyNAS runs the first stage per device.
pythonimport numpy as np def space_score(w, r, mem_limit_kb, configs): # configs: list of (expansion e, depth d) mem = np.array([0.008 * w * r**2 * e for e, d in configs]) flops = np.array([0.00035 * w**2 * r**2 * e * d for e, d in configs]) ok = mem <= mem_limit_kb # the memory wall return flops[ok].mean() if ok.mean() > 0.05 else float("nan") # best = the (w, r) with the largest mean FLOPs among spaces where networks fit
Symptom: the search returns nothing, or a network far below the budget. Measure: the share of the space that fits the limit. Near zero, the space is too big. If all fit with tiny FLOPs, it is too small. Fix: move the space, not the search.
Chapter 8
Compare three ways to pick the next design, and watch a controller learn from reward with the REINFORCE rule
Which design do you train next? The lecture lists five strategies. Here are the first three.
| Grid search | Random search | |
|---|---|---|
| How it picks | Every combination of a few values per knob, each trained from scratch | A fresh random draw for every trial |
| 9 trials, one knob matters | Tests 3 values of that knob | Tests 9 values of it |
| Cost | The product of the list lengths | Whatever trial budget you set |
In the lecture's grid, the most accurate cell (56.2 percent) breaks the latency limit. The best that fits is 54.9 percent.
Rows are width, columns resolution. Tap a cell to train it. Green fits the latency limit; red breaks it.
Accuracies and the latency limit are from the lecture's grid-search slide. The device counts cells, not hours.
EfficientNet grid-searches three numbers once. Call the depth, width and resolution multipliers d, w and r. In compound scaling, one dial φ grows all three through base numbers α, β, γ.
d equals alpha to the phi, w equals beta to the phi, r equals gamma to the phi, subject to alpha times beta squared times gamma squared being about 2.
Pick phi. Raise alpha, beta and gamma to the phi to get d, w and r. The constraint makes each step of phi about double the FLOPs.
The EfficientNet paper reports alpha 1.2, beta 1.1, gamma 1.15: 1.2 × 1.21 × 1.3225 = 1.92. So phi = 1 gives 1.92 times the FLOPs.
Reinforcement learning (RL) learns from past scores. An RNN controller with weights θ writes a network as tokens (filter height, filter width, stride, number of filters). Call its chance of writing architecture a πθ(a).
The sampled child network trains, and its accuracy is the reward R(a). A running average of rewards is the baseline b. REINFORCE raises the average reward J:
Grad-theta of J equals the expected value of R of a minus b, times grad-theta of log pi-theta of a.
Sample a and train it. Subtract b from its reward R of a. Make a more likely by that amount if it beat b, less likely if not.
Made up: R of a = 74.2 and b = 72.0, an advantage of 2.2. Below, the chosen chance rises from 0.30 to 0.35.
Each bar is the controller's chance of picking one of four operations. The tick is that operation's true mean accuracy, hidden from the controller.
Illustrative: true mean accuracies 70, 72, 74 and 66 percent, noise about 1 point, step size 0.1, baseline a running average.
pythonimport torch, torch.nn as nn class Controller(nn.Module): def __init__(self, n_ops=4, n_layers=6, hid=64): super().__init__() self.cell, self.emb = nn.LSTMCell(hid, hid), nn.Embedding(n_ops + 1, hid) self.head, self.n_layers, self.hid = nn.Linear(hid, n_ops), n_layers, hid def sample(self): # returns tokens (6,) and the sum of log-probs h = c = torch.zeros(1, self.hid); x = self.emb(torch.tensor([4])) # start token toks, logp = [], 0.0 for _ in range(self.n_layers): h, c = self.cell(x, (h, c)) dist = torch.distributions.Categorical(logits=self.head(h)) # softmax over ops t = dist.sample(); logp = logp + dist.log_prob(t) toks.append(t.item()); x = self.emb(t) # feed the choice back in return toks, logp # one step: reward = accuracy(train(build(toks))); baseline b = 0.9*b + 0.1*reward # loss = -(reward - b) * logp; loss.backward(); optimizer.step()
Symptom: two runs end at different networks. Cause: without a baseline, every noisy reward near 70 pushes its pick up. Turn the baseline off to see it. Fix: a baseline and many samples. RL still needs thousands of trained children.
Chapter 9
Replace a hard pick among operations with a soft mix, then train the mix by gradient descent with a latency penalty
A hard pick among operations has no slope. DARTS (Liu et al., ICLR 2019) makes the pick smooth, so gradient descent can train it.
An edge of a cell may apply any operation o from a set O: a convolution, a pooling, or zero (no connection). Give each a number αo, its architecture parameter. The edge outputs a blend:
o-bar of x equals the sum over o in O of e to the alpha-o, over the sum over o-prime of e to the alpha-o-prime, times o of x.
Turn the alphas into weights with a softmax. Run every operation on x. Add the outputs, each scaled by its weight.
Made-up outputs 1.0, 2.0, 0.2 for k3, k5, skip, and every alpha 0: each weight is 1/3, so the mix is 3.2 / 3 = 1.067.
At the end, each edge keeps its most likely operation, the argmax of α.
Now there are weights w and parameters α. With training loss Ltrain and held-out loss Lval, the goal is bilevel, one optimization inside another:
Minimize over alpha the L-val of w-star of alpha and alpha, such that w-star of alpha is the argmin over w of L-train of w and alpha.
For an alpha, train the weights on L-train to get w-star. Score that pair on L-val. Choose the alpha with the lowest L-val.
Made up: alpha A trains to L-train 0.20, L-val 0.65. Alpha B trains to 0.30 and 0.55. The outer problem picks B.
Full training per α is too slow, so DARTS alternates: one step on w with Ltrain, one on α with Lval.
ProxylessNAS adds latency. Device measurement is expensive and slow, so a model F (a regressor or lookup table) predicts it. Call operation o's weight po.
Loss equals Loss-CE plus lambda-1 times the norm of w squared, plus lambda-2 times E of latency. E of latency is the sum over o of p-o times F of o.
Weight each F of o by its p-o and add: that is E of latency. Add lambda-2 times it to the loss. Its gradient pushes alpha toward fast operations.
Made up: weights 1/3 and F = 2.0, 3.5, 0.4 ms give E of latency = 1.97 ms. With lambda-2 = 0.5, Loss-CE 1.20 and decay 0.05: 1.20 + 0.05 + 0.98 = 2.23.
Bars are the softmax weights. The line below marks each output, the mix and the target. Train, raise the penalty, train again.
Illustrative, made-up numbers. Loss: squared error to 1.8, plus λ times the expected latency. Step 0.5.
pythonimport torch, torch.nn as nn, torch.nn.functional as F class MixedOp(nn.Module): def __init__(self, ops, lat): # ops: list of modules; lat: list of ms super().__init__() self.ops, self.lat = nn.ModuleList(ops), torch.tensor(lat) self.alpha = nn.Parameter(torch.zeros(len(ops))) # architecture parameters def forward(self, x): # x (B, C, H, W) -> (B, C, H, W) p = F.softmax(self.alpha, dim=0) return sum(pi * op(x) for pi, op in zip(p, self.ops)) def expected_latency(self): return (F.softmax(self.alpha, dim=0) * self.lat).sum() # alternate: step w on the train batch, step alpha on a val batch with CE + lam * latency
Train with λ = 0: the blend hits the target, but k5 alone misses. So the final argmax network is worse than the supernet. Fix: retrain it from scratch. At λ = 0.5 the weight moves to skip.
Chapter 10
Evolve a population of networks with a fitness that mixes accuracy and latency
A dog breeder breeds the best of each litter. After many litters the dogs improve, and no one drew the final dog. Evolutionary search works the same way: a population of networks, a score for each, and a loop that breeds new networks from the fit ones.
The fitness function F(accuracy, efficiency) scores a network. The lecture samples sub-networks of an Once-for-All (OFA) network against a target of 10 ms and 80 percent:
Fitness does the job of the latency penalty in Chapter 9. Evolution needs no gradient, so F can be any rule, even a hard cutoff.
A mutation changes one thing in a network. A crossover builds a child from two parents: for each layer, take one parent's operator at random. The lecture's examples use OFA mobile blocks, where MB6 3×3 means expansion 6 and a 3×3 kernel.
| Move | Before | After |
|---|---|---|
| Mutation on depth | Stage 1: 3 blocks. Stage 2: 3 blocks. | Stage 1: 2 blocks. Stage 2: 4 blocks. |
| Mutation on operator | Six MB6 3×3 blocks | MB6 3×3, MB6 5×5, MB6 5×5, MB4 5×5, MB6 3×3, MB6 7×7 |
| Crossover | Parent 1: 3×3 at all six layers. Parent 2: 3×3, 5×5, 5×5, 5×5 (MB4), 3×3, 7×7. | Layers 1, 3, 4 from parent 1 and 2, 5, 6 from parent 2: 3×3, 5×5, 3×3, 3×3, 3×3, 7×7 |
Mutation explores near a good network. Crossover can join the good early part of one network to the good late part of another in one step.
Blue dots are the population. The green ring is the best network that fits. The strips show the last crossover and the last mutation, one cell per layer.
Illustrative: the 4,096 network toy space of the hero. Fitness is the toy accuracy for networks under the budget, and a penalty for those over it. Each layer is one of k3, k5, k7 or skip. Population 12: each generation the 6 fittest survive, and 3 mutants and 3 crossovers fill the places.
Press Ten generations twice: the population climbs toward the best network that fits. Drag the budget down, and within a few generations the population drifts left.
Keep too few survivors and the population becomes copies, so crossover has nothing to mix. Keep too many and weak networks hold it back. Small mutations keep a good network good; large ones explore but often break it. The lecture also cites Regularized Evolution (Real et al., AAAI 2019), which removes the oldest network instead of the weakest.
pythonimport random def evolve(init, fitness, mutate, crossover, gens=20, keep=6): pop = init(12) # list of 12 archs, e.g. [0, 2, 1, 3, 0, 1] for _ in range(gens): pop.sort(key=fitness, reverse=True) parents = pop[:keep] # survivor selection kids = [mutate(random.choice(parents)) for _ in range(3)] kids += [crossover(*random.sample(parents, 2)) for _ in range(3)] pop = parents + kids return max(pop, key=fitness) def crossover(a, b): # the lecture's rule: per layer, flip a coin return [random.choice(pair) for pair in zip(a, b)]
Symptom: the winner is accurate but too slow. Measure: its latency against the limit. With accuracy alone as fitness, the population drifts to big networks. Fix: put efficiency in F. Every fitness call also needs an accuracy estimate, and Part II shows how OFA makes it cheap.
Chapter 11
Keep the numbers, terms, checklist and code, and find the next lecture
Here is the lecture in one paragraph. A network uses a few layer types, and each has a MAC price. Blocks such as the bottleneck, the depthwise-separable block and the inverted bottleneck are ways to buy the same job for fewer MACs. A search space is a menu of those choices, at the level of a cell or of the whole network. A search strategy walks the menu, and an estimator scores each pick. On tiny devices, the memory wall makes the choice of space matter as much as the strategy.
| What | Value | Where |
|---|---|---|
| Standard conv MACs | co · ci · kh · kw · ho · wo | Chapter 1 |
| Depthwise saving | ci times fewer MACs | Chapter 1 |
| ResNet50 bottleneck | 512² × 17 against 512² × 144: 8.5 times fewer | Chapter 2 |
| MobileNetV2 block, N = 160 | 960 × 329 MACs per pixel | Chapter 3 |
| MobileNetV2 against ResNet | 4.6 times fewer parameters but 1.8 times less peak activation (inference); 4.3 and 1.1 times in training | Chapter 3 |
| NASNet-style cell space | (4 M² N)B = 3.2 × 1011 at M = 5, N = 2, B = 5 | Chapter 5 |
| OFA-style space from the slide lists | 108 × 243 × 5 = 131,220 networks | Chapter 6 |
| Memory: V100, iPhone 11, STM32F746 | 16 GB, 4 GB, 320 kB | Chapter 7 |
| TinyNAS space accuracy | 78.7 percent, against 74.7 ± 1.9 (random) and 77.0 (huge) | Chapter 7 |
| Grid example | Best that fits: 54.9 percent; most accurate: 56.2 percent, over the limit | Chapter 8 |
| Compound scaling | α · β² · γ² ≈ 2 | Chapter 8 |
| Strategy | How it picks the next design | Needs | Weak point |
|---|---|---|---|
| Grid | Every combination of a few values | A short list per knob | Cost multiplies with every knob |
| Random | A fresh random draw | Nothing but a sampler | Ignores what it has learned |
| Reinforcement learning | A controller samples, reward updates it | A trained network per sample | Noisy, thousands of samples |
| Gradient | Soft mix of choices, trained by backprop | A differentiable mix; latency model | The argmax gap |
| Evolution | Mutate and cross over the fit | A fitness for each network | Every fitness call needs an estimate |
The whole loop fits in a page. This sketch uses the toy space of the hero. It compares random search and evolution under one budget. Shapes are in the comments.
pythonimport math, random LAT = [2.0, 3.5, 5.0, 0.4] # ms per layer for k3, k5, k7, skip (toy) POW = [1.0, 1.35, 1.6, 0.15] W = [.55, .8, 1, 1, .8, .55] # how much each layer matters def estimate(arch): # arch: list of 6 ints in 0..3 -> (accuracy %, latency ms) ms = 2 + sum(LAT[o] for o in arch) acc = 52 + 26 * (1 - math.exp(-sum(w * POW[o] for w, o in zip(W, arch)) / 3.4)) return acc, ms # a real estimator trains the network here def fitness(arch, budget): acc, ms = estimate(arch) return acc if ms <= budget else -ms # over budget: always loses def mutate(a): i = random.randrange(len(a)); b = a[:]; b[i] = random.randrange(4); return b def random_search(budget, trials): archs = [[random.randrange(4) for _ in W] for _ in range(trials)] return max(archs, key=lambda a: fitness(a, budget)) def evolve(budget, trials, pop_size=12): pop = [[random.randrange(4) for _ in W] for _ in range(pop_size)] for _ in range((trials - pop_size) // 6): pop.sort(key=lambda a: -fitness(a, budget)) par = pop[:6] # survivor selection kids = [mutate(random.choice(par)) for _ in range(3)] kids += [[random.choice(p) for p in zip(*random.sample(par, 2))] for _ in range(3)] # crossover pop = par + kids return max(pop, key=lambda a: fitness(a, budget)) random.seed(0) for f in (random_search, evolve): a = f(16, 100); print(f.__name__, a, [round(x, 1) for x in estimate(a)])
This lecture sets up the search. The next lecture, NAS II, covers the rest of the plan: performance estimation, hardware-aware NAS, zero-shot NAS, neural-hardware co-search and applications in NLP, GANs, point clouds and pose. The memory wall of Chapter 7 comes back in full in MCUNet.
This lesson follows Lecture 7 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. Read the lecture on the course site, where the slides are linked. The papers it cites include NASNet (Zoph et al.), DARTS (Liu et al.), ProxylessNAS and Once-for-All (Cai et al.), MobileNetV2 (Sandler et al.), EfficientNet (Tan and Le) and MCUNet (Lin et al.). The explanations, devices and toy numbers here are our own.
Now press Teach and explain, from memory, how REINFORCE or DARTS picks an operation, and why the choice of space comes first. Then go back to the search at the top and change the budget once more.