AI Logic

Neural Architecture Search (NAS)

ProxylessNAS

Updated:

How ProxylessNAS works. Left: the search flow, starting from a network with all candidate paths, alternating the w update (select one path) and the α update (select two paths, validation loss plus latency), then keeping the path with the largest weight in each block and training it. Right: the mixed operation in one block, where α produces probabilities p and a binary gate g runs only one MBConv path

Background and Overview

ProxylessNAS is a neural architecture search (NAS) method that uses "binary gates", which stochastically select and run only one candidate path at a time, to keep the memory needed for search at about the level of ordinary training, so that the network architecture can be searched directly on the target data and the target hardware without small substitute tasks (proxies). Cai, Zhu, and Han (MIT) presented it at ICLR in 2019.

Gradient-based architecture search methods such as DARTS place all candidate operations in every block, compute all of their outputs, and add them up with weights. With NN candidates, memory and compute grow by roughly a factor of NN. As a result, searching directly on large datasets such as ImageNet was impossible, and these methods relied on proxies such as the following.

  • Search on a small dataset (CIFAR-10).
  • Search on a small network with fewer blocks.
  • Train for only a few epochs before evaluating.

In addition, reusing a building block (cell) found on a small network in a large network meant stacking the same cell repeatedly, so a different architecture could not be chosen for each layer.

ProxylessNAS solves this by limiting the number of paths run in each block at each training step to one (two when updating the architecture parameters). As an analogy, DARTS "puts every player on the field at once and allocates playing time according to performance", while ProxylessNAS "sends out only one player per match according to their selection probability and adjusts the probabilities little by little based on the result". Because only one player is on the field at a time, the approach scales to big matches (large datasets and large networks) as is.

As a result, it finds architectures tailored to mobile phones, GPUs, and CPUs on ImageNet in about 200 GPU hours per search. This is roughly 1/200 of MnasNet (estimated at about 40,000 GPU hours).

Theory

ProxylessNAS treats search as path pruning. While training a large network that contains every candidate path (an over-parameterized network), it learns which paths are unnecessary, and at the end it prunes those paths to extract a small network. The procedure is as follows (left of the figure above).

  1. Build the over-parameterized network: Each block becomes a mixed operation with NN candidate paths in parallel. Each path has one architecture parameter αi\alpha_i.
  2. Update the weights ww: Freeze α\alpha, sample one binary gate per mini-batch, and update only the weights of the selected path with the training loss.
  3. Update the architecture parameters α\alpha: Freeze ww, sample two paths, and update the α\alpha of those two paths with the validation loss (plus the latency loss). Steps 2 and 3 alternate.
  4. Prune: In each block, keep only the path with the largest path weight pip_i.
  5. Train: Train the resulting small network and use it.

The path weights are probabilities obtained by passing α\alpha through a softmax: pi=exp⁡(αi)/∑jexp⁡(αj)p_i = \exp(\alpha_i) / \sum_j \exp(\alpha_j). DARTS added the outputs of all paths weighted by these pip_i. ProxylessNAS instead samples a binary gate gg in which exactly one entry is 1, according to pp (Eq. (2) in the paper).

g=binarize(p1,…,pN)={[1,0,…,0]with probability p1⋮[0,0,…,1]with probability pNg = \mathrm{binarize}(p_1, \dots, p_N) = \begin{cases} [1, 0, \dots, 0] & \text{with probability } p_1 \\ \quad\vdots \\ [0, 0, \dots, 1] & \text{with probability } p_N \end{cases}

The output of the mixed operation is only the output of the path whose gate is 1 (Eq. (3) in the paper).

mOBinary(x)=∑i=1Ngi oi(x)m_{\mathcal{O}}^{\text{Binary}}(x) = \sum_{i=1}^{N} g_i \, o_i(x)

Because the other paths are not computed, their feature maps do not need to be kept in memory, and memory usage stays at about the level of training a single small network. The paper states that this saves memory by more than an order of magnitude.

Gradients of the Architecture Parameters

Because the binary gate is generated stochastically from α\alpha, gradients do not flow to α\alpha as is. Following BinaryConnect, which trains networks with binarized weights, ProxylessNAS uses the gradient with respect to the gate gjg_j in place of the gradient with respect to pjp_j (Eq. (4) in the paper).

∂L∂αi=∑j=1N∂L∂pj∂pj∂αi≈∑j=1N∂L∂gj∂pj∂αi=∑j=1N∂L∂gj pj(δij−pi)\frac{\partial L}{\partial \alpha_i} = \sum_{j=1}^{N} \frac{\partial L}{\partial p_j} \frac{\partial p_j}{\partial \alpha_i} \approx \sum_{j=1}^{N} \frac{\partial L}{\partial g_j} \frac{\partial p_j}{\partial \alpha_i} = \sum_{j=1}^{N} \frac{\partial L}{\partial g_j} \, p_j (\delta_{ij} - p_i)

δij\delta_{ij} is 1 when i=ji = j and 0 otherwise. ∂L/∂gj\partial L / \partial g_j is obtained by backpropagation, but this requires the output oj(x)o_j(x) of path jj. Computing it for all NN paths would again multiply memory by NN.

Therefore, when updating α\alpha, only two paths are sampled from the NN paths according to the multinomial distribution (p1,…,pN)(p_1, \dots, p_N), and the rest are treated as if they did not exist. The candidates are temporarily reduced to these two, pp and gg are recomputed within the pair, and the update uses Eq. (4). After the update, the same value is added to both α\alpha values to rescale them so that the path weights pp of the unselected paths stay unchanged. The paper motivates this decomposition with the intuition that "if a path is the best choice at a particular position, it should be better than any other path when compared one-on-one".

Appendix D of the paper also describes an alternative implementation that avoids the approximation. The outputs oj(x)o_j(x) of the paths that were not run are computed during the backward pass after the output gradient ∇yL\nabla_y L is available, and are discarded as soon as ∂L/∂gj\partial L / \partial g_j is obtained. This allows Eq. (4) to be computed without holding the outputs of all paths at the same time.

Adding Latency to the Loss

In addition to accuracy, ProxylessNAS directly targets latency (the time to run inference on one image) on the target hardware. Since latency is not differentiable, the paper presents two approaches.

The first expresses latency as a continuous function of the architecture parameters. The expected latency of the ii-th block is the sum of predicted path latencies weighted by the path probabilities (Eq. (5) in the paper).

E[latencyi]=∑jpji×F(oji)\mathbb{E}[\text{latency}_i] = \sum_{j} p_j^{i} \times F(o_j^{i})

F(⋅)F(\cdot) is a latency prediction model, and F(oji)F(o_j^i) is the predicted latency of path ojio_j^i. Because blocks run sequentially, the expected latency of the whole network is the sum of the block expectations, E[latency]=∑iE[latencyi]\mathbb{E}[\text{latency}] = \sum_i \mathbb{E}[\text{latency}_i] (Eq. (6) in the paper). This is added to the loss (Eq. (7) in the paper).

Loss=LossCE+λ1∥w∥22+λ2 E[latency]\text{Loss} = \text{Loss}_{\text{CE}} + \lambda_1 \|w\|_2^2 + \lambda_2 \, \mathbb{E}[\text{latency}]

LossCE\text{Loss}_{\text{CE}} is the cross-entropy, λ1∥w∥22\lambda_1 \|w\|_2^2 is weight decay, and λ2>0\lambda_2 > 0 is a coefficient that sets the trade-off between accuracy and latency. Architectures found with this approach are called Proxyless-G (G for gradient).

The second trains the binary gates with REINFORCE (policy gradient). Since the reward RR does not need to be differentiable, latency can be put directly into the reward (Eq. (8) in the paper).

∇αJ(α)=Eg∼α[R(Ng) ∇αlog⁡p(g)]≈1M∑i=1MR(Ngi) ∇αlog⁡p(gi)\nabla_{\alpha} J(\alpha) = \mathbb{E}_{g \sim \alpha}\bigl[R(\mathcal{N}_g) \, \nabla_{\alpha} \log p(g)\bigr] \approx \frac{1}{M} \sum_{i=1}^{M} R(\mathcal{N}_{g^i}) \, \nabla_{\alpha} \log p(g^i)

Ng\mathcal{N}_g is the small network selected by gate gg, and MM is the number of samples. In the ImageNet experiments, the reward is ACC(m)×[LAT(m)/T]wACC(m) \times [LAT(m)/T]^{w} (TT is the target latency and ww is a trade-off coefficient). Architectures found with this approach are called Proxyless-R (R for REINFORCE). The formula resembles NAS with reinforcement learning, but no RNN controller is used; the binary-gate parameters α\alpha are updated directly.

How It Works and Why It Is Effective

ProxylessNAS can search without proxies for three reasons.

  • Memory does not scale with the number of paths: At each training step, one path runs for the weight update and two for the architecture parameter update. Adding more candidates barely changes the memory per step, so the search can run on large data with large networks as is.
  • No controller is needed: Reinforcement-learning NAS methods such as NASNet train a separate RNN that generates architectures and train a network for each candidate. ProxylessNAS finishes the search by training a single over-parameterized network, so its GPU hours are close to those of ordinary training.
  • Each block can have a different architecture: Since there is no need to stack a cell found on a proxy, a different operation can be chosen for each block. In the ImageNet experiments, each block's candidates are the MBConv (inverted residual block) of MobileNetV2 with kernel sizes {3,5,7}\{3, 5, 7\} and expansion ratios {3,6}\{3, 6\}, plus a "zero" operation that skips the block. Because zero can be chosen, the search can lean toward either shallow-and-wide or deep-and-narrow networks.

Adding latency to the loss also matters. In the paper, Proxyless-G searched without the latency loss produced an architecture with 158ms latency on a Pixel 1. Shrinking its width to reach 83ms gave 71.8% top-1 accuracy, 2.4 points lower than with the latency loss (74.2%). When accuracy is the only objective, there is no reason to prefer computationally cheap operations.

Measuring latency on the device every time is slow (each measurement averages hundreds of runs and takes about 20 seconds) and requires many devices. The paper therefore uses a latency prediction model for mobile phones. It sampled 5,000 architectures from the search space, built the model from 4,000 of them, and validated on the rest; the error (RMSE) against measurements on a Pixel 1 was 0.75ms. The model's inputs are the operation type, the input and output feature map sizes, and the kernel size, stride, and expansion ratio.

The difference in architectures chosen for each device is another important observation in the paper. The GPU architecture was shallow and wide, and preferred large MBConvs (7×7, expansion ratio 6), especially in the high-resolution early stages. The CPU architecture was deep and narrow and preferred small MBConvs. The paper explains that GPUs have high parallelism, so merging work into a single large operation runs faster. On every device, large MBConvs were chosen in the first block of each stage that downsamples the feature map.

Experimental Results

Results on ImageNet for mobile phones (Google Pixel 1, latency constraint of 80ms or less) are as follows (Table 2 in the paper).

ModelTop-1Top-5Mobile latencySearch cost (GPU hours)
MobileNet (V1)70.6%89.5%113msManually designed
MobileNetV272.0%91.0%75msManually designed
NASNet-A74.0%91.3%183ms48,000
AmoebaNet-A74.5%92.0%190ms75,600
MnasNet74.0%91.8%76ms40,000
Proxyless-G (no latency loss)71.8%90.3%83ms200
Proxyless-G (with latency loss)74.2%91.7%79ms200
Proxyless-R74.6%92.2%78ms200

Proxyless-R achieved top-1 accuracy 2.6 points higher than MobileNetV2 and 0.6 points higher than MnasNet, with slightly lower latency. In a comparison across width multipliers, at around 74.6% top-1, MobileNetV2 took 143ms while ProxylessNAS took 78ms (1.83× faster).

Results for the architecture searched for GPUs (Tesla V100, batch size 8) are as follows (excerpt from Table 3 in the paper).

ModelTop-1Top-5GPU latency
MobileNetV272.0%91.0%6.1ms
ShuffleNet V2 (1.5)72.6%-7.3ms
ResNet-3473.3%91.4%8.0ms
DARTS73.1%91.0%-
MnasNet74.0%91.8%6.1ms
ProxylessNAS (GPU)75.1%92.5%5.1ms

The three architectures searched for each device, measured on the other devices as well, give the following results (Table 4 in the paper). Each architecture was fastest on the device it was searched for and slower on the others.

ArchitectureTop-1GPU latencyCPU latencyMobile latency
ProxylessNAS (GPU)75.1%5.1ms204.9ms124ms
ProxylessNAS (CPU)75.3%7.4ms138.7ms116ms
ProxylessNAS (mobile)74.6%7.2ms164.1ms78ms

On CIFAR-10, the search used a tree-structured cell search space (based on PyramidNet) and searched 648 choices directly without repeating cells. With Cutout, the test error was 2.08% for Proxyless-G (5.7M parameters) and 2.30% for Proxyless-R (5.8M parameters), on par with AmoebaNet-B (2.13%, 34.9M parameters) with far fewer parameters (Table 1 in the paper).

Practical Considerations

The latency prediction model and the latency loss coefficient λ2\lambda_2 (for Proxyless-R, the target latency TT and the coefficient ww) must be prepared for each target device. If the prediction model deviates from the real device's latency, the search will pick architectures that are fast only according to the prediction. The paper also uses the prediction model for search and measures the reported latency on real devices.

  • The architectures found are limited to the search space: In the ImageNet experiments, the candidates are only variants of the MobileNetV2 MBConv plus zero. Layer types not included in the search space (for example, components like SE) are never selected.
  • The searched architecture is retrained: The search decides the path in each block, and the resulting small network is trained again. On CIFAR-10, it is trained with the same settings as the search, but with the number of epochs increased from 200 to 300.
  • More hyperparameters: The optimizer for the architecture parameters (in the paper, Adam with a learning rate of 0.006 for the gradient method on CIFAR-10, 0.01 for REINFORCE, and 0.001 on ImageNet) and the validation split (5,000 images taken from the training data on CIFAR-10, 50,000 on ImageNet) must be chosen.
  • Stochastic selection: Since a different path runs at each step, how often each path's weights are trained depends on that path's probability.

Comparison with Other Methods

Compared with NAS methods based on reinforcement learning, evolution, and gradients, ProxylessNAS differs in the following ways.

MethodHow the architecture is chosenMemory during searchDirect search on ImageNetDifferent architecture per blockHardware latency
NASNetRNN controller trained with RLOne candidate (each candidate trained)No (reuses CIFAR-10 cell)No (repeats cells)Not used
ENASRNN controller + weight sharingOne candidateNoNoNot used
DARTSGradient descent on weighted sum of all pathsProportional to number of candidatesNo (not enough memory)NoNot used
MnasNetRNN controller trained with RLOne candidate (each candidate trained)Yes (short 5-epoch training)Yes (per each of 7 blocks; layers repeat within a block)Measured on device
ProxylessNASBinary gates trained with gradients or REINFORCEOne or two pathsYesYes (per block)Prediction model added to loss

Rough guidelines for choosing:

  • Searching for an architecture tailored to a specific device on large data with little compute: ProxylessNAS is a good fit, though building a latency prediction model takes effort.
  • Searching for a cell architecture easily on small data: DARTS or ENAS is often sufficient.
  • Choosing architectures many times for many devices and constraints: ProxylessNAS needs to redo the search and training for each device. Once-for-All trains one large network once and extracts small networks for each device from it without retraining.

PyTorch example

Show code
python
import math
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

"""
A small experiment with ProxylessNAS (Proxyless-G) binary gates and the latency loss on MNIST.
- w update: in each block, sample and run only one path (Eqs. 2 and 3)
- α update: sample only two paths, update with the Eq. 4 gradient and the latency loss (Eqs. 5-7),
            then rescale α so that the probabilities of the unselected paths stay unchanged
"""

batch_size = 64
epochs = 2
lr_w = 0.05
lr_alpha = 0.006      # same value as the paper's gradient method on CIFAR-10
lambda_lat = 0.1      # latency loss coefficient λ2

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, [50000, 10000])  # validation data is used to update α
train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=True)
val_loader = DataLoader(val_set, batch_size=batch_size, shuffle=True)


class MBConv(nn.Module):
  """MobileNetV2 inverted residual block (expand with 1x1 -> depthwise conv -> project back with 1x1)"""
  def __init__(self, C, k, expand):
    super().__init__()
    H = C * expand
    self.body = nn.Sequential(
      nn.Conv2d(C, H, 1, bias=False), nn.BatchNorm2d(H), nn.ReLU6(),
      nn.Conv2d(H, H, k, padding=k // 2, groups=H, bias=False), nn.BatchNorm2d(H), nn.ReLU6(),
      nn.Conv2d(H, C, 1, bias=False), nn.BatchNorm2d(C))

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


class Zero(nn.Module):
  """Zero path. Combined with the residual connection, it skips the block"""
  def forward(self, x):
    return torch.zeros_like(x)


# Candidate paths and the predicted per-device latency F(o) (ms). Example values here; in practice, measure on the device or use a prediction model
CANDIDATES = [('mb3_k3', 3, 3, 1.0), ('mb3_k5', 5, 3, 1.4), ('mb6_k3', 3, 6, 1.8), ('mb6_k5', 5, 6, 2.5), ('zero', 0, 0, 0.0)]


class BinaryMixedOp(nn.Module):
  def __init__(self, C):
    super().__init__()
    self.ops = nn.ModuleList([Zero() if k == 0 else MBConv(C, k, e) for _, k, e, _ in CANDIDATES])
    self.register_buffer('latency', torch.tensor([lat for *_, lat in CANDIDATES]))
    self.alpha = nn.Parameter(torch.zeros(len(CANDIDATES)))  # architecture parameters α
    self.mode = 'weight'
    self.sampled = None

  def probs(self):
    return F.softmax(self.alpha, dim=0)  # path weights p

  def expected_latency(self):
    return (self.probs() * self.latency).sum()  # Eq. 5

  def forward(self, x):
    if self.mode == 'weight':
      # Eqs. 2 and 3: pick only one path according to p and compute only that path (α stays frozen)
      j = torch.multinomial(self.probs().detach(), 1).item()
      return x + self.ops[j](x)
    # α update: pick two paths according to p, then recompute p and g within the pair
    idx = torch.multinomial(self.probs().detach(), 2, replacement=False)
    self.sampled = idx
    p2 = F.softmax(self.alpha[idx], dim=0)
    j = torch.multinomial(p2.detach(), 1).item()
    g = F.one_hot(torch.tensor(j), 2).float().to(x.device)
    # Value stays the binary gate g, gradient flows to p2 -> same gradient as Eq. 4, which replaces ∂L/∂p with ∂L/∂g
    gate = g - p2.detach() + p2
    out = sum(gate[k] * self.ops[i](x) for k, i in enumerate(idx.tolist()))
    return x + out


class SearchNet(nn.Module):
  def __init__(self, C=16, n_blocks=4):
    super().__init__()
    self.stem = nn.Sequential(nn.Conv2d(1, C, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(C), nn.ReLU6())
    self.blocks = nn.ModuleList([BinaryMixedOp(C) for _ in range(n_blocks)])
    self.head = nn.Sequential(nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(C, 10))

  def forward(self, x):
    x = self.stem(x)
    for b in self.blocks:
      x = b(x)
    return self.head(x)

  def set_mode(self, mode):
    for b in self.blocks:
      b.mode = mode

  def arch_params(self):
    return [b.alpha for b in self.blocks]

  def weight_params(self):
    return [p for n, p in self.named_parameters() if not n.endswith('alpha')]


model = SearchNet().to(device)
criterion = nn.CrossEntropyLoss()
opt_w = optim.SGD(model.weight_params(), lr=lr_w, momentum=0.9, weight_decay=4e-5)  # λ1‖w‖² via weight_decay
opt_alpha = optim.Adam(model.arch_params(), lr=lr_alpha)

for epoch in range(epochs):
  model.train()
  for (x_tr, y_tr), (x_val, y_val) in zip(train_loader, val_loader):
    x_tr, y_tr, x_val, y_val = x_tr.to(device), y_tr.to(device), x_val.to(device), y_val.to(device)

    # 1. Update w (run only one path)
    model.set_mode('weight')
    opt_w.zero_grad()
    criterion(model(x_tr), y_tr).backward()
    opt_w.step()

    # 2. Update α (run only two paths; loss = cross-entropy + λ2 E[latency], Eqs. 6 and 7)
    model.set_mode('arch')
    old = [a.detach().clone() for a in model.arch_params()]
    opt_alpha.zero_grad()
    loss = criterion(model(x_val), y_val)
    loss = loss + lambda_lat * sum(b.expected_latency() for b in model.blocks)
    loss.backward()
    opt_alpha.step()
    with torch.no_grad():
      for b, a_old in zip(model.blocks, old):
        idx = b.sampled
        new_pair = b.alpha[idx].clone()
        b.alpha.copy_(a_old)  # restore α of the unselected paths
        # keep the sum of exp(α) over the two paths equal to its value before the update, so the other paths' p is unchanged
        offset = torch.logsumexp(a_old[idx], 0) - torch.logsumexp(new_pair, 0)
        b.alpha[idx] = new_pair + offset

# Pruning: keep the path with the largest probability in each block
for i, b in enumerate(model.blocks):
  p = b.probs().detach().cpu()
  best = p.argmax().item()
  print(f"block {i}: {CANDIDATES[best][0]} (p={p[best]:.2f}, expected latency={b.expected_latency().item():.2f}ms)")

FAQ

Q. What is the "proxy" in ProxylessNAS?
A.

A proxy is a small, cheap task used for search in place of the real task. Examples include searching on CIFAR-10 instead of ImageNet, searching on a network with fewer blocks, and evaluating after training for only a few epochs. The best architecture on a proxy is not necessarily the best on the real task or hardware. By reducing memory with binary gates, ProxylessNAS searches directly on ImageNet and the target hardware without proxies.

Q. What is the main difference between DARTS and ProxylessNAS?
A.

How the output of the mixed operation is formed. DARTS adds the outputs of all candidates weighted by softmax(α)\mathrm{softmax}(\alpha), so it computes all paths at once and memory grows with the number of candidates. ProxylessNAS selects a path with a binary gate in which exactly one entry is 1 according to the probabilities pp, so only one or two paths run at a time. In exchange, the gradient of α\alpha is obtained with an approximation borrowed from BinaryConnect (Eq. (4)).

Q. Latency is not differentiable, so how is it added to the loss?
A.

The latency of each block is expressed as the sum of predicted latencies weighted by the path probabilities, E[latencyi]=∑jpjF(oj)\mathbb{E}[\text{latency}_i] = \sum_j p_j F(o_j). Since pjp_j is a function of α\alpha, this expectation is differentiable with respect to α\alpha. The predicted values F(oj)F(o_j) are fixed in advance from measurements on the real device or from a prediction model built from those measurements. Another option is Proxyless-R, which puts latency into the reward with REINFORCE.

References

  1. Cai, H., Zhu, L., & Han, S. (2019). ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware. International Conference on Learning Representations (ICLR 2019). arXiv:1812.00332.
  2. MIT HAN Lab. ProxylessNAS (official pretrained models and evaluation code). GitHub.