Neural Architecture Search with Reinforcement Learning
Updated:
Background and Overview
NAS (Neural Architecture Search) with reinforcement learning is a method that prepares an RNN (the controller) that writes out a network architecture as a "sequence of values," actually trains the architectures it produces, and trains the RNN with reinforcement learning using the resulting validation accuracy as the reward. It was presented by Zoph and Le at ICLR in 2017 and sparked the spread of research on automatically searching for network architectures themselves (NAS).
Until then, architectural choices such as the number of layers, filter sizes, and how layers connect were decided by people through experience and trial and error. Hyperparameter search methods such as random search and Bayesian optimization can be used, but while they are good at searching a fixed number of values, they struggle with variable-length architectures in which "the number of values to decide changes with the number of layers."
The paper's starting point is the observation that a network architecture can be written as a variable-length string. A string can be output one token at a time by an RNN, just as a sentence is generated word by word. As a cooking analogy, it is like an apprentice chef (the controller) who writes a recipe line by line, has a dish actually cooked from that recipe, looks at how the taste is rated (the reward), and gradually learns to write recipes that get higher ratings.
As a result, for CIFAR-10 image classification it found a convolutional network with a test error of 3.65%, close to the best human-designed architecture at the time, and for Penn Treebank language modeling it found a new RNN cell that outperforms the LSTM. On the other hand, because every architecture evaluated requires training a network to completion, the search required massive compute using 800 GPUs.
Theory
The search proceeds by repeating the following four steps (left side of the figure above).
Output an architecture: The controller outputs a sequence of values (tokens) a1:T representing an architecture, choosing each one with a softmax.
Train the child network: Build a network with the output architecture (the child network) and train it on the training data.
Measure the reward: Use the trained child network's accuracy on the validation data as the reward R.
Update the controller: Update the controller parameters θc with a policy gradient method so that architectures with high rewards become more likely to be output.
When searching for convolutional networks, the controller outputs, for each layer, "filter height → filter width → stride height → stride width → number of filters" in order (right side of the figure above). Each step is a softmax classification, and the selected value becomes the input to the next step. Output stops once the predetermined number of layers is reached.
The controller's objective is to maximize the expected reward of the architectures it outputs.
J(θc)=EP(a1:T;θc)[R]
The reward R is only known after training the child network and is not differentiable with respect to θc. The paper therefore uses REINFORCE (Williams, 1992), a policy gradient method, and estimates the gradient with the following expression (Section 3.2 of the paper).
m is the number of architectures output per update, and T is the number of values that define one architecture.
Rk is the validation accuracy of the k-th architecture.
b is the baseline, an exponential moving average of the accuracies of previous architectures.
The expression means: "increase the probability of the choices that led to above-average accuracy, and decrease the probability of the choices that led to below-average accuracy." Without subtracting b, the reward is positive for every architecture, so probabilities would only be pushed upward, and the variance of the gradient estimate would be large. As long as b does not depend on the current choice, subtracting it does not bias the gradient estimate.
The reward is measured on the validation data because the goal is to find architectures that work well on new data. In the CIFAR-10 experiments, 5,000 of the 50,000 training images are held out as validation data, and child networks are trained on the remaining 45,000.
Expanding the Search Space and Parallelization
The simplest search space "just stacks convolutional layers in sequence," but the paper expands it in three directions.
Skip connections: An "anchor" is placed at the N-th layer, and whether each earlier layer j becomes an input to this layer i is chosen with the sigmoid probability in the expression below (Section 3.3 of the paper). If multiple inputs are chosen, they are concatenated along the channel dimension. This makes it possible to build branched architectures such as ResNet and GoogLeNet.
Layer types: Adding a step that chooses the layer type (pooling, batch normalization, etc.) allows layers other than convolutions to be chosen.
RNN cells: The computation that produces ht from the input xt and the previous output ht−1 is represented as a tree, and at each node of the tree a "combination method (addition or element-wise multiplication)" and an "activation function (identity, tanh, sigmoid, or ReLU)" are chosen. Where to connect the LSTM memory cells ct−1,ct is also chosen.
P(layer j is an input to layer i)=sigmoid(v⊤tanh(Wprevhj+Wcurrhi))
Here, hj,hi are the controller's hidden states at the anchors, and Wprev,Wcurr,v are learned parameters. Because connections are also chosen probabilistically, REINFORCE can be used as is.
Since training a child network takes hours, the paper speeds up the search with distributed training. S parameter servers hold the shared parameters, and K controller replicas each output m architectures and train them in parallel, sending the resulting gradients asynchronously to the parameter servers. In the CIFAR-10 experiments, S=20, K=100, and m=8, so 800 networks were always being trained simultaneously on 800 GPUs.
The main settings on CIFAR-10 are as follows.
Item
Value
Values chosen per layer
Filter height and width (1, 3, 5, 7), number of filters (24, 36, 48, 64), stride (fixed at 1, or chosen from 1, 2, 3)
Controller
2-layer LSTM (35 units per layer), Adam (learning rate 0.0006), weights initialized uniformly from −0.08 to 0.08
The maximum validation accuracy over the last 5 epochs, cubed
Number of layers
Starts at 6 layers and adds 2 layers every 1,600 architectures output
Architectures evaluated
12,800
After the search, the architecture with the highest validation accuracy is selected, the learning rate, weight decay, and other settings are tuned with a small grid search, and the network is retrained to completion.
Experimental Results
The results for CIFAR-10 image classification are as follows (Table 1 in the paper). Four settings with search spaces of different breadth are compared.
The best result of 3.65% beats the DenseNet of the time (3.74%) and, according to the paper, runs 1.05x faster. It does not, however, reach DenseNet-BC (3.46%), which reduces parameters with 1×1 convolutions. The v1 architecture uses many rectangular filters and favors larger filters in higher layers, characteristics that differ from human designs. Removing all skip connections from this architecture worsened the error rate to 7.97%.
For Penn Treebank language modeling, the discovered RNN cell outperformed the LSTM (Table 2 in the paper).
This cell also beat the LSTM when transferred to character-level language modeling (1.214 bits per character), and replacing the LSTM in machine translation (GNMT) with it raised BLEU by 0.5. The discovered cell is included in TensorFlow under the name NASCell.
The paper also compares against selecting architectures at random with the same compute, showing that the controller trained with policy gradients yields both a better best architecture and a better average over the top architectures. The controller learns to output better architectures as the search progresses.
Practical Considerations
Every architecture evaluated requires training a child network to completion, so the search is extremely expensive. The CIFAR-10 search used 800 GPUs and, according to the subsequent NASNet paper, took 28 days. If compute on that scale is not available, consider ENAS, which shares weights, or DARTS, which searches with gradients.
The search space strongly affects the results. In this paper too, broadening the search space by allowing strides to be chosen worsened the error rate from 5.50% to 6.01%. A broader space does not necessarily yield better architectures.
The architecture found by the search is not necessarily the best as is. In the paper as well, the best result of 3.65% came from adding more filters to the found architecture and retuning the learning rate and other settings.
Reward design changes the results. The paper uses the cube of the accuracy on CIFAR-10 and a value inversely proportional to the square of the perplexity on Penn Treebank as rewards; the shape of the reward is part of the design.
The architecture is tailored to the data used in the search. Using it on other data or with networks of other sizes requires re-evaluation. NASNet addressed this problem by transferring building blocks searched on small data to large data.
Comparison with Other Methods
After NAS with reinforcement learning, a series of methods were proposed to reduce the compute of the search. The CIFAR-10 numbers are the values reported in each method's paper.
Method
What is searched
Search method
CIFAR-10 error
Search compute
NAS with reinforcement learning (this article)
Whole network
RNN + REINFORCE; each architecture trained to completion
To understand how the computation works or learn the basic form of searching with reinforcement learning, starting with the method in this article is the shortest path. Many later methods inherit its "controller + reward" structure.
To greatly reduce compute, choose ENAS, which shares weights, or DARTS, which searches with gradients.
To transfer the found architecture to large data or other tasks, NASNet's approach of searching for cells is a good fit.
To also include processing speed on devices such as smartphones as a constraint, the MnasNet approach adds latency to the reward.
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, Subset
from tqdm import tqdm
"""
Image classification task using MNIST data
The controller (LSTM) outputs the values of convolutional layers one at a time,
and is updated with REINFORCE using the child network's validation accuracy as the reward
(to keep computation light, each child network is trained for one epoch on a small subset of the data)
"""
# Hyperparameters
num_layers = 3 # number of convolutional layers in the child network
num_samples = 30 # number of architectures output by the controller (12,800 for CIFAR-10 in the paper)
lr_controller = 6e-4 # controller learning rate (same as the paper's CIFAR-10 setting)
baseline_decay = 0.9 # decay rate of the baseline (exponential moving average of rewards)
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
# Dataset (separate training data from the validation data used to measure the reward)
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
full_train = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
train_loader = DataLoader(Subset(full_train, range(0, 5000)), batch_size=64, shuffle=True)
val_loader = DataLoader(Subset(full_train, range(55000, 60000)), batch_size=256)
# Values chosen per layer and their candidates (a subset of the candidates in Section 4.1 of the paper)
CHOICES = [
('kernel_h', [1, 3, 5, 7]),
('kernel_w', [1, 3, 5, 7]),
('filters', [24, 36, 48, 64]),
]
class Controller(nn.Module):
"""An RNN that takes the value chosen at the previous step as input and chooses the next value with a softmax"""
def __init__(self, hidden=35):
super().__init__()
self.hidden = hidden
self.lstm = nn.LSTMCell(hidden, hidden)
self.start = nn.Parameter(torch.zeros(1, hidden))
self.embeds = nn.ModuleList([nn.Embedding(len(c), hidden) for _, c in CHOICES])
self.heads = nn.ModuleList([nn.Linear(hidden, len(c)) for _, c in CHOICES])
for p in self.parameters():
nn.init.uniform_(p, -0.08, 0.08) # same initialization as the paper
def sample(self):
h = c = torch.zeros(1, self.hidden, device=self.start.device)
x = self.start
arch, log_probs = [], []
for _ in range(num_layers):
layer = {}
for k, (name, cands) in enumerate(CHOICES):
h, c = self.lstm(x, (h, c))
dist = torch.distributions.Categorical(logits=self.heads[k](h))
idx = dist.sample()
log_probs.append(dist.log_prob(idx))
layer[name] = cands[idx.item()]
x = self.embeds[k](idx) # feed the chosen value as the input to the next step
arch.append(layer)
return arch, torch.cat(log_probs).sum()
def build_child(arch):
layers, in_ch = [], 1
for layer in arch:
kh, kw = layer['kernel_h'], layer['kernel_w']
layers += [nn.Conv2d(in_ch, layer['filters'], (kh, kw), padding=(kh // 2, kw // 2)),
nn.BatchNorm2d(layer['filters']), nn.ReLU()]
in_ch = layer['filters']
layers += [nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(in_ch, 10)]
return nn.Sequential(*layers)
def train_and_evaluate(arch):
child = build_child(arch).to(device)
opt = optim.SGD(child.parameters(), lr=0.1, momentum=0.9, nesterov=True)
child.train()
for x, y in train_loader:
x, y = x.to(device), y.to(device)
opt.zero_grad()
F.cross_entropy(child(x), y).backward()
opt.step()
child.eval()
correct = 0
with torch.no_grad():
for x, y in val_loader:
correct += (child(x.to(device)).argmax(1) == y.to(device)).sum().item()
return correct / len(val_loader.dataset)
controller = Controller().to(device)
opt_c = optim.Adam(controller.parameters(), lr=lr_controller)
baseline = None
best = (0.0, None)
for step in tqdm(range(num_samples)):
arch, log_prob = controller.sample()
reward = train_and_evaluate(arch) # reward: validation accuracy
baseline = reward if baseline is None else baseline_decay * baseline + (1 - baseline_decay) * reward
# REINFORCE: scale the gradient of the log-probability of the chosen values by (R - b) to raise expected accuracy
loss = -(reward - baseline) * log_prob
opt_c.zero_grad()
loss.backward()
opt_c.step()
if reward > best[0]:
best = (reward, arch)
print(f"best val acc: {best[0]:.4f}")
print(best[1])
FAQ
Q. Why use reinforcement learning for architecture search?
A.
Because the reward, the validation accuracy, is only known after training the child network and is not differentiable with respect to the controller's parameters. REINFORCE can estimate the direction that increases the expected reward without differentiating the reward itself, simply by summing the gradients of the log-probabilities of the chosen values scaled by (R−b).
Q. Why is the controller an RNN?
A.
Because a network architecture can be written as a variable-length sequence of values, where the number of values to decide changes with the number of layers. An RNN can choose the next value one at a time based on previously chosen values, just as a sentence is generated word by word. For example, it can adjust how it chooses the next value depending on the filter size chosen for the layer above.
Q. Can it be used with a single local GPU?
A.
The paper's scale (about 28 days on 800 GPUs) is not realistic. The mechanism can be tried by shrinking the child networks and reducing the number of training epochs, but accuracy after short training can differ from accuracy after full training. For practical use, methods such as ENAS, which shares weights and searches in less than a day on a single GPU, are better suited.