AI Logic

Neural Architecture Search (NAS)

NASNet

Updated:

NASNet's architecture and search space. Left: the overall architecture for CIFAR-10 (after a 3×3 convolution, N normal cells and a reduction cell are stacked alternately). Right: the controller's LSTM chooses one block of a cell in five steps (two hidden states, an operation for each, and a combination method), with an example of the block produced by the chosen values

Background and Overview

NASNet refers both to a neural architecture search method that, instead of searching the whole network, uses reinforcement learning on a small dataset (CIFAR-10) to search for the architecture of a small stackable building block (a cell) and then transfers it to a large dataset (ImageNet), and to the networks found this way. It was presented by Zoph, Vasudevan, Shlens, and Le at CVPR in 2018.

The method it builds on, NAS with reinforcement learning, searches the architecture of the whole network, so the search is extremely expensive, and searching directly on large data such as ImageNet was not practical. NASNet solves this problem by changing the design of the search space. Noting that good human-designed networks such as GoogLeNet (Inception) and ResNet repeat building blocks of the same form many times, it narrows the search target to "the architecture of a single cell."

As an analogy, instead of designing entire houses and building each one to compare them, the shape of one good brick is searched for using a small model, and the found brick is then used for both a shed and a large house by changing how many are laid.

Because the cell architecture does not depend on the network's depth or the image size, cells found on CIFAR-10 can be used on ImageNet simply by stacking more of them with more filters. As a result, it achieved a then state-of-the-art top-1 accuracy of 82.7% on ImageNet with less computation than human-designed models of similar accuracy. The search itself also became about 7x more efficient than the original method.

Theory: The Cell Search Space

A NASNet network is built by stacking two kinds of cells (left side of the figure above).

  • Normal cell: Returns a feature map of the same height and width as its input.
  • Reduction cell: Uses stride 2 for its initial operations to halve the height and width. Each time the height and width are halved, the number of filters is doubled.

The overall arrangement (NN normal cells at a time, with reduction cells in between) is fixed by hand, and only the contents of the normal cell and the reduction cell are searched. On ImageNet, where inputs are as large as 299×299, more reduction cells are used.

Each cell takes the outputs hih_i and hi−1h_{i-1} of the previous two cells as inputs. A cell consists of BB blocks, and the controller (an RNN) decides each block in the following five steps (right side of the figure above; Figure 3 in the paper).

  1. Select a hidden state: Choose from hih_i, hi−1h_{i-1}, and the hidden states created by earlier blocks.
  2. Select a second hidden state: Choose from the same candidates as in step 1.
  3. Select an operation to apply to the hidden state from step 1: Choose from the 13 operations below.
  4. Select an operation to apply to the hidden state from step 2: Choose from the same candidates as in step 3.
  5. Select a combination method: Choose whether to add the outputs of steps 3 and 4 element-wise or concatenate them along the channel dimension.

The resulting hidden state is added to the candidates available to subsequent blocks. This is repeated BB times, and finally the hidden states not used as input by any block are concatenated along the channel dimension to form the cell output. The paper uses B=5B = 5.

The candidate operations are the following 13 commonly used in CNNs.

TypeOperations
Convolutions1×1, 3×3, 1×3 then 3×1, 1×7 then 7×1, 3×3 dilated convolution
Depthwise separable convolutions3×3, 5×5, 7×7
Pooling3×3 average pooling, 3×3, 5×5, and 7×7 max pooling
OtherIdentity

The controller makes 2×5B2 \times 5B choices in total for the normal and reduction cells, each with a softmax. The probability of outputting one architecture AA is the product of the probabilities of all choices.

P(A)=∏t=110BP(at∣a1:t−1)P(A) = \prod_{t=1}^{10B} P(a_t \mid a_{1:t-1})

The controller is updated using the gradient of this probability weighted by the validation accuracy of a child network trained with architecture AA. The idea is the same as NAS with reinforcement learning, but NASNet uses PPO (Proximal Policy Optimization) instead of REINFORCE as the update rule because it trains faster and more stably.

There are two reasons why searching for cells is faster and transfers better. First, the search space becomes smaller (only 5B=255B = 25 values per cell need to be decided, regardless of network depth). Second, during the search, candidates can be evaluated quickly with a small network (cells repeated N=2N = 2 times), while for the final model a large network can be built simply by increasing the number of cells and filters.

Search Settings and ScheduledDropPath

The main settings for the search on CIFAR-10 are as follows (Chapter 4 and Appendix A of the paper).

ItemValue
Data used for search5,000 of the CIFAR-10 training images are held out as validation data for measuring the reward
Controller1-layer LSTM (100 units). PPO (learning rate 0.00035), entropy penalty (weight 0.00001)
BaselineExponential moving average of rewards (weight 0.95)
Child networksSmall networks with cells repeated N=2N = 2 times, trained for 20 epochs (learning rate decayed with a cosine schedule)
Architectures evaluated20,000 (the controller is updated in batches of 20)
Compute4 days on 500 GPUs, with 450 child networks trained simultaneously
Final selectionThe top 250 architectures are trained to completion, and the best one is selected

The networks built from the top three cells found this way are called NASNet-A, NASNet-B, and NASNet-C. The cell of NASNet-A, the best of them, makes heavy use of separable convolutions.

The NASNet paper also proposes a regularization method called ScheduledDropPath. It improves on DropPath (a method in the same family as Stochastic Depth), which randomly drops each path in a cell (the output of one operation) during training, by increasing the drop probability linearly from the start to the end of training. According to the paper, DropPath with a constant probability was not very effective for NASNet, while ScheduledDropPath, which gradually increases the probability, substantially improved final performance on both CIFAR-10 and ImageNet.

The idea is to keep the drop probability small at the beginning of training so the network can first make progress, and to increase it later in training to prevent over-reliance on particular paths. At test time no paths are dropped, and output magnitudes are matched to the keep probability used during training.

Experimental Results

The results for CIFAR-10 image classification are as follows (Table 1 in the paper; NASNet results are averages over 5 runs). 6 @ 768 denotes "cells repeated N=6N = 6 times, with 768 filters in the penultimate layer."

ModelParametersTest error
DenseNet-BC (human-designed)25.6M3.46%
Shake-Shake 26 2x96d + Cutout (human-designed)26.2M2.56%
NAS with reinforcement learning v337.4M3.65%
NASNet-A (6 @ 768)3.3M3.41%
NASNet-A (6 @ 768) + Cutout3.3M2.65%
NASNet-A (7 @ 2304) + Cutout27.6M2.40%

The results are better than NAS with reinforcement learning, with far fewer parameters. The best result of 2.40% surpassed the then state of the art (2.56%).

The results of transferring the cells found on CIFAR-10 to ImageNet, with weights trained from scratch, are as follows (Tables 2 and 3 in the paper).

ModelParametersMultiply-addstop-1 accuracy
Inception V3 (human-designed)23.8M5.72B78.8%
NASNet-A (7 @ 1920)22.6M4.93B80.8%
SENet (human-designed)145.8M42.3B82.7%
NASNet-A (6 @ 4032)88.9M23.8B82.7%
MobileNet-224 (human-designed, mobile)4.2M569M70.6%
ShuffleNet (2x, human-designed, mobile)about 5M524M70.9%
NASNet-A (4 @ 1056, mobile)5.3M564M74.0%

At comparable compute, NASNet-A achieved higher accuracy than human-designed models, from large models down to small mobile models.

Furthermore, using the ImageNet-trained NASNet-A as the feature extractor for Faster R-CNN gave a test-dev mAP of 43.1% (input 1200×1200) on COCO object detection, surpassing the best result at the time.

The paper also compares against random search in the same search space. The best architecture found by reinforcement learning is more than 1% better on CIFAR-10 than the best found by random search, but the gap is smaller than in the NAS with reinforcement learning paper, showing that random search can also find fairly good architectures when the search space is well designed.

Practical Considerations

Although cheaper than the original method, the search still takes 4 days on 500 GPUs. Rather than running the NASNet search yourself, it is more practical to use the NASNet-A cell found in the paper or a pre-trained model (such as nasnetalarge in timm). To perform the search itself locally, lighter methods such as ENAS, which shares weights, or DARTS, which searches with gradients, are better suited.

  • The overall arrangement is decided by hand. Only the contents of the cell are searched; how many cells to stack (NN) and the initial number of filters are set manually according to the task and available compute.
  • Fewer multiply-adds do not necessarily mean faster execution. NASNet cells have many branches and many separable convolutions, so actual processing time on GPUs or smartphones can be longer than the number of multiply-adds suggests. MnasNet, which includes processing time in the reward during search, addresses this problem.
  • Training tricks also contribute to the results. ImageNet training uses RMSProp, label smoothing (0.1), an auxiliary classifier (loss weight 0.4), ScheduledDropPath, and more. To reach the same accuracy using only the NASNet-A cell, these settings must be matched as well.
  • No residual connections are added between cells. According to the paper, since cells learn their own skip connections, manually adding residual connections between cells did not improve performance.

Comparison with Other Methods

NASNet's search space (searching for cells) became the standard in much subsequent NAS research. The CIFAR-10 error rates in the table below are the values reported in each paper, and conditions such as the use of Cutout are not the same.

MethodWhat is searchedSearch methodCIFAR-10 errorSearch compute
NAS with reinforcement learningWhole networkRNN + REINFORCE3.65%800 GPUs × about 28 days
NASNet (this article)CellsRNN + PPO2.65% (with Cutout, 3.3M)500 GPUs × 4 days
AmoebaNetCells (same search space as NASNet)Evolutionary search3.34% (without Cutout, 3.2M)450 GPUs × about 7 days
ENASCells (search space close to NASNet's)RNN + REINFORCE, shared weights2.89% (with Cutout, 4.6M)1 GPU × about 0.45 days
DARTSCellsContinuous relaxation + gradient descent2.76% (with Cutout, 3.3M)1 GPU × 4 days (4 runs)

Guidelines for choosing:

  • To use the found architecture as a building block, change the number of stacked NASNet-A cells and the number of filters to match the compute budget.
  • To compare search methods themselves, putting NASNet side by side with AmoebaNet (evolution), which uses the same search space, isolates the difference in search method. In the AmoebaNet paper, evolution found good architectures earlier in the same search space.
  • To reduce search compute, choose ENAS, which shares weights, or DARTS, which searches with gradients, both of which inherit NASNet's idea of searching for cells.

PyTorch example

Show code
python
import torch
import torch.nn as nn

"""
An example of assembling a NASNet-search-space cell from an architecture (genotype).
One block = (input 1, input 2, op 1, op 2, combination). Cell inputs are 0 = h_{i-1}, 1 = h_i;
indices 2 and above are hidden states created by earlier blocks. Unused hidden states are concatenated to form the cell output.
(The GENOTYPE below is an illustrative example, not the paper's actual NASNet-A)
A pre-trained NASNet-A is available in timm: timm.create_model('nasnetalarge', pretrained=True)
"""


class SepConv(nn.Module):
  """Separable convolution. Following Appendix A.4 of the paper, apply ReLU -> conv -> BN twice"""
  def __init__(self, C, k):
    super().__init__()
    layers = []
    for _ in range(2):
      layers += [nn.ReLU(), nn.Conv2d(C, C, k, padding=k // 2, groups=C, bias=False),
                 nn.Conv2d(C, C, 1, bias=False), nn.BatchNorm2d(C)]
    self.op = nn.Sequential(*layers)

  def forward(self, x):
    return self.op(x)


OPS = {
  'identity': lambda C: nn.Identity(),
  'sep_3x3': lambda C: SepConv(C, 3),
  'sep_5x5': lambda C: SepConv(C, 5),
  'sep_7x7': lambda C: SepConv(C, 7),
  'avg_3x3': lambda C: nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False),
  'max_3x3': lambda C: nn.MaxPool2d(3, stride=1, padding=1),
}

# (input 1, input 2, op 1, op 2, combination) x B = 5 blocks (illustrative example)
GENOTYPE = [
  (0, 1, 'sep_3x3', 'avg_3x3', 'add'),
  (1, 1, 'sep_5x5', 'identity', 'add'),
  (0, 2, 'max_3x3', 'sep_3x3', 'add'),
  (3, 1, 'avg_3x3', 'sep_7x7', 'add'),
  (0, 4, 'identity', 'avg_3x3', 'add'),
]


class DropPath(nn.Module):
  """During training only, zero out a path (the output of one op) per sample with probability p"""
  def __init__(self):
    super().__init__()
    self.p = 0.0  # ScheduledDropPath: increased linearly from outside as training progresses

  def forward(self, x):
    if not self.training or self.p == 0.0:
      return x  # does nothing under model.eval()
    keep = 1.0 - self.p
    mask = torch.bernoulli(torch.full((x.size(0), 1, 1, 1), keep, device=x.device))
    return x * mask / keep


class Cell(nn.Module):
  def __init__(self, C, genotype=GENOTYPE):
    super().__init__()
    self.genotype = genotype
    self.ops = nn.ModuleList()
    self.drops = nn.ModuleList()
    for i1, i2, op1, op2, _ in genotype:
      self.ops.append(nn.ModuleList([OPS[op1](C), OPS[op2](C)]))
      self.drops.append(nn.ModuleList([DropPath(), DropPath()]))
    used = {i for i1, i2, *_ in genotype for i in (i1, i2)}
    self.outputs = [i for i in range(2, 2 + len(genotype)) if i not in used]  # unused hidden states

  def forward(self, h_prev, h):
    states = [h_prev, h]
    for (i1, i2, _, _, comb), (o1, o2), (d1, d2) in zip(self.genotype, self.ops, self.drops):
      a, b = d1(o1(states[i1])), d2(o2(states[i2]))
      states.append(a + b if comb == 'add' else torch.cat([a, b], dim=1))
    return torch.cat([states[i] for i in self.outputs], dim=1)


def set_drop_path(model, step, total_steps, final_p=0.3):
  """ScheduledDropPath: increase the drop probability linearly from 0 to final_p (final_p is an example)"""
  for m in model.modules():
    if isinstance(m, DropPath):
      m.p = final_p * step / total_steps


cell = Cell(C=16)
h_prev = torch.randn(2, 16, 32, 32)
h = torch.randn(2, 16, 32, 32)
cell.train()
set_drop_path(cell, step=500, total_steps=1000)
out = cell(h_prev, h)
print(cell.outputs, out.shape)  # indices of unused hidden states and the shape of the concatenated output

FAQ

Q. Why can cells found on CIFAR-10 also be used on ImageNet?
A.

Because the search target is limited to "the contents of a cell," which does not depend on depth or image size. Normal cells keep the height and width unchanged and reduction cells halve them, so the same cells can be used for images of any size by stacking them with a different number of reduction cells. In the paper, only the cell architecture is transferred to ImageNet, and the weights are trained from scratch.

Q. What is the difference between NASNet-A, NASNet-B, and NASNet-C?
A.

They are networks built from the top three cells found in the search. NASNet-A performed best, and most of the numbers in this article are for NASNet-A. NASNet-B and NASNet-C come from cells found in slightly different search spaces; for example, NASNet-B passes all hidden states created within the cell to the next layer, not just the unused ones.

Q. Can ScheduledDropPath be used in other networks?
A.

The mechanism is simple and can be incorporated into any network with branching paths. However, the paper verified its effect only on NASNet. The later AmoebaNet paper also uses it with the same settings, but reports its contribution to ImageNet top-1 accuracy as 0.3%. The effect varies with the network and training settings.

References

  1. Zoph, B., Vasudevan, V., Shlens, J., & Le, Q. V. (2018). Learning Transferable Architectures for Scalable Image Recognition. IEEE Conference on Computer Vision and Pattern Recognition (CVPR 2018). arXiv:1707.07012.
  2. Zoph, B., & Le, Q. V. (2017). Neural Architecture Search with Reinforcement Learning. International Conference on Learning Representations (ICLR 2017). arXiv:1611.01578.
  3. Schulman, J., Wolski, F., Dhariwal, P., Radford, A., & Klimov, O. (2017). Proximal Policy Optimization Algorithms. arXiv:1707.06347.