Part 09›
✎

05. Neural Architecture Search#

Level: Practitioner · Reading time: 15 min · Exercise: 45 min Prerequisites: Neural Network Basics for Efficiency, Pruning and Sparsity

In one sentence: After this chapter you can define a search space and a cost model for a target device, run a small search over it, and decide when a once-for-all network saves you retraining a model per device.

Why this matters#

You need an image model for a microcontroller with 256 KB of memory. Your options are a pruned ResNet, a narrow MobileNet, or a design of your own. Each of those families was tuned by hand for someone else's hardware and data.

Chapter 03 shrinks a model that already exists. This chapter asks the question one step earlier: why start from a model designed for a data-center GPU?

The core idea#

Neural architecture search (NAS) replaces hand design with a loop over three parts, the same three Han puts on his slides (Lecture 7, slides 43 and 44):

  1. A search space: the set of allowed architectures, described by a few choices.
  2. A search strategy: how to pick the next candidate.
  3. A performance estimate: accuracy together with a cost such as latency or memory.

Figure 1. The NAS loop: a strategy proposes, an estimate scores, and the best candidate wins.

flowchart LR
    S["Search space"] --> T["Search strategy picks a candidate"]
    T --> E["Performance estimate scores it"]
    E -->|"score"| T
    T -->|"after many rounds"| B["Best architecture for the device"]

Each round trains and measures one candidate, so the estimate is where the search spends its money.

The analogy is a query planner or an autotuner. You state the goal and the constraints; the system picks a plan. The analogy breaks on the price of a lookup. A planner estimates a plan in microseconds. Here the accuracy of one candidate costs a training run of hours, and short runs rank candidates noisily. Most of NAS is about paying for fewer lookups.

How it works, step by step#

Step 1: Pick the building blocks#

Han spends the first half of Lecture 7 on the blocks a search space is built from (slides 16 to 37):

Block Used by Why it is cheap
Bottleneck ResNet-50 a 1 × 1 layer squeezes channels before the expensive 3 × 3 layer
Grouped convolution ResNeXt weights divided by the number of groups
Depthwise separable MobileNet one filter per channel, then a cheap 1 × 1 mix
Inverted bottleneck MobileNetV2 expands channels cheaply, applies depthwise convolution, projects back
Grouped 1 × 1 plus channel shuffle ShuffleNet groups stay narrow and still exchange information
Attention transformers every token reaches every other token in one layer

Step 2: Define the search space#

Step 3: Choose a search algorithm#

Strategy How it moves Han's remark
Grid search try every combination easy to implement, slow to evaluate one by one; throw out the designs that break the constraint before training any of them (Lecture 7, 54:00)
Random search sample at random run it first as a sanity check: if the reward does not improve after a few iterations, something is wrong with the search space, the search, the evaluation or the reward (56:00)
Reinforcement learning a controller learns by trial and error to propose high-reward architectures tricky and not easy to use in practice; the controller proposes an architecture with probability P, a child network is trained for a reward R, and the controller is updated with the gradient of P scaled by R (56:00)
Gradient descent relax the choices to weights and optimize them differentiable
Evolutionary search mutate and recombine a population the fitness function selects on latency, accuracy, throughput, memory or energy (62:00)

An evolutionary loop:

  1. Sample an initial population of architectures.
  2. Score each one: its fitness, or reward, is accuracy under the cost constraint.
  3. Keep the best half.
  4. Create children by crossover (take one parent's choice per block) and mutation (change one block, or a stage depth).
  5. Repeat for a fixed number of generations.

Han's version of the definition: "Mutation takes one input, crossover takes two inputs" (Lecture 7, 64:00). His students implement it in the course lab.

Step 4: Estimate performance without paying full price#

Method Idea Price
Train from scratch train each candidate to the end Han cites tens of thousands of models and 22,000 GPU hours, on CIFAR-10, a small image data set (Lecture 8, 2:00)
Inherit weights candidates share weights trained once cheaper; rankings are approximate
Hypernetwork one network generates the weights for any candidate rarely used (8:00)
Zero-shot score an architecture without training it cheapest; a research topic (slides 75 to 77)

Step 5: Make it hardware-aware#

Han's slides 20 to 22 of Lecture 8 carry one headline: MACs are not real hardware efficiency. Architectures with similar FLOPs can have very different latency. Three fixes:

Step 6: Train once for many devices: once-for-all#

Designing a separate model for every phone, laptop and chip does not scale. The once-for-all approach trains one large network that contains many smaller ones:

  1. Define elastic dimensions: depth (which layers), width (which channels), kernel size, input resolution.
  2. During training, sample a sub-network at each step and train only it, so many sub-networks learn together (Lecture 8, 40:00).
  3. For each device, search the sub-network that meets its latency using the latency table. No further training.

He lists the fields his lab applied the idea to, language models, generative models, point clouds and pose estimation (Lecture 8, 2:00), and notes that NVIDIA applied it to language models: a large sub-network for a data-center GPU, a middle one for a desktop, a small one for mobile (74:00).

Worked example#

A complete search in 40 lines. The accuracy model is a stand-in: it rewards capacity with diminishing returns. Everything else is real mechanics.

import random

random.seed(0)
KERNELS = (3, 5, 7)                                 # kernel size choices per block
LATENCY_US = {3: 110, 5: 230, 7: 420}               # measured once on the target device

def latency(arch):                                  # arch = one kernel size per block
    return sum(LATENCY_US[k] for k in arch)

def proxy_accuracy(arch):                           # stand-in for a real training run
    capacity = sum(k * k for k in arch)
    return 0.60 + 0.30 * (1 - 2.718 ** (-capacity / 500))

def fitness(arch, budget_us):                       # reward: accuracy under the budget
    return proxy_accuracy(arch) if latency(arch) <= budget_us else 0.0

def random_search(budget, tries=200):
    return max((tuple(random.choice(KERNELS) for _ in range(4)) for _ in range(tries)),
               key=lambda a: fitness(a, budget))

def evolve(budget, size=8, generations=20):
    pop = [tuple(random.choice(KERNELS) for _ in range(4)) for _ in range(size)]
    for _ in range(generations):
        pop.sort(key=lambda a: fitness(a, budget), reverse=True)
        parents = pop[:size // 2]                   # keep the best half
        kids = []
        while len(kids) < size - len(parents):
            a, b = random.sample(parents, 2)
            child = tuple(random.choice((x, y)) for x, y in zip(a, b))     # crossover
            if random.random() < 0.3:                                     # mutation
                i = random.randrange(4)
                child = child[:i] + (random.choice(KERNELS),) + child[i + 1:]
            kids.append(child)
        pop = parents + kids
    return max(pop, key=lambda a: fitness(a, budget))

for name, search in (("random", random_search), ("evolutionary", evolve)):
    best = search(600)                              # 600 microsecond budget
    print(f"{name:>13}: {best}  latency {latency(best)} us  "
          f"accuracy {proxy_accuracy(best):.3f}")

What to observe:

What the practitioners say#

Pitfalls#

  1. Searching with MACs as the cost. Fix: measure latency on the device and search against that.
  2. Searching on a proxy dataset or device. Fix: search on the target, or verify the final candidates on it.
  3. Trusting short training runs to rank candidates. Fix: retrain the top few to the end before choosing.
  4. A search space larger than the budget can explore. Fix: shrink it to what fits the resource first.
  5. Counting only parameters for tiny devices. Fix: constrain activation memory too.
  6. Tuning the search on your test set. Fix: keep a held-out set; see a minimal eval harness.

Try it#

Extend the example.

  1. Add a width choice per block (for example 16, 32 or 64 channels) and extend the latency table.
  2. Run both searches under budgets of 450 µs, 600 µs and 1,000 µs.
  3. Write down the size of your search space.

You are done when you have the best architecture and its latency for each of the three budgets, the search space size, and one sentence on how the best design changes with the budget.

Stretch: replace the proxy accuracy with real short training runs of your top five candidates on a small image dataset.

Key takeaways#

Self-check#

  1. Name the three parts of a NAS loop.
  2. Why can two architectures with the same MAC count have different latency?
  3. What do crossover and mutation each take as input?
  4. A search space has 4 blocks, each with 5 operator choices and 2 combination rules. How many candidates?
  5. What problem does a once-for-all network solve?
Show answers 1. A search space, a search strategy, and a performance estimate. 2. Latency depends on memory access patterns, kernel efficiency and operator support on the chip, not on the number of multiplies alone. 3. Mutation takes one parent. Crossover takes two. 4. 10,000. Each block has 5 × 2 = 10 choices, and 10⁴ = 10,000. 5. Training and searching a separate model for every hardware platform. One trained network contains sub-networks for many devices.

Sources#

Next#

→ Knowledge Distillation, which changes what a small model learns rather than its architecture.