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 N candidates, memory and compute grow by roughly a factor of N. As a result, searching directly on large datasets such as ImageNet was impossible, and these methods relied on proxies such as the following.
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).
Build the over-parameterized network: Each block becomes a mixed operation with N candidate paths in parallel. Each path has one architecture parameter αi.
Update the weights w: Freeze α, sample one binary gate per mini-batch, and update only the weights of the selected path with the training loss.
Update the architecture parameters α: Freeze w, sample two paths, and update the α of those two paths with the validation loss (plus the latency loss). Steps 2 and 3 alternate.
Prune: In each block, keep only the path with the largest path weight pi.
Train: Train the resulting small network and use it.
The path weights are probabilities obtained by passing α through a softmax: pi=exp(αi)/∑jexp(αj). DARTS added the outputs of all paths weighted by these pi. ProxylessNAS instead samples a binary gategin which exactly one entry is 1, according to p (Eq. (2) in the paper).
g=binarize(p1,…,pN)=⎩⎨⎧[1,0,…,0]⋮[0,0,…,1]with probability p1with probability pN
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=1∑Ngioi(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 α, gradients do not flow to α as is. Following BinaryConnect, which trains networks with binarized weights, ProxylessNAS uses the gradient with respect to the gate gj in place of the gradient with respect to pj (Eq. (4) in the paper).
δij is 1 when i=j and 0 otherwise. ∂L/∂gj is obtained by backpropagation, but this requires the output oj(x) of path j. Computing it for all N paths would again multiply memory by N.
Therefore, when updating α, only two paths are sampled from the N paths according to the multinomial distribution (p1,…,pN), and the rest are treated as if they did not exist. The candidates are temporarily reduced to these two, p and g are recomputed within the pair, and the update uses Eq. (4). After the update, the same value is added to both α values to rescale them so that the path weights p 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) of the paths that were not run are computed during the backward pass after the output gradient ∇yL is available, and are discarded as soon as ∂L/∂gj 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 i-th block is the sum of predicted path latencies weighted by the path probabilities (Eq. (5) in the paper).
E[latencyi]=j∑pji×F(oji)
F(⋅) is a latency prediction model, and F(oji) is the predicted latency of path oji. Because blocks run sequentially, the expected latency of the whole network is the sum of the block expectations, E[latency]=∑iE[latencyi] (Eq. (6) in the paper). This is added to the loss (Eq. (7) in the paper).
Loss=LossCE+λ1∥w∥22+λ2E[latency]
LossCE is the cross-entropy, λ1∥w∥22 is weight decay, and λ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 R does not need to be differentiable, latency can be put directly into the reward (Eq. (8) in the paper).
Ng is the small network selected by gate g, and M is the number of samples. In the ImageNet experiments, the reward is ACC(m)×[LAT(m)/T]w (T is the target latency and w 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 α 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} and expansion ratios {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).
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).
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.
Architecture
Top-1
GPU latency
CPU latency
Mobile latency
ProxylessNAS (GPU)
75.1%
5.1ms
204.9ms
124ms
ProxylessNAS (CPU)
75.3%
7.4ms
138.7ms
116ms
ProxylessNAS (mobile)
74.6%
7.2ms
164.1ms
78ms
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 (for Proxyless-R, the target latency T and the coefficient w) 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.
Yes (per each of 7 blocks; layers repeat within a block)
Measured on device
ProxylessNAS
Binary gates trained with gradients or REINFORCE
One or two paths
Yes
Yes (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(α), 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 p, so only one or two paths run at a time. In exchange, the gradient of α 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). Since pj is a function of α, this expectation is differentiable with respect to α. The predicted values F(oj) 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.