🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Neural Architecture Search: Automating Model Design

🟢 Free Lesson

Neural Architecture Search: Automating Model Design

Architecture design has historically been a craft: researchers try an idea, train it, inspect the results, and try again. Neural architecture search (NAS) reframes that loop as an optimization problem — define a space of possible networks, a search strategy that explores it, and an evaluation function that scores candidates — then let an algorithm do the searching.

The naive version of this idea is also why NAS has a bad reputation: brute-force search over architectures, training each candidate fully, would cost more than most organizations spend on all their training combined. Nearly all practical NAS research has therefore focused on the evaluation problem — how to score thousands of architectures cheaply enough that search becomes affordable. Weight sharing, where one supernet is trained once and sub-architectures are scored by sampling paths through it, is the breakthrough that made NAS commercially interesting.

This lesson covers the three components of any NAS system, defines a search space concretely, implements differentiable search with DARTS and evolutionary search, explains weight-sharing supernets, and gives an honest cost accounting of when NAS pays off versus when expert priors win.

The three components

Every NAS system decomposes into the same three pieces, and each has failure modes that determine whether the search succeeds.

ComponentQuestion it answersCommon choicesFailure mode
Search spaceWhat architectures are legal?Cell-based, hierarchical, free-form opsSpace excludes the good designs
Search strategyWhich candidates to try next?Random, RL, evolutionary, differentiablePremature convergence, wasted budget
EvaluationHow good is a candidate?Full training, weight sharing, proxy tasksRanking correlation breaks

The search space is the most consequential decision and the least discussed. A space built from operations known to work (convolutions of several widths, pooling, skip connections, attention) constrains search to a neighborhood of sensible designs; a space that includes only weak operations caps performance regardless of how clever the strategy is. Conversely, an enormous space with no structure turns search into needle-hunting.

Evaluation is where the budget goes. Training each candidate to convergence on ImageNet would make search cost thousands of GPU-days. Proxy evaluations — shorter training runs, smaller datasets, or shared weights — cut this dramatically, but each proxy introduces a risk: the ranking of architectures on the proxy may not match the ranking on the real task. A NAS system's practical value comes mostly from keeping that ranking correlation high while driving evaluation cost down.

Defining a search space

A search space is a declarative description of legal architectures. In code it is an object that can sample random architectures and enumerate operation choices:

python
import random
from dataclasses import dataclass, field
from typing import Dict, List

@dataclass
class Operation:
    name: str
    choices: Dict[str, List]
    flops_weight: float

class CellSearchSpace:
    def __init__(self, max_nodes: int = 4, reduction_choices: bool = True):
        self.operations = {
            "conv3x3": Operation("conv3x3", {"channels": [24, 36, 48]}, 0.10),
            "conv5x5": Operation("conv5x5", {"channels": [24, 36, 48]}, 0.22),
            "depthwise3x3": Operation("depthwise3x3", {"channels": [24, 48]}, 0.04),
            "avg_pool": Operation("avg_pool", {"stride": [1, 2]}, 0.01),
            "max_pool": Operation("max_pool", {"stride": [1, 2]}, 0.01),
            "skip": Operation("skip", {}, 0.00),
            "none": Operation("none", {}, 0.00),
        }
        self.connections = ["concat", "add"]
        self.max_nodes = max_nodes

    def random_cell(self) -> Dict:
        cell = {"nodes": []}
        for node in range(2, self.max_nodes + 1):
            inputs = random.sample(range(node), k=2)
            edges = []
            for src in inputs:
                op_name = random.choice(list(self.operations))
                edges.append({"from": src, "op": op_name,
                              "params": {k: random.choice(v)
                                         for k, v in self.operations[op_name].choices.items()}})
            cell["nodes"].append({"inputs": inputs, "edges": edges,
                                  "combine": random.choice(self.connections)})
        return cell

space = CellSearchSpace(max_nodes=4)
candidate = space.random_cell()

The cell-based pattern above — search over a small repeated module, then stack the winning cell many times — comes from the seminal ENAS/DARTS line of work and remains the dominant design. It shrinks the combinatorial problem from searching a whole network to searching a graph of four intermediate nodes, each with a handful of operation choices. The stacking assumption (good cells compose) is not guaranteed, but it holds often enough to make the decomposition practical.

Differentiable search with DARTS

DARTS's insight was to make architecture selection differentiable. Instead of discrete candidates, each edge holds a weighted mixture of all candidate operations, and the mixing weights become learnable parameters trained jointly with the network weights — by gradient descent, not by outer-loop search.

python
import torch
import torch.nn as nn
import torch.nn.functional as F

class MixedOperation(nn.Module):
    def __init__(self, in_ch: int, out_ch: int):
        super().__init__()
        self.ops = nn.ModuleDict({
            "conv3x3": nn.Conv2d(in_ch, out_ch, 3, padding=1),
            "conv5x5": nn.Conv2d(in_ch, out_ch, 5, padding=2),
            "avg_pool": nn.AvgPool2d(3, stride=1, padding=1),
            "max_pool": nn.MaxPool2d(3, stride=1, padding=1),
            "skip": nn.Identity() if in_ch == out_ch else nn.Conv2d(in_ch, out_ch, 1),
        })
        self.arch_params = nn.Parameter(torch.randn(len(self.ops)))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        weights = F.softmax(self.arch_params, dim=0)
        return sum(w * op(x) for w, op in zip(weights, self.ops.values()))

class DARTSCell(nn.Module):
    def __init__(self, in_ch: int, out_ch: int, n_nodes: int = 4):
        super().__init__()
        self.n_nodes = n_nodes
        self.edges = nn.ModuleList()
        for node in range(n_nodes):
            for _ in range(node + 1):
                self.edges.append(MixedOperation(in_ch, out_ch))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        states = [x]
        idx = 0
        for node in range(self.n_nodes):
            agg = sum(self.edges[idx + j](states[j]) for j in range(node + 1))
            idx += node + 1
            states.append(agg)
        return torch.cat(states[1:], dim=1)

Training alternates: update network weights on training data, update architecture parameters on a validation split. The final architecture is read off by taking the argmax operation on each edge.

DARTS is elegant but has well-documented pathologies. Its continuous relaxation biases selection toward skip connections — they are cheap and train easily, so gradients favor them, and searches routinely collapse to all-skip cells with poor performance. Schedulers that prune weak operations early, or restrict the candidate set per edge, are standard countermeasures. Ranking candidates by their weights at the end also correlates imperfectly with actually training the discretized architecture — a reminder that the proxy-evaluation problem never fully disappears.

Evolutionary search

Evolutionary NAS treats architectures as genomes: sample a population, evaluate, select the fittest, crossover and mutate, repeat. It is conceptually straightforward, embarrassingly parallel (every candidate evaluates independently), and surprisingly competitive with more exotic strategies.

python
import random
from typing import Callable, List, Tuple

class EvolutionarySearch:
    def __init__(self, space: CellSearchSpace, pop_size: int = 20,
                 mutation_rate: float = 0.2):
        self.space = space
        self.pop_size = pop_size
        self.mutation_rate = mutation_rate

    def mutate(self, cell: Dict) -> Dict:
        mutated = {"nodes": []}
        for node in cell["nodes"]:
            new_edges = []
            for edge in node["edges"]:
                if random.random() < self.mutation_rate:
                    edge = dict(edge)
                    edge["op"] = random.choice(list(self.space.operations))
                new_edges.append(edge)
            mutated["nodes"].append({**node, "edges": new_edges})
        return mutated

    def crossover(self, a: Dict, b: Dict) -> Dict:
        child = {"nodes": []}
        for i, node in enumerate(a["nodes"]):
            source = node if i < len(a["nodes"]) // 2 else b["nodes"][i]
            child["nodes"].append(source)
        return child

    def search(self, evaluate: Callable[[Dict], float],
               generations: int = 20) -> Tuple[Dict, float]:
        pop = [self.space.random_cell() for _ in range(self.pop_size)]
        scores = [evaluate(c) for c in pop]
        best, best_score = pop[0], scores[0]

        for _ in range(generations):
            ranked = sorted(zip(scores, pop), reverse=True, key=lambda x: x[0])
            elites = [cell for _, cell in ranked[:4]]
            offspring = []
            while len(offspring) < self.pop_size - len(elites):
                p1, p2 = random.sample(elites, 2)
                child = self.mutate(self.crossover(p1, p2))
                offspring.append(child)
            pop = elites + offspring
            scores = [evaluate(c) for c in pop]
            gen_best = max(scores)
            if gen_best > best_score:
                best_score = gen_best
                best = pop[scores.index(gen_best)]
        return best, best_score

search = EvolutionarySearch(space)
best_cell, score = search.search(evaluate=quick_eval, generations=20)

The mutation rate is the dial that controls exploration: too low and the population converges to one lineage within a few generations; too high and crossover loses its value because children barely resemble their parents. Elitism (carrying top candidates forward untouched) prevents losing a good discovery to a bad mutation batch. AmoebaNet and regularized evolution — which drops the worst candidate each iteration rather than selecting the best parents — showed that simple tournament-style evolution matches or beats RL-based search, an early lesson that search-strategy sophistication matters less than evaluation cost.

Weight sharing and supernet training

The evaluation bottleneck is what made NAS expensive: score a thousand candidates and you have trained a thousand models. Weight sharing solves it with one-shot training. Build a supernet containing every operation on every edge, train it once with path sampling (each forward pass selects one path through the graph), then evaluate any candidate architecture by loading it into the trained supernet and scoring it on a validation set — no retraining.

python
class OneShotNAS:
    def __init__(self, space: CellSearchSpace, d_model: int = 48):
        self.space = space
        self.shared = nn.ModuleDict()
        for name, op in space.operations.items():
            if name in ("skip", "none"):
                continue
            self.shared[name] = nn.Linear(d_model, d_model)

    def sample_path(self) -> List[str]:
        return [random.choice(list(self.space.operations))
                for _ in range(self.space.max_nodes * 2)]

    def forward_path(self, x: torch.Tensor, path: List[str]) -> torch.Tensor:
        h = x
        for op_name in path:
            if op_name in ("skip", "none"):
                continue
            h = F.relu(self.shared[op_name](h))
        return h

    def score_architecture(self, path: List[str],
                           val_loader, criterion) -> float:
        self.eval()
        total, count = 0.0, 0
        with torch.no_grad():
            for x, y in val_loader:
                logits = self.forward_path(x, path)
                total += criterion(logits, y).item()
                count += 1
        return total / count

Weight sharing cuts evaluation cost by orders of magnitude — the result that made NAS commercially viable — but introduces its own ranking problem. Sub-architectures share weights, so a candidate may score well only because the weights it inherited suit it; rankings from a supernet correlate with, but do not perfectly predict, rankings after full independent training. Techniques like sandwich rules (always train the largest and smallest path plus random ones), fair sampling of paths, and post-hoc fine-tuning of the chosen architecture close much of that gap.

When NAS is worth the cost

NAS pays off in constrained, high-volume settings: searching for a mobile-class architecture once and deploying it millions of times, where a few points of efficiency at equal accuracy compound enormously. It pays off when the target hardware has unusual constraints (specific accelerator, memory ceiling, latency budget) that expert priors do not capture, because hardware-aware search can put measured latency directly into the fitness function.

NAS usually loses to expert design when the domain is well-trodden — standard CNN and transformer backbones are the distilled result of thousands of human search iterations, and beating them on a novel task with a modest search budget is hard. It also loses when your budget cannot afford even proxy evaluation across a meaningful fraction of the space; a small search in a narrow space is often worse than starting from a strong pretrained prior and tuning it.

The honest framing: NAS automates a design loop that human researchers already run. It is worth automating when your evaluation function is cheap and your deployment volume is large; otherwise, transfer learning from good existing architectures is the higher-return investment.

Common Mistakes

Building a search space that excludes known-good operations

Fix: Seed the space with operations from strong hand-designed cells — search should refine priors, not rediscover them from nothing.

Letting DARTS collapse to all-skip cells

Fix: Prune weak operations early in the schedule and monitor the operation distribution as a health metric.

Trusting supernet rankings without validation

Fix: Spot-check top candidates with independent short trainings; ranking correlation with full training is the metric that matters.

Evaluating candidates on a proxy unrelated to the real task

Fix: Use the closest affordable proxy (similar data, similar augmentation) and re-verify finalists on the actual target.

Running search before deciding deployment constraints

Fix: Put latency, memory, and FLOPs into the fitness function from the start — post-hoc filtering wastes the whole search.

Key Takeaways

  • NAS is three coupled problems: define a space, choose a search strategy, and evaluate candidates cheaply.
  • The evaluation budget — not the search algorithm — is what makes or breaks a NAS project.
  • DARTS makes architecture selection differentiable but biases toward skip connections without pruning schedules.
  • Evolutionary search is simple, parallel, and competitive; mutation rate and elitism are its key controls.
  • Weight-sharing supernets cut evaluation cost by orders of magnitude at the price of imperfect ranking fidelity.
  • NAS wins in constrained, high-volume deployments; otherwise strong pretrained priors usually return more per GPU-hour.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement