AI Logic

Model Compression

Once-for-All

Updated:

How Once-for-All works. The left side shows the flow from training the largest network, through progressive shrinking that adds selectable values in the order kernel, depth, width, to the Once-for-All network, from which a specialized subnetwork is searched and extracted for each device and latency constraint. The right side shows the three ways of shrinking: cropping the center of the kernel, keeping the first D layers, and keeping the most important channels first.

Background and Overview

Once-for-All (OFA) is a method that trains a large network with variable depth, width, kernel size, and input resolution just once, and then extracts small subnetworks that fit a given device or speed constraint without retraining. It was proposed in 2019 by Cai, Gan, Wang, Zhang, and Han at MIT (ICLR 2020).

Even for the same app, the best network shape differs widely depending on the hardware it runs on, from the latest smartphones to phones several years old, cloud GPUs, and embedded devices. Before OFA, networks were either designed by hand for each device or found with neural architecture search (NAS), and each one was trained from scratch every time. With NN devices, the cost also grows NN-fold.

OFA solves this by decoupling training from search.

  • Training (only once): A single network containing many subnetworks is trained so that every subnetwork reaches the same accuracy as if it had been trained on its own.
  • Search (per device, no training): An accuracy predictor and a latency lookup table are used to find a subnetwork that meets the constraints, and its weights are extracted and used as they are.

This reduces the per-device design cost from O(N)O(N) to O(1)O(1). On ImageNet under mobile settings (fewer than 600M MACs), the paper reaches 80.0% top-1 accuracy and shows subnetworks that are up to 4.0 points more accurate than MobileNetV3, or 1.5× faster at the same accuracy (from the paper's abstract).

The key to making so many subnetworks coexist is a training procedure that extends from large to small in order (progressive shrinking). The paper positions this as a generalized form of pruning that shrinks even depth and kernel size.

Theory (Training Every Subnetwork in One Network)

Let WoW_o be the weights of the OFA network and archi\text{arch}_i a subnetwork architecture configuration. C(Wo,archi)C(W_o, \text{arch}_i) is the operation that selects the part of WoW_o corresponding to archi\text{arch}_i. The training objective is to minimize the validation loss of every subnetwork (Eq. (1) in the paper).

min⁡Wo∑archiLval(C(Wo,archi))\min_{W_o} \sum_{\text{arch}_i} \mathcal{L}_{\text{val}}\big(C(W_o, \text{arch}_i)\big)

The architecture space is the same as that of MobileNetV3: five units, each grouping layers with the same feature-map size. Four dimensions can vary.

DimensionChoices
Depth (layers per unit)2, 3, 4
Width (channel expansion ratio per layer)3, 4, 6
Kernel size (per layer)3, 5, 7
Input resolution128 to 224 (step of 4, 25 options)

There are about ((3×3)2+(3×3)3+(3×3)4)5≈2×1019\left((3 \times 3)^2 + (3 \times 3)^3 + (3 \times 3)^4\right)^5 \approx 2 \times 10^{19} combinations, each usable at 25 resolutions. Because all subnetworks share weights, only 7.7M parameters are stored in total.

Enumerating every subnetwork at each step to compute gradients is computationally infeasible. Sampling a few at random each step lets subnetworks that share weights interfere with one another, and accuracy drops sharply. OFA therefore uses progressive shrinking, which fixes the training order from large to small (left of the top figure).

  1. Train the largest network. All settings are at their maximum: kernel 7, depth 4, width 6.
  2. Make kernel size elastic. At each training step, one subnetwork with kernel sizes chosen from 7, 5, and 3 for each layer is sampled and trained.
  3. Make depth elastic. The choices are expanded in two stages, first to {4, 3} and then to {4, 3, 2}. Two subnetworks are sampled per step and their gradients are aggregated.
  4. Make width elastic. The choices are expanded first to {6, 4} and then to {6, 4, 3}. Gradients from four subnetworks are aggregated per step.

Input resolution is varied per batch by changing the image size throughout the whole training process. After the largest network is trained, a knowledge distillation loss that uses the largest network's outputs as soft labels is combined with the loss on the ground-truth labels. Even after smaller settings are added, the larger settings continue to be sampled and trained.

Extracting Smaller Subnetworks

Smaller subnetworks share the important parts of the larger subnetworks' weights (right of the top figure).

  • Kernel size: The center of a 7×7 kernel is used as the 5×5 kernel, and its center in turn as the 3×3 kernel. However, when the same weights play two roles, "part of a large kernel" and "a small kernel on its own", the desired value distributions differ and performance drops. So after cropping the center, a transformation matrix is applied (25×25 for 5×5, 9×9 for 3×3). The transformation matrices are separate for each layer and shared across channels, so the extra parameters are only 25×25+9×9=70625 \times 25 + 9 \times 9 = 706 per layer.
  • Depth: If a unit originally has NN layers, a subnetwork of depth DD keeps the first DD layers and skips the last N−DN - D layers. Which DD layers to use is not left free, so each depth corresponds to exactly one combination.
  • Width: Channels are reordered by the L1 norm of their weights in descending order (most important first), and subnetworks with smaller width use only the top channels. Reordering does not change the computation of the larger subnetworks, so accuracy is preserved while smaller subnetworks start from well-trained, important channels.

Progressive shrinking has two advantages. When smaller subnetworks are added, the larger ones are already well trained, so they are less disrupted by the smaller ones. Smaller subnetworks also start training from the important weights of the larger ones. It is like a cooking apprenticeship: first learn to make the full-course meal, then expand to simplified versions of the menu.

Searching for a Subnetwork per Device

After training, the most accurate subnetwork is searched for each device and constraint (such as latency). No training happens at this stage (Section 3.4 of the paper).

  1. Build an accuracy predictor. 16K subnetworks with different architectures and resolutions are sampled at random, and their accuracy is measured on 10K images held out from the training data. These pairs are used to train a three-layer fully connected network (400 units per layer) that predicts accuracy from the architecture. The prediction error (root mean squared error) was 0.21%.
  2. Build a latency lookup table. For each target device, a table of measured latencies per layer type is prepared and used to predict the latency of an architecture.
  3. Run evolutionary search. Using the predictor and the latency table, evolutionary search finds the subnetwork with the highest predicted accuracy that satisfies the latency constraint.
  4. Extract the weights and deploy. The weights of the chosen subnetwork are taken directly from the OFA network. If needed, a short fine-tuning can raise accuracy further.

Collecting data for the predictor takes 40 GPU hours, and this does not grow with the number of devices.

Experimental Results

Table 1 of the paper compares OFA with hardware-aware NAS methods on a Google Pixel1 smartphone (ImageNet top-1 accuracy). The cost is the total for N=40N = 40 devices.

MethodTop-1Compute (MACs)LatencyTotal cost (GPU hours)
MnasNet74.0%317M70ms1,600k
ProxylessNAS74.6%320M71ms20k
MobileNetV3-Large75.2%219M58ms7.2k
OFA (without progressive shrinking)72.4%235M59ms1.2k
OFA (with progressive shrinking)76.0%230M58ms1.2k
OFA (+ 75 epochs of fine-tuning)76.9%230M58ms4.2k
  • 0.8 points above MobileNetV3-Large without retraining: At about the same latency, it reached 76.0%.
  • Cost independent of the number of devices: With N=40N = 40, CO₂ emissions were 1/16 of ProxylessNAS and 1/1,300 of MnasNet. Training OFA itself takes about 1,200 GPU hours on V100s.
  • Progressive shrinking matters: Without progressive shrinking, accuracy was 72.4%, 3.6 points lower. Figure 7 also shows gains of 2.5 to 3.7 points for subnetworks in all eight configurations.
  • 80.0% under mobile settings: It reached 80.0% at 595M MACs, 0.2 points above EfficientNet-B2 with 1.68× less compute. At 143ms latency on the Pixel1 it reached 80.1%, running 2.6× faster than EfficientNet-B2.

The paper reports that retraining the architectures found by search from scratch did not reach OFA's accuracy. This suggests that not only the architecture but also the weights learned by OFA themselves contribute to accuracy.

Practical Considerations

  • The initial training is expensive. In addition to training the largest network (180 epochs on 32 GPUs), each stage of progressive shrinking requires training that totals several hundred epochs, about 1,200 GPU hours overall. With only a few devices or constraints, training a single model normally is cheaper.
  • The architecture space is fixed up front. Only architectures within the predefined ranges of depth, width, kernel, and resolution can be selected. The paper's space is based on the shape of MobileNetV3, so architectures of a completely different shape cannot be extracted.
  • Measure latency on real hardware. Even with few MACs, speed varies by device. The paper also builds a latency table for each target device.
  • Pretrained networks are publicly available. The authors have released the code and 50 pretrained models tailored to various devices and latencies.

Sampling subnetworks at random and training all of them together from the start makes subnetworks that share weights interfere with one another, and accuracy drops sharply ("without progressive shrinking" in Table 1 is 3.6 points lower). Follow the procedure of widening the selectable range in order from large to small.

Comparison with Other Methods

The following table compares methods that shrink a network to fit a device from the same viewpoints.

MethodDimensions shrunkNumber of resultsPer-device training
PruningWidth (weights, channels)OneRequired (fine-tuning after each shrink)
Hardware-aware NAS (ProxylessNAS, MnasNet, etc.)Whole architectureOne per searchRequired (search and training every time)
Weight-sharing NAS (ENAS, DARTS, etc.)Whole architectureOne per searchRequired (retrain the found architecture)
Once-for-AllDepth, width, kernel, resolutionAbout 2×10192 \times 10^{19}Not required (extract and use as is)

ENAS and similar methods also share weights, but their goal is to make search cheaper, and the found architecture is retrained from scratch. OFA differs in that the shared weights themselves become a finished product usable by every subnetwork. Compared with Slimmable Networks, which make only width variable with four options, OFA varies four dimensions and offers far more selectable configurations.

  • OFA is well suited when targeting many kinds of devices, or speed constraints that change with factors such as remaining battery.
  • If the only goal is to make one model lighter for a single fixed device, pruning, quantization, and knowledge distillation are simpler.
  • Subnetworks extracted with OFA can also be further combined with quantization.

PyTorch example

Show code
python
import random
import torch
import torch.nn as nn
import torch.nn.functional as F

# OFA's three ways of shrinking, written for one layer and one unit (Section 3.3 of the paper).

class ElasticDepthwiseConv(nn.Module):
    """Elastic kernel: use the center of 7x7 as 5x5 and 3x3, applying transformation matrices (Fig. 5, left)"""
    def __init__(self, channels, max_kernel=7):
        super().__init__()
        self.weight = nn.Parameter(torch.randn(channels, 1, max_kernel, max_kernel) * 0.1)
        # Per-layer transformation matrices (shared across channels): 25x25 + 9x9 = 706 extra parameters
        # Initialized to the identity (an example; the paper does not specify initialization)
        self.T5 = nn.Parameter(torch.eye(25))
        self.T3 = nn.Parameter(torch.eye(9))
        self.kernel = max_kernel

    def get_kernel(self, k):
        w = self.weight                                       # (C, 1, 7, 7)
        if k <= 5:
            w = w[:, :, 1:6, 1:6].reshape(-1, 25) @ self.T5   # apply the matrix to the center 5x5
            w = w.reshape(-1, 1, 5, 5)
        if k == 3:
            w = w[:, :, 1:4, 1:4].reshape(-1, 9) @ self.T3    # then the center 3x3
            w = w.reshape(-1, 1, 3, 3)
        return w

    def forward(self, x, active_channels=None):
        w = self.get_kernel(self.kernel)
        if active_channels is not None:
            w = w[:active_channels]                           # when width is reduced
        return F.conv2d(x, w, padding=self.kernel // 2, groups=w.shape[0])


class ElasticBlock(nn.Module):
    """1x1 expand -> depthwise conv -> 1x1 project (a simplified MobileNetV3-style layer)"""
    def __init__(self, c, max_expand=6):
        super().__init__()
        self.hidden = c * max_expand
        self.expand = nn.Conv2d(c, self.hidden, 1, bias=False)
        self.dw = ElasticDepthwiseConv(self.hidden)
        self.project = nn.Conv2d(self.hidden, c, 1, bias=False)
        self.expand_ratio, self.c = max_expand, c

    @torch.no_grad()
    def sort_channels(self):
        """Elastic width: reorder hidden channels by weight L1 norm, largest first (Fig. 6)"""
        # L1 norm of each channel's weights (as an example, measured on the 1x1 projection weights)
        importance = self.project.weight.abs().sum(dim=(0, 2, 3))
        idx = importance.argsort(descending=True)
        self.expand.weight.copy_(self.expand.weight[idx])
        self.dw.weight.copy_(self.dw.weight[idx])
        self.project.weight.copy_(self.project.weight[:, idx])     # reordering leaves the output unchanged

    def forward(self, x):
        n = self.c * self.expand_ratio                             # use only the top n channels
        h = F.conv2d(x, self.expand.weight[:n]).relu()
        h = self.dw(h, active_channels=n).relu()
        return x + F.conv2d(h, self.project.weight[:, :n])


class ElasticUnit(nn.Module):
    """Elastic depth: use only the first D layers and skip the rest (Fig. 5, right)"""
    def __init__(self, c, max_depth=4):
        super().__init__()
        self.blocks = nn.ModuleList(ElasticBlock(c) for _ in range(max_depth))
        self.depth = max_depth

    def forward(self, x):
        for block in self.blocks[: self.depth]:
            x = block(x)
        return x


def sample_subnet(unit, kernels, depths, ratios):
    unit.depth = random.choice(depths)
    for b in unit.blocks:
        b.dw.kernel = random.choice(kernels)
        b.expand_ratio = random.choice(ratios)


# Progressive shrinking: add selectable values in order from large to small (Appendix B)
unit = ElasticUnit(c=16)
opt = torch.optim.SGD(unit.parameters(), lr=0.01, momentum=0.9, nesterov=True)
stages = [
    dict(kernels=[7], depths=[4], ratios=[6], n_sub=1),           # largest network
    dict(kernels=[7, 5, 3], depths=[4], ratios=[6], n_sub=1),     # (1) elastic kernel
    dict(kernels=[7, 5, 3], depths=[4, 3, 2], ratios=[6], n_sub=2),   # (2) elastic depth
    dict(kernels=[7, 5, 3], depths=[4, 3, 2], ratios=[6, 4, 3], n_sub=4),  # (3) elastic width
]
for s in stages:
    if s["ratios"] != [6]:
        for b in unit.blocks:
            b.sort_channels()                                     # reorder before shrinking width
    for step in range(3):                                         # in practice, tens to over a hundred epochs
        x = torch.randn(2, 16, random.choice([16, 20, 24]), 24)   # resolution also varies per batch
        opt.zero_grad()
        for _ in range(s["n_sub"]):                               # aggregate gradients from several subnetworks
            sample_subnet(unit, s["kernels"], s["depths"], s["ratios"])
            unit(x).pow(2).mean().backward()                      # in practice: classification loss + distillation from the largest network
        opt.step()
print("Training procedure checked")

FAQ

Q. How does Once-for-All differ from ordinary NAS?
A.

Ordinary NAS searches for an architecture for each device or constraint and trains the found architecture from scratch. With NN devices, the cost is NN times as much. OFA trains a single network containing many subnetworks once at the start, then only runs a predictor-based search for each device and extracts the weights as they are. In the paper, CO₂ emissions for deploying to 40 kinds of devices were 1/16 of ProxylessNAS and 1/1,300 of MnasNet.

Q. Do extracted subnetworks need to be retrained?
A.

No. In the paper's Pixel1 experiment, it reached 76.0% top-1 accuracy without retraining, beating MobileNetV3-Large (75.2%). A short fine-tuning raises accuracy further, though (76.4% after 25 epochs, 76.9% after 75 epochs).

Q. Why can it be called a kind of pruning?
A.

Because the flow of training a large network first, keeping the important parts to make it smaller, and then fine-tuning is the same as pruning. The difference is that pruning shrinks only width (channels) to produce one model, whereas OFA also shrinks depth, kernel size, and resolution, and fine-tunes all subnetworks, large and small, together.

References

  1. H. Cai, C. Gan, T. Wang, Z. Zhang, and S. Han, "Once-for-All: Train One Network and Specialize it for Efficient Deployment," ICLR 2020, arXiv:1908.09791.
  2. mit-han-lab/once-for-all (official implementation and pretrained models by the paper's authors)