AI Logic

Architectures

RepVGG

Updated:

Architecture of RepVGG. The left side shows the overall flow of RepVGG-A0 at inference (five stages of only 3×3 convolutions, global average pooling, and a fully connected layer). The upper right shows the training-time block (the sum of three branches, 3×3 convolution with BN, 1×1 convolution with BN, and a BN-only identity mapping, followed by ReLU) being reparameterized into the inference-time 3×3 convolution and ReLU. The lower right shows the 3×3 weights, the zero-padded 1×1 weights, and the identity with a 1 at the center being added into a single 3×3 kernel.

Background and overview

RepVGG is a convolutional neural network that uses a branched structure only during training, then converts the weights after training so that inference uses a VGG-style network with only 3×3 convolutions and ReLUs arranged in a single line. The paper calls this method of "converting weights to replace one structure with another" structural reparameterization. It was proposed in 2021 by Ding and colleagues at Tsinghua University and MEGVII and presented at CVPR 2021.

Branch-free (plain) networks such as VGG are simple to build and run fast. However, when made deeper they train poorly and lose in accuracy to branched architectures such as ResNet. On the other hand, structures such as ResNet's residual connections and GoogLeNet's concatenated branches help training but have the following drawbacks at inference.

  • Slower: each addition or concatenation of branch outputs increases memory reads and writes and makes computation harder to parallelize.
  • More memory: with residual connections, the block's input must be kept until the addition finishes, so the peak memory for feature maps is twice the input.
  • Harder to modify: the last layer of a residual block must output the same shape as its input, which makes operations such as channel pruning difficult.

RepVGG's idea is: "the benefits of branches are for training, and their drawbacks appear at inference. So use different structures for training and inference."

The main results of the paper are as follows.

  • On ImageNet, RepVGG-B3 reached 80.52% top-1 accuracy, the first plain architecture to exceed 80% (to the paper's knowledge).
  • On a 1080Ti GPU, RepVGG-A2 was 0.17 points more accurate than ResNet-50 and ran 83% faster. RepVGG-B1g4 was 0.37 points more accurate than ResNet-101 and 101% faster.

Theory: three training-time branches and structural reparameterization

A RepVGG block is the sum of three branches during training and a single 3×3 convolution at inference. The upper right of the figure at the top of the article shows the training-time and inference-time blocks.

Training-time block

For a block input xx, the outputs of the following three branches are summed and passed through ReLU.

  • 3×3 convolution + BN: an ordinary convolutional layer.
  • 1×1 convolution + BN: corresponds to the 1×11 \times 1 shortcut that ResNet uses when input and output shapes differ.
  • Identity + BN: passes the input through unchanged and applies only BN. It is attached only to layers whose input and output shapes match (stride 1 and the same number of channels).

As an equation, the output M(2)M^{(2)} is computed from the input M(1)M^{(1)} as follows (Eq. 1 of the paper; ∗* is convolution, W(3)W^{(3)} and W(1)W^{(1)} are the 3×3 and 1×1 weights, and μ,σ,γ,β\mu, \sigma, \gamma, \beta are BN's mean, standard deviation, scale, and shift).

M(2)=bn(M(1)∗W(3))+bn(M(1)∗W(1))+bn(M(1))M^{(2)} = \mathrm{bn}\bigl(M^{(1)} * W^{(3)}\bigr) + \mathrm{bn}\bigl(M^{(1)} * W^{(1)}\bigr) + \mathrm{bn}\bigl(M^{(1)}\bigr)

Each of the three branches has its own BN. This extends ResNet's residual connection y=x+f(x)y = x + f(x) to y=x+g(x)+f(x)y = x + g(x) + f(x).

Conversion to the inference-time form

After training, the three branches are merged into a single 3×3 convolution with the following steps (Section 3.3 of the paper). The lower right of the figure at the top of the article shows these steps.

  1. Fold BN into the preceding convolution: at inference, BN is a linear expression (x−μi) γi/σi+βi(x - \mu_i)\,\gamma_i / \sigma_i + \beta_i for each channel ii, so it can be absorbed into the weights and bias of the preceding convolution (Eq. 3 of the paper).
  2. Treat the identity as a 1×1 convolution: the identity is the same as a 1×1 convolution whose weight is the identity matrix. This lets step 1 apply to this branch as well.
  3. Pad the 1×1 weights to 3×3: surrounding the 1×1 weights with zeros gives 3×3 weights with a value only at the center.
  4. Add the three: adding the three 3×3 weights and the three biases yields a single 3×3 convolution.

The equation for step 1 is as follows. W′W' and b′b' are the weight and bias after folding in BN.

Wi,:,:,:′=γiσiWi,:,:,:,bi′=βi−μiγiσiW'_{i,:,:,:} = \frac{\gamma_i}{\sigma_i} W_{i,:,:,:}, \qquad b'_i = \beta_i - \frac{\mu_i \gamma_i}{\sigma_i}

Because both convolution and inference-time BN are linear, the sum gives exactly the same result. The conversion is done once after training and does not need to be recomputed at each inference.

For the conversion to hold, the 3×3 and 1×1 layers must have the same stride, and the 1×1 layer's padding must be one pixel less than the 3×3 layer's. With the common "padding 1 for the 3×3 layer", the 1×1 layer uses padding 0.

Why training becomes easier

The paper explains this with the view that ResNet can be seen as "an implicit ensemble of many shallow models". A ResNet block splits the flow into two paths, so nn blocks yield 2n2^n paths. A RepVGG block splits it into three, giving 3n3^n. For example, stage 4 of RepVGG-B0 has 2×315≈2.8×1072 \times 3^{15} \approx 2.8 \times 10^7 paths, far more than the same number of 3×3 convolutions arranged ResNet-style (28=2562^8 = 256 paths).

Having the same structure at inference does not mean the training-time behavior is the same. Training-time BN uses per-mini-batch means and variances, so it is not linear, and training with a single convolution in place of the three-branch block does not give the same result. In the paper, placing a single BN after the addition lowered accuracy from 75.14% to 73.52% (Table 7).

Overall architecture

At inference, RepVGG is a stack of only 3×3 convolutions and ReLUs arranged in five stages. The left side of the figure at the top of the article shows the flow of RepVGG-A0.

  • The first layer of each stage halves the height and width with stride 2. Unlike VGG, max pooling is not used (to keep the inference-time body to a single type of operation).
  • Global average pooling and a fully connected layer come at the end.

The number of layers per stage is determined by the following three guidelines (Section 3.4 of the paper).

  • Stage 1 has 1 layer: the resolution is large and time-consuming, so few layers are used.
  • Stage 5 has 1 layer: it has many channels, so a single layer keeps parameters down.
  • Stage 4 has the most layers: following ResNet and others, layers are concentrated in the 14×14 stage.

The widths scale the [64,128,256,512][64, 128, 256, 512] used in VGG and ResNet by a multiplier aa for stages 2–4 and bb for stage 5 (Table 2 of the paper).

StageOutput sizeRepVGG-ARepVGG-B
1112×1121×min⁡(64,64a)1 \times \min(64, 64a)1×min⁡(64,64a)1 \times \min(64, 64a)
256×562×64a2 \times 64a4×64a4 \times 64a
328×284×128a4 \times 128a6×128a6 \times 128a
414×1414×256a14 \times 256a16×256a16 \times 256a
57×71×512b1 \times 512b1×512b1 \times 512b

"2×64a2 \times 64a" means two layers with 64a64a channels. Varying aa and bb gives the following models (Table 3 of the paper).

ModelLayers per stageaabb
RepVGG-A01, 2, 4, 14, 10.752.5
RepVGG-A11, 2, 4, 14, 112.5
RepVGG-A21, 2, 4, 14, 11.52.75
RepVGG-B01, 4, 6, 16, 112.5
RepVGG-B11, 4, 6, 16, 124
RepVGG-B21, 4, 6, 16, 12.55
RepVGG-B31, 4, 6, 16, 135

To reduce computation further, the 3rd, 5th, 7th, … layers are made group convolutions (g2 and g4 mean 2 and 4 groups). Making two adjacent layers both group convolutions would stop information from mixing across channels, so every other layer is used.

Why only 3×3 convolutions

3×3 convolutions are especially well optimized in libraries such as cuDNN. In the paper's measurements (1080Ti), the computational throughput of 3×3 convolutions was about 4× that of 1×1, 5×5, and 7×7 (Table 1 of the paper). Stride-1 3×3 convolutions can also be accelerated with the Winograd algorithm, which cuts the number of multiplications to 4/9.

Experimental results

Comparison on ImageNet (120-epoch training with simple data augmentation. Speed is images per second on a 1080Ti with batch size 128 in FP32. Comparison models were retrained with the same settings. Excerpt from Table 4 of the paper)

ModelTop-1 accuracySpeed (images/s)ParametersComputation
RepVGG-A072.41%32568.30M1.4B
ResNet-1871.16%244211.68M1.8B
RepVGG-A174.46%233912.78M2.4B
ResNet-3474.17%141921.78M3.7B
RepVGG-A276.48%132225.49M5.1B
EfficientNet-B075.11%8295.26M0.4B
ResNet-5076.31%71925.53M3.9B
RepVGG-B178.37%68551.82M11.8B
RegNetX-3.2GF77.98%67115.26M3.2B
ResNet-10177.21%43044.49M7.6B
VGG-1672.21%415138.35M15.5B

Some RepVGG models have more computation than ResNet, but in actual speed they beat ResNets of similar accuracy. Compared with VGG-16, RepVGG-B2 has 58% of the parameters, runs 10% faster, and is 6.57 points more accurate.

Comparison with longer training (200 epochs with AutoAugment, Label Smoothing, and Mixup. Table 5 of the paper)

ModelTop-1 accuracySpeed (images/s)Parameters
RepVGG-B380.52%363110.96M
RegNetX-12GF80.55%27746.05M
EfficientNet-B379.31%22412.19M

Effect of the branches (RepVGG-B0, 120 epochs. The inference-time structure is identical in all cases. Tables 6 and 7 of the paper)

Training-time structureTop-1 accuracy
No branches (ordinary plain model)72.39%
1×1 branch only73.15%
Identity branch only74.79%
Both (RepVGG)75.14%
Remove BN from the identity branch74.18%
Single BN after the addition73.52%
Same number of layers arranged ResNet-style74.56%

Even with the same inference-time structure, the presence of training-time branches changed accuracy by 2.75 points. On the other hand, replacing all 3×3 convolutions in ResNet-50 with RepVGG blocks raised accuracy by only 0.03 points. The paper concludes that structural reparameterization is not a technique that helps everywhere, but a method that is important for training plain models.

Semantic segmentation (Cityscapes, replacing the backbone of PSPNet; excerpt from Table 8 of the paper): with RepVGG-B2 as the backbone, the mean IoU was 80.57%, exceeding ResNet-101's 78.51%.

Practical considerations

Keep the following points in mind when using RepVGG.

  • Convert only once, before inference: keep the three branches during training and convert after training finishes. Continuing to train the converted model loses the trainability that the branches provide.
  • Convert using BN in model.eval() mode: the conversion formulas assume inference-time BN, which uses the mean and variance accumulated during training.
  • Verify that the conversion is correct: before use, confirm that the outputs for the same input nearly match before and after conversion (within floating-point error).

RepVGG is designed for speed on GPUs and dedicated chips, and its parameter count is on the large side (25.49M for RepVGG-A2, 110.96M for B3). The paper also notes that MobileNet or ShuffleNet may be better suited to low-power devices. For smartphones, there is also MobileOne, which extends the same reparameterization idea to depthwise convolutions.

Because the structure is plain, post-processing such as channel pruning and quantization is also easier (Section 3.1 of the paper).

Comparison with other models

The following compares RepVGG with models of similar structure or purpose.

ModelInference-time structureTraining-time structureMain operationsSuited hardware
VGGPlainSame as inference3×3 convolution, max poolingGPU (but heavy)
ResNetResidual connectionsSame as inferenceBottleneck (1×1, 3×3)GPU, CPU
RepVGGPlainThree branches (3×3, 1×1, identity)3×3 convolution onlyGPU, dedicated chips
MobileOnePlainMultiple branches for both depthwise and pointwise convolutionsDepthwise convolution, 1×1 convolutionSmartphones
RegNetResidual connectionsSame as inferenceGroup-convolution bottleneckGPU

Guidelines for choosing:

  • For a simple, fast model on GPUs: RepVGG is a good fit. Its inference-time operations are only 3×3 convolutions and ReLUs, which also makes implementation and optimization easier.
  • To run on smartphones and similar devices: compare MobileOne and the MobileNet family, which have fewer parameters.
  • If switching structures between training and inference is too much work: choose ResNet or RegNet, which need no structural conversion.

PyTorch example

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

"""
A RepVGG block (a small implementation following Eqs. 1–4 of the paper).
During training, sum three branches (3×3 conv + BN, 1×1 conv + BN, BN only (identity)) and apply ReLU.
Calling reparameterize() after training replaces them with a single 3×3 convolution (with bias).
"""


def fuse_bn(kernel, bn):
    """Fold BN into the preceding convolution (Eq. 3): W' = γ/σ · W, b' = β − μγ/σ"""
    std = (bn.running_var + bn.eps).sqrt()
    t = (bn.weight / std).reshape(-1, 1, 1, 1)
    return kernel * t, bn.bias - bn.running_mean * bn.weight / std


class RepVGGBlock(nn.Module):
    def __init__(self, in_ch, out_ch, stride=1, groups=1):
        super().__init__()
        self.in_ch, self.groups = in_ch, groups
        self.conv3 = nn.Conv2d(in_ch, out_ch, 3, stride, padding=1, groups=groups, bias=False)
        self.bn3 = nn.BatchNorm2d(out_ch)
        self.conv1 = nn.Conv2d(in_ch, out_ch, 1, stride, padding=0, groups=groups, bias=False)  # padding is 1 less than the 3×3
        self.bn1 = nn.BatchNorm2d(out_ch)
        # identity branch only when input and output shapes match (stride 1, same channels)
        self.bn_id = nn.BatchNorm2d(in_ch) if (in_ch == out_ch and stride == 1) else None
        self.fused = None

    def forward(self, x):
        if self.fused is not None:                      # inference: one 3×3 convolution and ReLU
            return F.relu(self.fused(x))
        y = self.bn3(self.conv3(x)) + self.bn1(self.conv1(x))
        if self.bn_id is not None:
            y = y + self.bn_id(x)
        return F.relu(y)

    @torch.no_grad()
    def reparameterize(self):
        k3, b3 = fuse_bn(self.conv3.weight, self.bn3)
        k1, b1 = fuse_bn(self.conv1.weight, self.bn1)
        k = k3 + F.pad(k1, [1, 1, 1, 1])                # zero-pad the 1×1 weights into the center of a 3×3
        b = b3 + b1
        if self.bn_id is not None:
            # identity = convolution with an identity-matrix weight (1 only at the center for the same channel)
            per_group = self.in_ch // self.groups
            eye = torch.zeros_like(k3)
            for i in range(self.in_ch):
                eye[i, i % per_group, 1, 1] = 1.0
            kid, bid = fuse_bn(eye, self.bn_id)
            k, b = k + kid, b + bid
        c = self.conv3
        self.fused = nn.Conv2d(c.in_channels, c.out_channels, 3, c.stride, padding=1, groups=c.groups, bias=True)
        self.fused.weight.copy_(k)
        self.fused.bias.copy_(b)
        for name in ["conv3", "bn3", "conv1", "bn1", "bn_id"]:
            setattr(self, name, None)                  # discard the training-time branches


block = RepVGGBlock(16, 16)
block.train()
block(torch.randn(8, 16, 32, 32))                       # accumulate BN mean and variance by training (just once here)

block.eval()                                            # convert using inference-time BN (accumulated mean and variance)
x = torch.randn(2, 16, 32, 32)
with torch.no_grad():
    before = block(x)
    block.reparameterize()
    after = block(x)
print(torch.allclose(before, after, atol=1e-5))         # True: outputs match before and after conversion

FAQ

Q. Why do training and inference give the same result even though the structures differ?
A.

Because inference-time BN and convolution are both linear. BN can be folded into the weights and bias of the preceding convolution, the identity can be treated as a 1×1 convolution whose weight is the identity matrix, and a 1×1 convolution can be treated as a 3×3 convolution surrounded by zeros. A sum of linear maps is a single linear map, so the single 3×3 convolution obtained by adding the weights and biases of the three branches produces the same output as the original block.

Q. Then why not train with a single 3×3 convolution from the start?
A.

Even if inference is the same, training-time behavior is not. Training-time BN uses per-mini-batch statistics, so the form with a separate BN per branch cannot be expressed as a single convolution. In the paper, with the same inference-time structure, training without branches gave 72.39% accuracy, while training with the three branches gave 75.14% (RepVGG-B0).

Q. How do RepVGG and MobileOne differ?
A.

Both merge training-time branches into one at inference. RepVGG adds 1×1 and identity branches to an ordinary 3×3 convolution, targeting speed on GPUs. MobileOne adds branches to both the depthwise convolution and the 1×1 convolution of MobileNet, and further lines up kk branches of the same shape, targeting small models that run in under 1 millisecond on smartphones.

References

  1. Ding, X., Zhang, X., Ma, N., Han, J., Ding, G., & Sun, J. (2021). RepVGG: Making VGG-style ConvNets Great Again. CVPR 2021. arXiv:2101.03697.
  2. megvii-model/RepVGG: the official implementation (the repository listed in the paper)
  3. Veit, A., Wilber, M., & Belongie, S. (2016). Residual Networks Behave Like Ensembles of Relatively Shallow Networks. NIPS 2016. arXiv:1605.06431.