AI Logic

Neural Architecture Search (NAS)

ENAS

Updated:

How ENAS works. Left: the search flow, which alternately updates the shared weights ω on the training data and the controller θ with rewards on the validation data, and finally selects an architecture and retrains it from scratch. Right: an example RNN cell, showing, within a large graph with 4 nodes, the edges chosen by the controller (solid lines) and the edges not chosen (dashed lines), with the average of nodes 3 and 4 as the output

Background and Overview

ENAS (Efficient Neural Architecture Search) is a neural architecture search method that treats every candidate network in the search (child model) as a subgraph of one large computational graph and shares weights among child models, eliminating the need to train each candidate from scratch. It was presented by Pham, Guan, Zoph, Le, and Dean at ICML in 2018.

NAS with reinforcement learning and NASNet trained each architecture output by the controller (an RNN) from scratch and discarded the weights after measuring accuracy. The ENAS paper identifies this as the bottleneck that accounts for most of the computation. Even NASNet took 3–4 days on 450 GPUs.

The key idea of ENAS is to reuse weights, once trained, for other candidates as well. As an analogy, instead of setting up a kitchen from scratch each time a recipe is compared, a single shared kitchen with one set of tools is prepared, and every recipe uses the same tools. The tools (weights) become better suited the more they are used, and new recipes (architectures) can be tried right away.

As a result, every experiment's search finished within 16 hours on a single GPU (GTX 1080Ti), reducing GPU hours to less than 1/1000 of NAS with reinforcement learning. Even so, on Penn Treebank language modeling it outperformed NAS with reinforcement learning, and on CIFAR-10 image classification it found architectures with accuracy close to NASNet.

Theory: Search with Shared Weights

ENAS represents the entire search space as a single directed acyclic graph (DAG). Nodes are local computations, and edges are the flow of information. A child model is a subgraph that selects some of the edges and node computations of this graph, and the controller decides which edges and computations to use (right side of the figure above).

Taking the search for an RNN cell (with NN nodes) as an example, the controller chooses, for each node, "which previous node to take input from" and "which activation function to use." In the example in the figure above (N=4N = 4), the computation is as follows.

h1=tanh⁡(xtW(x)+ht−1W1(h))h2=ReLU(h1W2,1(h))h3=ReLU(h2W3,2(h))h4=tanh⁡(h1W4,1(h))ht=(h3+h4)/2\begin{aligned} h_1 &= \tanh\bigl(x_t W^{(x)} + h_{t-1} W_1^{(h)}\bigr) \\ h_2 &= \mathrm{ReLU}\bigl(h_1 W_{2,1}^{(h)}\bigr) \\ h_3 &= \mathrm{ReLU}\bigl(h_2 W_{3,2}^{(h)}\bigr) \\ h_4 &= \tanh\bigl(h_1 W_{4,1}^{(h)}\bigr) \\ h_t &= (h_3 + h_4) / 2 \end{aligned}

The average of the nodes not chosen as input by any other node (here, 3 and 4) is the cell output hth_t. The key point is that there is exactly one weight matrix Wℓ,j(h)W_{\ell,j}^{(h)} for each pair of nodes j<ℓj < \ell, and every child model uses it. Choosing a previous node is also choosing which weight matrix to use.

ENAS learns two sets of parameters: the parameters θ\theta of the controller (an LSTM with 100 units) and the weights ω\omega shared by the child models. Training alternates between the following two phases (left side of the figure above).

  1. Update the shared weights ω\omega: With the controller's policy π(m;θ)\pi(m; \theta) fixed, minimize the expected cross-entropy on the training data with SGD. During one pass over the training data, a child model mm is sampled for each mini-batch and its gradient is computed.
  2. Update the controller parameters θ\theta: With ω\omega fixed, maximize the expected reward R(m,ω)R(m, \omega) measured on the validation data. The gradient is computed with REINFORCE, using a moving-average baseline to reduce variance. Updates use Adam, and the paper performs 2000 steps per phase.

The gradient in step 1 is estimated by averaging over MM sampled child models (Eq. (1) in the paper).

∇ωEm∼π(m;θ)[L(m;ω)]≈1M∑i=1M∇ωL(mi,ω)\nabla_{\omega} \mathbb{E}_{m \sim \pi(m;\theta)}\bigl[\mathcal{L}(m; \omega)\bigr] \approx \frac{1}{M} \sum_{i=1}^{M} \nabla_{\omega} \mathcal{L}(m_i, \omega)

This estimate has higher gradient variance than standard SGD with a fixed child model, but according to the paper, M=1M = 1 (sampling only one child model per mini-batch) is enough for training to work well.

After the search, several architectures are sampled from the learned policy, and only the one with the highest reward on a single mini-batch of validation data is retrained from scratch.

The reward is measured on the validation data to select architectures that perform well on new data rather than ones that tend to overfit the training data. On CIFAR-10 the reward is the accuracy on a validation mini-batch, and on Penn Treebank it is c/validation perplexityc / \text{validation perplexity}.

Search Spaces: Whole Network and Cells

ENAS applies the same mechanism to three search spaces.

Search spaceWhat the controller chooses at each nodeCandidate operationsSize
RNN cellOne previous node, activation functiontanh, ReLU, identity, sigmoidAbout 101510^{15} for N=12N = 12
Whole network (macro)Previous layers to connect (any number), operation3×3 and 5×5 convolutions, 3×3 and 5×5 depthwise separable convolutions, 3×3 max pooling and average poolingAbout 1.6×10291.6 \times 10^{29} for 12 layers
Cell (micro)Two previous nodes, an operation for eachIdentity, 3×3 and 5×5 separable convolutions, 3×3 average pooling and max poolingAbout 1.3×10111.3 \times 10^{11} for B=7B = 7

In the macro search space, the outputs of the selected previous layers are concatenated along the channel dimension and passed to the next layer, so skip connections can also be searched. The cell search space follows NASNet: at each node other than the cell inputs (the outputs of the previous two cells), two inputs and two operations are chosen, and the two results are added. A reduction cell is built in the same form, with the chosen operations using stride 2.

The main settings on CIFAR-10 are as follows.

ItemValue
Shared weights ω\omegaNesterov momentum, cosine learning rate (max 0.05, min 0.001, T0=10T_0 = 10, Tmul=2T_{mul} = 2), weight decay 10−410^{-4}, He initialization. Search runs for 310 epochs
Controller θ\thetaAdam (learning rate 0.00035), initialized from a uniform distribution on −0.1 to 0.1. The controller's entropy is added to the reward to prevent premature convergence
Macro search space onlyTo avoid too many skip connections, the KL divergence between the connection probability and 0.4 is added to the reward (weight 0.8)

Experimental Results

The results for CIFAR-10 image classification are as follows (Table 2 in the paper).

MethodGPUsSearch daysParametersTest error
NAS with reinforcement learning + more filters80021–2837.4M3.65%
ENAS (macro)10.3221.3M4.23%
ENAS (macro) + more channels10.3238.0M3.87%
NASNet-A + Cutout4503–43.3M2.65%
ENAS (cell)10.454.6M3.54%
ENAS (cell) + Cutout10.454.6M2.89%

ENAS's error rates fall slightly short of the methods using the same kind of search space (NAS with reinforcement learning and NASNet), but its search compute is orders of magnitude smaller. The paper attributes this gap to ENAS skipping the step of sampling several architectures from the trained controller, training them to completion, and reselecting on the validation data.

The results for Penn Treebank language modeling are as follows (Table 1 in the paper; without post-training processing).

ModelParametersTest perplexity
LSTM (Yang et al., Mixture of Softmaxes)22M56.0
NAS with reinforcement learning cell54M62.4
ENAS cell24M55.8

ENAS found this cell in about 10 hours on a single GPU and achieved a perplexity more than 6 points better than the NAS with reinforcement learning cell with less than half the parameters. The cell it found uses only ReLU and tanh as activation functions, and its output is the average of 6 nodes.

The paper also confirms that the good results are not just due to the search space. Sampling architectures uniformly at random from the same search space gave 81.2 on Penn Treebank and 5.86% (macro) and 6.77% (cell) on CIFAR-10, far worse than ENAS (55.8, 4.23%, 3.54%). Training only the shared weights without training the controller also gave an error rate of 8.92%.

Practical Considerations

ENAS's reward is measured with the shared weights on a single mini-batch of validation data. It is not the performance the architecture would reach if trained from scratch, so the selected architecture must always be retrained from scratch and evaluated. The paper itself attributes the accuracy gap with NAS with reinforcement learning to skipping the step of training several candidates to completion and reselecting.

  • The controller tends to collapse onto one architecture early, so the paper applies a temperature (5.0) and a tanh bound (2.5) to the pre-softmax values and adds the controller's entropy to the reward.
  • Weight sharing also has the downside of using a lot of memory. Because one model holds the weights of every operation in the search space, the shared model grows as more candidate operations and layers are added.
  • The final selection is simplified. ENAS selects an architecture using a single mini-batch of validation data. The paper notes that, if compute allows, training several candidates to completion and selecting among them may improve results.
  • The Penn Treebank results also rely on training tricks. Training the shared weights uses a large learning rate (20.0), a small gradient clipping threshold (0.25), Variational Dropout, highway connections, and more.

Comparison with Other Methods

ENAS's idea of "overlaying all candidates on one large model and sharing weights" was carried over into later methods such as DARTS. The search compute for NAS and NASNet is taken from Table 2 of the ENAS paper, and for AmoebaNet and DARTS from their respective papers.

MethodSearch methodWeights per candidateCIFAR-10 errorSearch compute
NAS with reinforcement learningRNN + REINFORCETrained from scratch each time3.65%800 GPUs × 21–28 days
NASNetRNN + PPOTrained from scratch each time (20 epochs)2.65% (with Cutout)450 GPUs × 3–4 days
AmoebaNetEvolutionary searchTrained from scratch each time (25 epochs)3.34% (without Cutout)450 GPUs × about 7 days
ENAS (this article)RNN + REINFORCEShared across all candidates2.89% (with Cutout)1 GPU × about 0.45 days
DARTSGradient descent on a weighted sum of all candidatesShared across all candidates2.76% (with Cutout)1 GPU × 4 days (4 runs)

Guidelines for choosing:

  • When compute is limited to about one GPU and the search should use a reinforcement learning framework, ENAS is a good fit.
  • To perform the search itself with gradient descent, DARTS, which uses a weighted sum of all candidates, is the closest alternative. DARTS computes all candidates simultaneously and uses more memory, whereas ENAS computes only one child model at a time, so each computation is lighter.
  • When ample compute is available and candidates should be compared by accuracy after individual training, choose methods such as NASNet or AmoebaNet that train and evaluate candidates one by one.

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 task using MNIST data
A small-scale trial of the ENAS idea: prepare all candidate operations for each layer and share their weights (ω),
and let the controller (θ) choose one operation per layer. Updates of ω and θ alternate
(a simplified version of the paper's macro search space, without the choice of skip connections)
"""

batch_size = 128
epochs = 3
num_layers = 4
channels = 32
controller_steps = 50   # number of θ updates per epoch (2000 in the paper)

device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'

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, [55000, 5000])
train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=True)
val_loader = DataLoader(val_set, batch_size=batch_size, shuffle=True)

# The 6 operations of the paper's macro search space
OPS = {
  'conv3': lambda C: nn.Sequential(nn.Conv2d(C, C, 3, padding=1, bias=False), nn.BatchNorm2d(C), nn.ReLU()),
  'conv5': lambda C: nn.Sequential(nn.Conv2d(C, C, 5, padding=2, bias=False), nn.BatchNorm2d(C), nn.ReLU()),
  'sep3': lambda C: nn.Sequential(nn.Conv2d(C, C, 3, padding=1, groups=C, bias=False), nn.Conv2d(C, C, 1, bias=False), nn.BatchNorm2d(C), nn.ReLU()),
  'sep5': lambda C: nn.Sequential(nn.Conv2d(C, C, 5, padding=2, groups=C, bias=False), nn.Conv2d(C, C, 1, bias=False), nn.BatchNorm2d(C), nn.ReLU()),
  'max3': lambda C: nn.MaxPool2d(3, stride=1, padding=1),
  'avg3': lambda C: nn.AvgPool2d(3, stride=1, padding=1),
}
OP_NAMES = list(OPS)


class SharedModel(nn.Module):
  """A large model overlaying all child models. It holds one set of weights per layer and per operation, shared by all child models"""
  def __init__(self):
    super().__init__()
    self.stem = nn.Sequential(nn.Conv2d(1, channels, 3, padding=1, bias=False), nn.BatchNorm2d(channels))
    self.layers = nn.ModuleList([nn.ModuleList([OPS[n](channels) for n in OP_NAMES]) for _ in range(num_layers)])
    self.head = nn.Sequential(nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(channels, 10))

  def forward(self, x, arch):
    x = self.stem(x)
    for layer, op_idx in zip(self.layers, arch):
      x = layer[op_idx](x)  # use only the weights of the selected operation
    return self.head(x)


class Controller(nn.Module):
  def __init__(self, hidden=100):
    super().__init__()
    self.hidden = hidden
    self.lstm = nn.LSTMCell(hidden, hidden)
    self.embed = nn.Embedding(len(OP_NAMES) + 1, hidden)  # the last index is an empty input for the first step
    self.head = nn.Linear(hidden, len(OP_NAMES))

  def sample(self):
    h = c = torch.zeros(1, self.hidden, device=self.head.weight.device)
    inp = torch.tensor([len(OP_NAMES)], device=h.device)
    arch, log_probs, entropies = [], [], []
    for _ in range(num_layers):
      h, c = self.lstm(self.embed(inp), (h, c))
      dist = torch.distributions.Categorical(logits=self.head(h))
      idx = dist.sample()
      arch.append(idx.item())
      log_probs.append(dist.log_prob(idx))
      entropies.append(dist.entropy())
      inp = idx  # feed the previous step's choice as the next input
    return arch, torch.cat(log_probs).sum(), torch.cat(entropies).sum()


shared = SharedModel().to(device)
controller = Controller().to(device)
opt_w = optim.SGD(shared.parameters(), lr=0.05, momentum=0.9, nesterov=True, weight_decay=1e-4)
opt_c = optim.Adam(controller.parameters(), lr=3.5e-4)
baseline = None

for epoch in tqdm(range(epochs)):
  # 1. Update the shared weights ω on the training data (sample one child model per mini-batch: M = 1)
  shared.train()
  controller.eval()
  for x, y in train_loader:
    x, y = x.to(device), y.to(device)
    with torch.no_grad():
      arch, _, _ = controller.sample()
    opt_w.zero_grad()
    F.cross_entropy(shared(x, arch), y).backward()
    opt_w.step()

  # 2. Update the controller θ with REINFORCE using the reward (accuracy) on the validation data (ω fixed)
  shared.eval()
  controller.train()
  val_iter = iter(val_loader)
  for _ in range(controller_steps):
    try:
      x, y = next(val_iter)
    except StopIteration:
      val_iter = iter(val_loader)
      x, y = next(val_iter)
    arch, log_prob, entropy = controller.sample()
    with torch.no_grad():
      reward = (shared(x.to(device), arch).argmax(1) == y.to(device)).float().mean().item()
    baseline = reward if baseline is None else 0.95 * baseline + 0.05 * reward
    loss = -(reward - baseline) * log_prob - 1e-4 * entropy  # add entropy to prevent premature convergence
    opt_c.zero_grad()
    loss.backward()
    opt_c.step()

# Select an architecture: sample several and pick the one with the highest reward on one validation mini-batch
x, y = next(iter(val_loader))
best = None
with torch.no_grad():
  for _ in range(10):
    arch, _, _ = controller.sample()
    acc = (shared(x.to(device), arch).argmax(1) == y.to(device)).float().mean().item()
    if best is None or acc > best[0]:
      best = (acc, arch)
print(best[0], [OP_NAMES[i] for i in best[1]])  # retrain this architecture from scratch and evaluate it

FAQ

Q. Can architectures be compared correctly when weights are shared?
A.

Not perfectly. Because the shared weights are used by many child models, they are not necessarily optimal for any given architecture, and the ranking may differ from that obtained by training from scratch. Even so, in the paper, architectures selected by ENAS were far better than architectures chosen at random from the same search space, so the shared weights worked well enough as a guide for comparison. In the end, the selected architecture is retrained from scratch and evaluated.

Q. What is the difference between ENAS and DARTS?
A.

Both share weights, but they select architectures differently. In ENAS, a controller (an RNN) stochastically selects one child model and is trained with REINFORCE using rewards. DARTS sums the outputs of all candidates weighted by a softmax and learns those weights directly by gradient descent. ENAS computes only one child model at a time, whereas DARTS computes all candidates simultaneously.

Q. Why does training work with M = 1 (sampling only one child model)?
A.

The gradient of the shared weights ω\omega is an expectation over the distribution of child models, so even a single sampled child model gives an unbiased estimate. The variance is larger, but since a different child model is sampled for each mini-batch and many updates are made, the updates move in the direction of the expectation on average. The paper also reports that training worked well with M=1M = 1.

References

  1. Pham, H., Guan, M. Y., Zoph, B., Le, Q. V., & Dean, J. (2018). Efficient Neural Architecture Search via Parameter Sharing. Proceedings of the 35th International Conference on Machine Learning (ICML 2018), PMLR 80, 4095–4104. arXiv:1802.03268.
  2. Zoph, B., & Le, Q. V. (2017). Neural Architecture Search with Reinforcement Learning. International Conference on Learning Representations (ICLR 2017). arXiv:1611.01578.
  3. Zoph, B., Vasudevan, V., Shlens, J., & Le, Q. V. (2018). Learning Transferable Architectures for Scalable Image Recognition. CVPR 2018. arXiv:1707.07012.