Neural Architecture Search I

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.

Search under a budget

16 ms

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

Why Efficient Models Need a Search

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.

What you trade

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).

Count the space

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.

Say it aloud

N equals m to the L, which is 6 to the 20, about 3.7 times 10 to the 15.

N
N the number of different networks in the space.
m
m the number of operations one layer may pick: 6 here.
L
to the L multiply by m once per layer, because each of the L layers picks on its own: 20 layers here.
In plain words

Each layer picks one of m operations, whatever the other layers pick. So multiply m by itself L times. The product is N.

With numbers

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.

Count the designs

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.

20
6

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.

Who does what

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.

The road

  1. Count the cost of every layer type: the five primitive layers and MACs.
  2. Bottlenecks and groups: ResNet and ResNeXt, with the 8.5 times saving.
  3. Mobile and attention blocks: MobileNet, MobileNetV2, ShuffleNet and attention.
  4. What NAS is: the loop of space, strategy and estimate.
  5. Cell-level spaces: NASNet cells and the count of 3.2 × 1011.
  6. Network-level spaces: depth, width, resolution, kernel size and topology.
  7. Designing the space: memory limits and TinyNAS.
  8. Grid, random and RL: three ways to pick the next design.
  9. Gradient search: DARTS and the latency penalty.
  10. Evolution: mutation, crossover and fitness.
  11. The field guide: numbers, code and where to go next.
A team can train 8.8 million networks in a year. Their space holds 3.7 × 1015 networks. What does this tell them?

Chapter 1

Count the Cost of Every Layer Type

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.

Linear and convolution

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).

Say it aloud

h-o equals h-i plus 2 p minus k-h, all over s, plus 1.

ho
h-o the output height. The width follows the same rule.
hi
h-i the input height in pixels.
p
p the padding: rows of zeros added at the top and at the bottom.
kh
k-h the kernel height: 3 for a 3 by 3 kernel.
s
over s the stride: how many pixels the window jumps each step.
In plain words

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.

With numbers

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.

Say it aloud

MACs equal c-o times c-i times k-h times k-w times h-o times w-o.

MACs
MACs the multiply-accumulates for one image.
co
c-o the output channels: one stack of kernels each.
ci
c-i the input channels that each kernel stack reads.
kh · kw
k-h times k-w the cells of one kernel: 9 for 3 by 3.
ho · wo
h-o times w-o the output positions.
In plain words

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.

With numbers

A 3 by 3 layer, 64 channels, 56 by 56 map: 64 · 64 · 9 · 56 · 56 = 115,605,504 MACs.

Three cheaper cousins

LayerMACs, batch of 1, bias ignored
Linearco · ci
Convolutionco · ci · kh · kw · ho · wo
Grouped convolutionco · ci · kh · kw · ho · wo / g
Depthwise convolutionco · kh · kw · ho · wo
1×1 convolutionco · ci · ho · wo

All four at the same shape:

  1. Standard: 64 · 64 · 9 · 56 · 56 = 36,864 · 3,136 = 115,605,504 MACs, about 116 M.
  2. Grouped, g = 4: 115,605,504 / 4 = 28,901,376 MACs, about 29 M.
  3. Depthwise: 64 · 9 · 3,136 = 1,806,336 MACs, about 1.8 M.
  4. 1×1: 64 · 64 · 3,136 = 12,845,056 MACs, about 12.8 M.

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.

Price four convolutions

Each bar is MACs for one layer at the shape you set. The standard bar is the reference. Drag any slider.

64
56
3
4

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

The failure: trusting MACs alone

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.

A standard convolution uses 64 channels in and out. You swap it for a depthwise convolution at the same kernel and map size. How do the MACs change?

Chapter 2

Squeeze, Convolve, Expand: Bottlenecks and Groups

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.

Squeeze, convolve, expand

The ResNet50 bottleneck block has three layers: wide, narrow, wide again.

  1. Squeeze. A 1×1 convolution, weights (512, 2048, 1, 1), cuts 2048 channels to 512, a factor of 4.
  2. Convolve. A 3×3 convolution, weights (512, 512, 3, 3), works on 512 channels. It is the only layer that looks at neighbours.
  3. Expand. A 1×1 convolution, weights (2048, 512, 1, 1), takes 512 channels back to 2048.

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.

Say it aloud

512 times 512 times 144, over 512 times 512 times 17, is about 8.5.

512² × 144
512 squared times 144 the plain 3×3 layer on 2048 channels, per pixel: 37,748,736 MACs.
512² × 17
over 512 squared times 17 the whole bottleneck block, per pixel: 4,456,448 MACs.
≈ 8.5
is about 8.5 how many times cheaper the block is.
In plain words

Divide the plain cost by the block cost. The 512 times 512 cancels, so the saving is 144 over 17.

With numbers

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.

Groups: ResNeXt

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.

Squeeze the block

Top: one plain 3×3 layer on 2048 channels. Bottom: the bottleneck, as squeeze, convolve and expand. Set the inner width and the groups.

512
1

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

The failure: squeezing too hard

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.

In the ResNet50 bottleneck, what makes the block about 8.5 times cheaper than a plain 3×3 layer on 2048 channels?

Chapter 3

Depthwise, Inverted and Attention Blocks

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.

BlockThe trickMACs per pixel, width N
MobileNet: depthwise-separableA depthwise 3×3 captures space, one channel at a time. A 1×1 then fuses information across channels.9N + N²
MobileNetV2: inverted bottleneckA 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)
ShuffleNetThe 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.

The catch: memory

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:

SettingParametersActivation
Inference, 8-bit, batch 1: MobileNetV2-0.75 against ResNet-184.6 times fewer1.8 times less (peak)
Training, 32-bit, batch 16: MobileNetV2-1.4 against ResNet-504.3 times fewer (24 MB against 102 MB)1.1 times less (626 MB against 707 MB)

Price the mobile blocks

160
6

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.

Attention is a block too

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:

  1. Project the input into queries Q, keys K and values V, with h different learned linear projections, one set per head.
  2. On each head, compute scaled dot-product attention: softmax(Q KT / √dk) V.
  3. Concatenate the heads' outputs.
  4. Project the result again with one more linear layer.

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.

Price an attention block

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.

196
256

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.

The failure: counting only MACs

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.

MobileNetV2 has far fewer parameters than ResNet-50 but saves little activation memory in training. What is the main reason?

Chapter 4

Search for a Network Instead of Drawing One

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.

Three parts in one loop

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:

  1. Search space 𝒜. The set of networks the program may consider. It is the menu.
  2. Search strategy. The rule that picks which network from the menu to try next.
  3. Performance estimation strategy. The way to score the network the strategy picked, and to hand the score back.

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.

The objective

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.

One run, every step

A toy run with a budget of 18 ms and made-up numbers:

  1. Round 1. The strategy picks network A1. The estimator says 68.0 percent at 14 ms. It fits, and it becomes the best so far.
  2. Round 2. A2 scores 71.5 percent at 21 ms. It is over budget, so the search rejects it, even though its accuracy is higher.
  3. Round 3. A3 scores 70.2 percent at 17 ms. It fits and beats A1, so it becomes the best so far.

A candidate wins only if it fits the budget and scores best among those that fit.

Run the loop

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

The failure: an estimator that costs too much

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.

Which three parts does every NAS method have?

Chapter 5

Search a Small Cell and Count the Space

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: two cells, stacked

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.

Inside a cell

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:

  1. Select one hidden state as the first input.
  2. Select a second hidden state as the second input.
  3. Select an operation to apply to the first input (for example a 3×3 convolution, a pooling or the identity).
  4. Select an operation to apply to the second input.
  5. Select a method to combine the two results (for example add).

So the controller has 5B softmax layers: 25 for B = 5. The cell outputs the concatenation of the hidden states that no block used.

Derive the size of the space

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.

Say it aloud

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.

|S|
the size of S the number of different cells: the size of the search space.
2 × 2
2 times 2 two input picks, each from 2 candidate hidden states.
M
M the candidate operations. It appears twice, because each input gets its own operation.
N
N the ways to combine the two results, such as add.
B
to the power B one factor per block, because each block picks on its own. The designer fixes B.
In plain words

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.

With numbers

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.

Count the cells

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.

5
2
5

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

The failure: every stage looks the same

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.

In the formula (2 × 2 × M × M × N)B, why does M appear twice?

Chapter 6

Search Depth, Width, Resolution and Kernels

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.

DimensionWhat it setsThe lecture's options
DepthBlocks in each of 4 stages[1, 2, 3], [2, 3, 4], [3, 5, 7, 9], [1, 2, 3]
ResolutionSide of the input image, 3 channels128, 160, 192, 224, 256
WidthChannels at 5 points[48, 64, 96], [192, 256, 384], [384, 512, 768], [640, 1024, 1600], [1280, 2048, 3200]
Kernel sizeThe kernel of each depthwise layer3×3, 5×5, 7×7 (ProxylessNAS)
TopologyWhich layers connectA 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.

Kernels and topology

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.

Why the dimensions pull on each other

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.

Pick one network

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.

2
3
5
2
middle
224

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

The failure: a space that leaves the answer out

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.

A space has 3 depth options in each of 4 stages, 3 width options in each of 5 slots and 5 resolutions. Roughly how many networks does it hold?

Chapter 7

Design the Space Before You Search It

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 new wall: memory

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:

MachineMemoryStorage
Cloud GPU (NVIDIA V100)16 GBTB to PB
Phone (iPhone 11)4 GB, which is 4 times lessmore 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
ModelMemoryStorage
ResNet-507.2 MB102 MB
MobileNetV26.8 MB13.6 MB
MobileNetV2, 8-bit integers1.7 MB3.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: two stages

TinyNAS, from MCUNet (Lin et al., NeurIPS 2020), splits the work:

  1. Search space optimization. Out of many candidate spaces, find the one most likely to hold good networks that fit the memory limit.
  2. Resource-constrained model specialization. Search inside that one space for the network that fits the device.

Score a space without training

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.

Rank the spaces

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.

256 kB

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

The failure: a space with nothing that fits

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.

TinyNAS compares candidate spaces without training any network. What does it measure?

Chapter 8

Grid, Random and Reinforcement Learning

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 and random search

Grid searchRandom search
How it picksEvery combination of a few values per knob, each trained from scratchA fresh random draw for every trial
9 trials, one knob mattersTests 3 values of that knobTests 9 values of it
CostThe product of the list lengthsWhatever 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.

  1. Width 1.0×: 50.0, 53.0 and 54.9 percent. All three fit.
  2. Width 1.1×: 51.0 percent fits. 53.5 and 55.4 break the limit.
  3. Width 1.2×: 52.0 percent fits. 54.1 and 56.2 break the limit.

Walk the grid

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: a small grid for a big rule

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 α, β, γ.

Say it aloud

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.

d
d the depth multiplier: how many times more layers.
w
w the width multiplier: how many times more channels.
r
r the resolution multiplier: how many times larger the input side.
α
alpha the depth growth per step of phi, found by a small grid search.
β
beta the width growth per step of phi.
γ
gamma the resolution growth per step of phi.
φ
to the phi the one dial you turn: how many steps of extra compute.
αβ²γ² ≈ 2
alpha beta squared gamma squared, about 2 FLOPs grow with depth, width squared and resolution squared, so each step of phi doubles them.
In plain words

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.

With numbers

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

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:

Say it aloud

Grad-theta of J equals the expected value of R of a minus b, times grad-theta of log pi-theta of a.

∇θ J
grad-theta of J the direction to move theta that raises J, the average reward, fastest.
E
the expected value the average over many sampled architectures a.
R(a)
R of a the accuracy of the trained child network a.
b
minus b the baseline. Subtracting it keeps each step small and steady.
∇ log πθ(a)
grad-theta of log pi-theta of a the direction that makes the controller more likely to write a again.
In plain words

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.

With numbers

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.

  1. A layer picks among three operations with chances (0.5, 0.3, 0.2) and samples the second. The advantage is 74.2 − 72.0 = 2.2.
  2. For a softmax, the gradient of log π with respect to each logit is (1 if chosen, else 0) minus its chance: (−0.5, +0.7, −0.2).
  3. Multiply by the advantage: (−1.1, +1.54, −0.44).
  4. With a step size of 0.1, the logits move by (−0.11, +0.154, −0.044).
  5. The chances become about (0.453, 0.354, 0.193).

Train a controller

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()

The failure: huge variance

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.

A controller samples a network that scores 74.2 percent. The baseline is 72.0. What does REINFORCE do?

Chapter 9

Make the Choice Differentiable

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.

Soften the choice

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:

Say it aloud

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.

ο̄(x)
o-bar of x the mixed operation: the edge's output, a blend of every candidate.
∑o ∈ O
the sum over o in O add one term for each candidate operation.
eαo / ∑ eαo′
e to the alpha-o, over the sum of e to the alpha-o-prime the softmax weight of operation o: positive, and all weights add to 1.
o(x)
times o of x what operation o alone outputs for the input x.
In plain words

Turn the alphas into weights with a softmax. Run every operation on x. Add the outputs, each scaled by its weight.

With numbers

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 α.

Two sets of numbers, two losses

Now there are weights w and parameters α. With training loss Ltrain and held-out loss Lval, the goal is bilevel, one optimization inside another:

Say it aloud

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.

minα
minimize over alpha find the architecture parameters that make what follows smallest.
Lval
L-val the loss on held-out validation data.
w*(α)
w-star of alpha the best weights for one fixed alpha.
argminw
the argmin over w the weights that make the training loss smallest.
Ltrain
L-train the loss on the training data.
In plain words

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.

With numbers

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.

Put latency in the loss

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.

Say it aloud

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.

Loss
Loss what the search makes smaller.
LossCE
Loss-CE the cross-entropy loss: how wrong the predictions are.
λ1‖w‖2
lambda-1 times the norm of w squared weight decay: a small cost on large weights.
λ2
lambda-2 the trade dial between accuracy and latency, above 0.
E[latency]
E of latency the expected latency of a block. The network's is the sum over its blocks.
Σo
the sum over o add one term for each candidate operation.
po
p-o the softmax weight of operation o.
F(o)
F of o the predicted latency of operation o, such as F of conv 3 by 3.
In plain words

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.

With numbers

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.

One step, by hand

  1. Take the edge above, a target y = 1.8 and no penalty. The mix is 1.067, so the squared error is (1.067 − 1.8)² = 0.54.
  2. The loss gradient for each output is 2(mix − y) ok = −1.467 · ok, which gives (−1.467, −2.933, −0.293). Their weighted mean is −1.564.
  3. The gradient on αj is sj (gj minus that mean): (0.032, −0.456, +0.424).
  4. A step of 0.5 downhill moves α to (−0.016, +0.228, −0.212).
  5. The weights become about (0.32, 0.41, 0.27). The k5 weight rose from 0.33 to 0.41.

Train the dial

Bars are the softmax weights. The line below marks each output, the mix and the target. Train, raise the penalty, train again.

0.00

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

The failure: the argmax gap

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.

Why does ProxylessNAS use a latency model F instead of measuring latency at each search step?

Chapter 10

Mutate, Cross Over and Keep the Fit

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.

  1. Initialize a population of random networks.
  2. Compute fitness for each network.
  3. Crossover: make children by mixing two parents.
  4. Mutation: change a child a little, at random.
  5. Survivor selection: keep the fittest, drop the rest.
  6. Repeat until a stop rule fires, then return the best.

Fitness: accuracy and efficiency together

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.

Mutation and crossover

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.

MoveBeforeAfter
Mutation on depthStage 1: 3 blocks. Stage 2: 3 blocks.Stage 1: 2 blocks. Stage 2: 4 blocks.
Mutation on operatorSix MB6 3×3 blocksMB6 3×3, MB6 5×5, MB6 5×5, MB4 5×5, MB6 3×3, MB6 7×7
CrossoverParent 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.

Evolve the population

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.

16 ms

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.

Two dials

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)]

The failure: a fitness that ignores the budget

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.

A child is built from two parents by choosing, for each layer, the operator of one parent at random. What is this operation called?

Chapter 11

Field Guide

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.

Numbers to remember

WhatValueWhere
Standard conv MACsco · ci · kh · kw · ho · woChapter 1
Depthwise savingci times fewer MACsChapter 1
ResNet50 bottleneck512² × 17 against 512² × 144: 8.5 times fewerChapter 2
MobileNetV2 block, N = 160960 × 329 MACs per pixelChapter 3
MobileNetV2 against ResNet4.6 times fewer parameters but 1.8 times less peak activation (inference); 4.3 and 1.1 times in trainingChapter 3
NASNet-style cell space(4 M² N)B = 3.2 × 1011 at M = 5, N = 2, B = 5Chapter 5
OFA-style space from the slide lists108 × 243 × 5 = 131,220 networksChapter 6
Memory: V100, iPhone 11, STM32F74616 GB, 4 GB, 320 kBChapter 7
TinyNAS space accuracy78.7 percent, against 74.7 ± 1.9 (random) and 77.0 (huge)Chapter 7
Grid exampleBest that fits: 54.9 percent; most accurate: 56.2 percent, over the limitChapter 8
Compound scalingα · β² · γ² ≈ 2Chapter 8

The five strategies side by side

StrategyHow it picks the next designNeedsWeak point
GridEvery combination of a few valuesA short list per knobCost multiplies with every knob
RandomA fresh random drawNothing but a samplerIgnores what it has learned
Reinforcement learningA controller samples, reward updates itA trained network per sampleNoisy, thousands of samples
GradientSoft mix of choices, trained by backpropA differentiable mix; latency modelThe argmax gap
EvolutionMutate and cross over the fitA fitness for each networkEvery fitness call needs an estimate

Before you run a search

The core as code

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)])

Where it sits in the field

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.

Keep going

The takeaway. NAS has three parts: a space, a strategy and an estimator. The space sets what can be found, the strategy sets how fast, and the estimator sets what it costs. Fix the space first.
A search with a clever strategy keeps returning weak networks for a microcontroller. What should you check first?

Credit

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.

MIT 6.5940 Lecture 7: Neural Architecture Search (Part I)
The course site and slides · Previous: Quantization II · Next: NAS II · Back to Gleams