AI Logic

Neural Architecture Search (NAS)

DARTS (Differentiable Architecture Search)

Updated:

How DARTS works. Left: the search flow of continuous relaxation, bilevel optimization that alternately updates the weights w and the architecture parameters α, discretization, and training from scratch. Right: the mixed operation, which sums the outputs of all candidate operations on one edge weighted by softmax(α)

Background and Overview

DARTS (Differentiable ARchiTecture Search) is a neural architecture search (NAS) method that replaces the discrete choice of which layer (operation) to use with a weighted sum over all candidates, making it continuous, and then searches the network architecture itself with gradient descent. Liu, Simonyan, and Yang presented it at ICLR in 2019.

NAS is the technique of automatically searching for a network architecture (where to place convolutions, which layers to connect). Earlier representative methods generated candidate architectures with reinforcement learning or evolutionary search and trained and evaluated them one by one. Because every candidate needs training, these methods used enormous amounts of compute: for example, NASNet took 2000 GPU-days and AmoebaNet 3150 GPU-days.

DARTS solves the search not as "choosing among discrete candidates" but as "optimizing continuous parameters". In cooking terms, instead of making and tasting a separate dish for each of salt, soy sauce, and miso, it makes one pot with a little of everything, gradually adjusts the proportions while tasting, and at the end keeps only the seasoning with the largest share.

As a result, on CIFAR-10 image classification it finds architectures with accuracy close to those from reinforcement learning or evolutionary search, with about one day of search on a single GPU per run (4 GPU-days for four runs with different random seeds).

Theory

DARTS searches for the structure of a small building block called a cell and stacks cells to build a large network (the same idea as NASNet and others). A cell is a graph of nodes and edges (a directed acyclic graph).

  • A node x(i)x^{(i)} is an intermediate representation, such as a feature map.
  • An edge (i,j)(i, j) carries some operation o(i,j)o^{(i,j)} (convolution, pooling, and so on).
  • Each node is the sum of the values received from all preceding nodes: x(j)=∑i<jo(i,j)(x(i))x^{(j)} = \sum_{i<j} o^{(i,j)}(x^{(i)}).

The goal of the search is to decide which operation to place on each edge. DARTS searches with the following steps (left of the figure above).

  1. Continuous relaxation: place a "mixed operation" on each edge that overlays all candidate operations with weights.
  2. Bilevel optimization: update the network weights ww and the architecture parameters α\alpha alternately by gradient descent.
  3. Discretization: on each edge, keep only the operation with the largest weight.
  4. Evaluation: train a large network built by stacking the chosen cells again from scratch.

The mixed operation is (Eq. (2) in the paper):

oˉ(i,j)(x)=∑o∈Oexp⁡(αo(i,j))∑o′∈Oexp⁡(αo′(i,j)) o(x)\bar{o}^{(i,j)}(x) = \sum_{o \in \mathcal{O}} \frac{\exp\bigl(\alpha_o^{(i,j)}\bigr)}{\sum_{o' \in \mathcal{O}} \exp\bigl(\alpha_{o'}^{(i,j)}\bigr)} \, o(x)

O\mathcal{O} is the set of candidate operations, and α(i,j)\alpha^{(i,j)} is a vector attached to edge (i,j)(i, j) whose length equals the number of candidate operations. Passing α\alpha through a softmax gives each operation's weight. Because the candidates include "zero" (no connection), leaving an edge unconnected is also an option.

For example, if the α\alpha of an edge is (1.0,0.6,0.1,0.35,−0.8)(1.0, 0.6, 0.1, 0.35, -0.8), the weights of the five operations are about (0.36,0.24,0.15,0.19,0.06)(0.36, 0.24, 0.15, 0.19, 0.06). After the search, only the operation with the largest weight (the first one in this example) is kept.

Determining ww and α\alpha is the following bilevel optimization problem (Eqs. (3) and (4) in the paper):

min⁡α  Lval(w∗(α),α)s.t.w∗(α)=arg⁡min⁡w  Ltrain(w,α)\min_{\alpha} \; \mathcal{L}_{\text{val}}\bigl(w^*(\alpha), \alpha\bigr) \quad \text{s.t.} \quad w^*(\alpha) = \arg\min_{w} \; \mathcal{L}_{\text{train}}(w, \alpha)

Here Ltrain\mathcal{L}_{\text{train}} is the loss on the training data and Lval\mathcal{L}_{\text{val}} is the loss on the validation data. The problem means "choose the architecture whose validation loss is smallest once its weights are fully trained". The paper notes that α\alpha can be viewed as a kind of hyperparameter, but its dimension is much larger than that of a scalar hyperparameter such as the learning rate, which makes it harder to optimize.

α\alpha is updated with the validation loss because updating it with the training loss would favor operations that fit the training data easily (those with many parameters), leading to architectures that tend to overfit. The DARTS search sets aside half of the CIFAR-10 training data as validation data.

Gradient Approximation and Search Settings

Solving the bilevel optimization exactly would require retraining ww to convergence every time α\alpha changes slightly, which is impractical. DARTS therefore approximates w∗(α)w^*(\alpha) with "the value after a single gradient step from the current ww" (Eq. (6) in the paper).

∇αLval(w∗(α),α)≈∇αLval(w−ξ∇wLtrain(w,α),α)\nabla_{\alpha} \mathcal{L}_{\text{val}}\bigl(w^*(\alpha), \alpha\bigr) \approx \nabla_{\alpha} \mathcal{L}_{\text{val}}\bigl(w - \xi \nabla_{w} \mathcal{L}_{\text{train}}(w, \alpha), \alpha\bigr)

ξ\xi is the learning rate of this single step. The search alternates between the following two steps (Algorithm 1 in the paper).

  1. Update α\alpha with the gradient in the equation above.
  2. Update ww with ∇wLtrain(w,α)\nabla_w \mathcal{L}_{\text{train}}(w, \alpha).

The approximate gradient contains a second-order term (a Hessian-vector product), but the paper computes it with a finite-difference approximation that costs only two extra forward and backward passes. Setting ξ=0\xi = 0 removes the second-order term and gives the first-order approximation, which uses the current ww as is. The first-order approximation is faster, but in the paper's experiments it was less accurate. This idea of "evaluating after a single update step" is also used in meta-learning methods such as MAML.

The main search settings on CIFAR-10 are as follows.

ItemValue
Candidate operations3×3 and 5×5 separable convolutions, 3×3 and 5×5 dilated separable convolutions, 3×3 max pooling and average pooling, identity, zero (8 types)
Cell7 nodes (2 input, 4 intermediate, 1 output). Two kinds of cells are searched: a normal cell and a reduction cell that halves the height and width
Network used for the search8 cells, 16 channels, 50 epochs, batch size 64
Optimizing wwSGD with momentum (learning rate from 0.025 down to 0 with a cosine schedule)
Optimizing α\alphaAdam (learning rate 3×10−43 \times 10^{-4}). α\alpha is initialized to 0 (all operations start with equal weights)

In discretization, for each intermediate node of a convolutional cell, only the 2 strongest non-zero operations, on edges coming from different nodes, are kept.

Results and Comparison with Other Methods

The main results of the paper are as follows. As in the paper's tables, the search cost excludes the cost of selecting the architecture and of the final training.

TaskDARTS resultComparison
CIFAR-10 (image classification)Test error 2.76 ± 0.09% (3.3M parameters, 4 GPU-days of search)AmoebaNet-B 2.55 ± 0.05% (3150 GPU-days), ENAS 2.89% (0.5 GPU-days)
ImageNet (mobile setting, reusing the cell found on CIFAR-10)Top-1 error 26.7%NASNet-A 26.0% (2000 GPU-days)
Penn Treebank (language modeling)Test perplexity 55.7 (1 GPU-day of search)ENAS 58.6–63.1, hand-tuned LSTM 58.3–58.8

DARTS outperformed random selection of architectures in the same search space (3.29 ± 0.15% on CIFAR-10), and the second-order approximation gave better results than the first-order one (3.00 ± 0.14%).

DARTS search results vary with the random seed. Even in the paper, the search was run four times, each result was briefly retrained, and the cell that did best on validation data was chosen. Later work (Zela et al., 2020) also showed that, depending on the search space, DARTS can select architectures that perform very poorly. The accuracy of the mixed-operation network during search does not necessarily match the accuracy of the network after discretization.

Compared with other NAS methods, DARTS has the following characteristics.

MethodHow it searchesSearch cost (CIFAR-10)
NASNetGenerates architectures with reinforcement learning and trains and evaluates each one2000 GPU-days
AmoebaNetEvolutionary search3150 GPU-days
ENASReinforcement learning, with weights shared among candidate architectures0.5 GPU-days
DARTSContinuous relaxation and gradient descent1.5 (first-order) to 4 (second-order) GPU-days

Because DARTS computes all candidate operations at once during search, it uses a lot of memory. The search is therefore run on a small network (8 cells), and the cells found are stacked into a large network (20 cells). To address this mismatch in network size between search and final use, ProxylessNAS proposed searching directly on the target data and at the target size.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader, random_split
from tqdm import tqdm

'''
Image classification on MNIST
Search for the operation on each edge of a small cell with DARTS (first-order approximation)
'''

# Hyperparameters
batch_size = 64       # batch size
epochs = 3            # number of search epochs
lr_w = 0.025          # learning rate for the weights w
lr_alpha = 3e-4       # learning rate for the architecture parameters α
channels = 16         # number of channels

# 'cuda' if CUDA is available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'

# Datasets and loaders (half of the training data becomes validation data for updating α)
transform = transforms.Compose([
  transforms.ToTensor(),
  transforms.Normalize((0.1307,), (0.3081,))
])
full_train = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
train_set, val_set = random_split(full_train, [30000, 30000])
train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=True)
val_loader = DataLoader(val_set, batch_size=batch_size, shuffle=True)

# Candidate operations
OPS = {
  'sep_conv_3x3': lambda C: nn.Sequential(
    nn.ReLU(), nn.Conv2d(C, C, 3, padding=1, groups=C, bias=False), nn.Conv2d(C, C, 1, bias=False),
    nn.BatchNorm2d(C, affine=False)),
  'dil_conv_3x3': lambda C: nn.Sequential(
    nn.ReLU(), nn.Conv2d(C, C, 3, padding=2, dilation=2, groups=C, bias=False), nn.Conv2d(C, C, 1, bias=False),
    nn.BatchNorm2d(C, affine=False)),
  'max_pool_3x3': lambda C: nn.MaxPool2d(3, stride=1, padding=1),
  'skip_connect': lambda C: nn.Identity(),
}
OP_NAMES = list(OPS) + ['zero']


# Mixed operation: sum the outputs of all candidates weighted by softmax(α)
class MixedOp(nn.Module):
  def __init__(self, C):
    super().__init__()
    self.ops = nn.ModuleList([OPS[name](C) for name in OPS])

  def forward(self, x, weights):
    # The last weight is for the "zero" operation (its output is 0, so it is not added)
    return sum(w * op(x) for w, op in zip(weights[:-1], self.ops))


# Cell: 1 input node and 3 intermediate nodes. Each intermediate node is the sum of mixed operations from all preceding nodes
class Cell(nn.Module):
  def __init__(self, C, steps=3):
    super().__init__()
    self.steps = steps
    self.edges = nn.ModuleList([MixedOp(C) for i in range(steps) for _ in range(i + 1)])

  def forward(self, x, alphas):
    weights = F.softmax(alphas, dim=-1)
    states = [x]
    k = 0
    for i in range(self.steps):
      s = sum(self.edges[k + j](h, weights[k + j]) for j, h in enumerate(states))
      k += len(states)
      states.append(s)
    return torch.cat(states[1:], dim=1)  # concatenate the intermediate nodes along the channel axis


class SearchNetwork(nn.Module):
  def __init__(self, C=16, steps=3):
    super().__init__()
    self.stem = nn.Sequential(nn.Conv2d(1, C, 3, padding=1, bias=False), nn.BatchNorm2d(C))
    self.cell = Cell(C, steps)
    self.head = nn.Sequential(nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(C * steps, 10))
    num_edges = steps * (steps + 1) // 2
    # Architecture parameters α (initialized to 0 -> all operations start with equal weights)
    self.alphas = nn.Parameter(torch.zeros(num_edges, len(OP_NAMES)))

  def forward(self, x):
    return self.head(self.cell(self.stem(x), self.alphas))

  def weight_params(self):
    return [p for n, p in self.named_parameters() if n != 'alphas']


model = SearchNetwork(channels).to(device)
criterion = nn.CrossEntropyLoss()
opt_w = optim.SGD(model.weight_params(), lr=lr_w, momentum=0.9, weight_decay=3e-4)
opt_alpha = optim.Adam([model.alphas], lr=lr_alpha, betas=(0.5, 0.999), weight_decay=1e-3)

# Search: alternately update α (validation loss) and w (training loss) (first-order approximation)
for epoch in tqdm(range(epochs)):
  model.train()
  for (x_tr, y_tr), (x_val, y_val) in zip(train_loader, val_loader):
    x_tr, y_tr = x_tr.to(device), y_tr.to(device)
    x_val, y_val = x_val.to(device), y_val.to(device)

    # 1. Update α with the validation loss
    opt_alpha.zero_grad()
    criterion(model(x_val), y_val).backward()
    opt_alpha.step()

    # 2. Update w with the training loss
    opt_w.zero_grad()
    criterion(model(x_tr), y_tr).backward()
    opt_w.step()

# Discretization: on each edge, pick the non-zero operation with the largest weight
weights = F.softmax(model.alphas, dim=-1).detach().cpu()
for e, w in enumerate(weights):
  best = w[:-1].argmax().item()
  print(f"edge {e}: {OP_NAMES[best]} ({w[best]:.2f})")

FAQ

Q. Why are the architecture parameters α updated on validation data?
A.

Because the goal of DARTS is to find an architecture that works well on new data after training. Updating α with the training loss would favor operations that fit the training data easily, leading to architectures that tend to overfit. So the weights w are updated on training data and α on validation data.

Q. Should the first-order or the second-order approximation be used?
A.

The first-order approximation (ξ = 0) computes the gradient of α using the current weights as is, so it is faster and uses less memory. The second-order approximation evaluates after one update of the weights, which adds computation, but on CIFAR-10 in the paper it lowered the error rate from 3.00% to 2.76%. As a rule of thumb, use the second-order approximation if compute allows, and the first-order one for a first try.

Q. Can the weights learned during the search be used directly?
A.

No. DARTS selects only the cell structure, and the weights from the search are discarded. A large network built by stacking the chosen cells is trained again from scratch and evaluated. This is because the network during search (a weighted sum of all candidates) and the network after discretization are different networks.

References

  1. Liu, H., Simonyan, K., & Yang, Y. (2019). DARTS: Differentiable Architecture Search. International Conference on Learning Representations (ICLR 2019). arXiv:1806.09055.
  2. Zela, A., Elsken, T., Saikia, T., Marrakchi, Y., Brox, T., & Hutter, F. (2020). Understanding and Robustifying Differentiable Architecture Search. International Conference on Learning Representations (ICLR 2020). arXiv:1909.09656.