Back to paper library
Paper notesarXiv 2022CVPR 2023

InternImage

Miracles by Brute Force?

Original paper

InternImage: Exploring Large-Scale Vision Foundation Models with Deformable Convolutions

Paper authors

Wenhai Wang · Jifeng Dai · Zhe Chen …

Show all 12 authors

Wenhai Wang · Jifeng Dai · Zhe Chen · Zhenhang Huang · Zhiqi Li · Xizhou Zhu · Xiaowei Hu · Tong Lu · Lewei Lu · Hongsheng Li · Xiaogang Wang · Yu Qiao

Publication
CVPR 2023Conference
First submitted to arXiv
arXiv:2211.05778
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{classiccnnsinternimage2022,
  title = {{InternImage: Exploring Large-Scale Vision Foundation Models with Deformable Convolutions}},
  author = {Wenhai Wang and Jifeng Dai and Zhe Chen and Zhenhang Huang and Zhiqi Li and Xizhou Zhu and Xiaowei Hu and Tong Lu and Lewei Lu and Hongsheng Li and Xiaogang Wang and Yu Qiao},
  year = {2022},
  eprint = {2211.05778},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2211.05778}
}
On this page

In 2022, vision models with more than a billion parameters were almost all Transformers. ViT-G has 1.8 billion parameters, SwinV2-G reached 3 billion, and BEiT-3 has 1.9 billion. On the convolutional side, the largest models, ConvNeXt-XL and RepLKNet-XL, both stopped at a little over 300 million. ConvNeXt proved that convolutions can still hold their own at ordinary sizes, but at the scale of a billion parameters and hundreds of millions of images, nobody had yet built a convolutional network that could rival ViT.

This paper comes from Shanghai AI Laboratory, SenseTime, Tsinghua University, Nanjing University, and CUHK. On the author list, Jifeng Dai and Xizhou Zhu are the first authors of the first and second versions of deformable convolution, respectively, and this time they bring out their own operator to build a backbone for large models.

Defining the Problem

Where Convolutions Fall Short

The authors first compare ordinary convolution with multi-head self-attention (MHSA) and pin down two differences.

The first is long-range dependence. Stack 3×3 convolutions layer upon layer, and the effective receptive field actually stays small; however deep the network gets, it struggles to see the whole image from the start the way ViT does.

The second is adaptive spatial aggregation. Self-attention weights change with the input, differing for every image and every position. Convolution weights are fixed once training is done, and they carry strong inductive biases such as locality and translation equivariance. Inductive biases let convolutional networks converge fast and get by with less data, but they also limit how well the networks can learn more general patterns from web-scale data.

Four-panel diagram comparing four core operators, each with a blue star in the middle for the query pixel. (a) Global attention: the whole image is covered with green cells of varying shades representing adaptive weights, marked as having long-range dependence and adaptive aggregation but not saving computation or memory. (b) Local attention: only a small patch of green cells to the upper left of the star, marked as lacking long-range dependence. (c) Large kernel: a large patch of gray cells representing fixed weights, marked as lacking adaptive aggregation. (d) The authors' dynamic sparse kernel: nine small green squares scattered around the star at varying distances, with all three items checked
Figure 1 from the paper, excerpted from page 1 of the v4 PDF, CC BY 4.0. Gray marks fixed weights, and green marks weights that change with the input.

Large kernels like RepLKNet and SLaK made up for the first item, but the second is still missing, since their weights are just as fixed after training. Deformable convolution has both. Each sampling point's offset lets it look near or far, and both the offsets and the modulation weights are computed from the input.

Why DCNv2 Can't Be Used As-Is

DCNv2's output at position p0p_0 can be written as

y(p0)=∑k=1Kwk mk x ⁣(p0+pk+Δpk),y(p_0)=\sum_{k=1}^{K} w_k\, m_k\, x\!\left(p_0+p_k+\Delta p_k\right),

where KK is the number of sampling points, with K=9K=9 for 3×3. pkp_k is a grid position of ordinary convolution, Δpk\Delta p_k is the learned offset, mkm_k is the modulation weight after a sigmoid, and wkw_k is the projection weight of the kk-th sampling point, of size C×CC\times C.

The catch is that DCNv2 is usually used as an add-on, loading weights pretrained with ordinary convolution and then switching to deformable convolution for fine-tuning. For training a billion-parameter backbone from scratch, it has two flaws. Every sampling point has its own set of C×CC\times C weights, so parameter count and memory both grow with KK. And the sigmoid puts each mkm_k between 0 and 1, so the nine of them can add up to anything from 0 to 9; once the model is big and the data plentiful, gradients become unstable.

Solving the Problem

DCNv3's Three Changes

First, sampling points share weights. Borrowing the idea of separable convolution, wkw_k is split in two. The position-dependent part is handed to the modulation weight mkm_k, which plays the role of depthwise; the position-independent projection ww is shared by all sampling points, which plays the role of pointwise. Nine sets of C×CC\times C weights shrink to one.

Second, grouping. Following multi-head attention, the channels are split into GG groups, each with its own offsets and modulation weights, so different groups in the same layer can look at different places.

Third, softmax for the modulation weights. A sigmoid is computed for each point on its own; switching to one softmax over all nine points fixes their sum at 1.

Put together, this is DCNv3:

y(p0)=∑g=1G∑k=1Kwg mgk xg ⁣(p0+pk+Δpgk),y(p_0)=\sum_{g=1}^{G}\sum_{k=1}^{K} w_g\, m_{gk}\, x_g\!\left(p_0+p_k+\Delta p_{gk}\right),

where xgx_g is the gg-th group of channels, each group having C′=C/GC' = C/G channels, and mgkm_{gk} goes through a softmax along KK.

The offsets are fractional, so sampling positions usually land between pixels, and the values have to be fetched with bilinear interpolation. Let's write the simplest version with PyTorch's grid_sample, leaving out the final shared projection for now:

Python
import torch
import torch.nn.functional as F

def dcnv3_core(x, offset, logits, G):
    # x: (C, H, W); offset: (G, 9, 2, H, W), in pixels; logits: (G, 9, H, W)
    C, H, W = x.shape
    m = logits.softmax(dim=1)                                  # each group's 9 sampling-point weights sum to 1
    ys, xs = torch.meshgrid(torch.arange(H), torch.arange(W), indexing="ij")
    grid = [(dy, dx) for dy in (-1, 0, 1) for dx in (-1, 0, 1)]  # the 3×3 base positions p_k
    out = torch.zeros_like(x)
    for g, xg in enumerate(x.split(C // G)):                   # each group has its own offsets and weights
        for k, (dy, dx) in enumerate(grid):
            py = ys + dy + offset[g, k, 0]                     # p0 + p_k + Δp
            px = xs + dx + offset[g, k, 1]
            pos = torch.stack([px / (W - 1) * 2 - 1, py / (H - 1) * 2 - 1], -1)
            v = F.grid_sample(xg[None], pos[None], align_corners=True)[0]   # fetch values by bilinear interpolation
            out[g * (C // G):(g + 1) * (C // G)] += m[g, k] * v
    return out                                                 # followed by a linear projection shared by all sampling points

torch.manual_seed(0)
C, H, W, G = 8, 16, 16, 2
x = torch.randn(C, H, W)

# All offsets 0 and all weights equal: reduces to a 3×3 average
zero_off, flat = torch.zeros(G, 9, 2, H, W), torch.zeros(G, 9, H, W)
out = dcnv3_core(x, zero_off, flat, G)
print("With offsets at 0, max difference from 3×3 average pooling:", f"{(out - F.avg_pool2d(x, 3, 1, 1)).abs().max():.1e}")

# Move all 9 points of group 0 down by 5 cells: the 3×3 kernel sees 5 cells away
off = zero_off.clone()
off[0, :, 0] = 5.0
out = dcnv3_core(x, off, flat, G)
ref = F.avg_pool2d(x, 3, 1, 1)
print("After moving group 0 down 5 cells, max difference from the average 5 cells below:", f"{(out[:4, :-5] - ref[:4, 5:]).abs().max():.1e}")
print("Group 1 unaffected, max difference:", f"{(out[4:] - ref[4:]).abs().max():.1e}")
Code
With offsets at 0, max difference from 3×3 average pooling: 2.4e-07
After moving group 0 down 5 cells, max difference from the average 5 cells below: 1.8e-07
Group 1 unaffected, max difference: 2.4e-07

When the offsets are 0 and the softmax weights are uniform, DCNv3 is just a 3×3 average. Once the offsets move, the same nine sampling points can reach 5 cells away, and only that group moves along. In the actual model, both the offsets and the modulation weights are computed from the input by a 3×3 depthwise convolution followed by a linear layer, so they differ at every position. The official code also includes a pure PyTorch version, whose comments state it's meant only for debugging and testing; training uses the CUDA operator.

The softmax term looks like a minor tweak. Sigmoid weights are independent of one another, so the sum over the nine sampling points can differ by more than twentyfold from one position to another, which amounts to multiplying each position's output by a different factor. The softmax sum is always 1. The ablation later on will show how much this one change matters.

Stacking It into a Network

With the operator in hand, the next question is how to build a network out of it.

InternImage architecture diagram. On the left is the backbone: a photo of a red panda goes in, passes through the stem, then stages 1 to 4 in order, connected by downsampling layers, with the feature map shrinking from H/4×W/4 to H/32×W/32 before feeding classification, detection, segmentation, and other tasks. Three boxes on the right spell out that the stem is two stride-2 3×3 convolutions with LN and GELU, and that downsampling is a stride-2 3×3 convolution with LN; the basic block of stage i consists of DCNv3, LN, FFN, and LN with two residual connections, with the offset Δp and modulation weight m marked beside DCNv3; the four stacking rules are listed at the bottom
Figure 3 from the paper, excerpted from page 4 of the v4 PDF, CC BY 4.0.

The basic block looks a lot like a Transformer's. DCNv3 takes the place of self-attention, followed by an FFN with GELU, and the outputs of both branches go through LN before being added to the residual. The stem and downsampling layers stay with the convolutional-network style; the stem is two stride-2 3×3 convolutions, and downsampling is a single stride-2 3×3 convolution.

Each of the four stages has a channel count CiC_i, a group count GiG_i, and a block count LiL_i, which makes 12 hyperparameters in total, too many to tune. The authors use four rules to bring them down to 4:

  1. Ci=2i−1C1C_i = 2^{i-1} C_1, so the channel count doubles at each stage.
  2. Gi=Ci/C′G_i = C_i / C', so the number of channels per group, C′C', is fixed.
  3. L1=L2=L4L_1 = L_2 = L_4.
  4. L1≤L3L_1 \le L_3, so the third stage is the deepest.

The last two give the “AABA” stacking of ConvNeXt and Swin. That leaves four numbers, C1C_1, C′C', L1L_1, and L3L_3. The authors searched 30 combinations around 30 million parameters and picked (64,16,4,18)(64, 16, 4, 18) as InternImage-T.

To scale up further, the authors follow EfficientNet's compound scaling, multiplying depth by αϕ\alpha^{\phi} and width by βϕ\beta^{\phi} under the constraint αβ1.99≈2\alpha\beta^{1.99}\approx 2, and find experimentally that α=1.09\alpha = 1.09 and β=1.36\beta = 1.36 work best. The result is six sizes:

Table: Excerpted from Table 1 of the paper.
ModelC1C_1C′C'Blocks per stageParameters
InternImage-T64164, 4, 18, 430M
InternImage-S80164, 4, 21, 450M
InternImage-B112164, 4, 21, 497M
InternImage-L160165, 5, 22, 5223M
InternImage-XL192165, 5, 24, 5335M
InternImage-H320326, 6, 32, 61.08B

T through XL are sized to match ConvNeXt for easy comparison; H was built separately to reach a billion parameters.

Discussion

ImageNet

First, the ordinary sizes. T, S, and B are trained on ImageNet-1K alone for 300 epochs, with 224×224 input:

Table: Some columns excerpted from Table 2 of the paper. Models in the same row have similar parameter counts and FLOPs.
SizeSwinConvNeXtSLaKHorNetInternImage
T (about 30M)81.3%82.1%82.5%83.0%83.5%
S (about 50M)83.0%83.1%83.8%84.0%84.2%
B (about 90M)83.5%83.8%84.0%84.3%84.9%

At the same size, InternImage is highest in every row. T is 1.4 percentage points above ConvNeXt-T, and B is 1.1 higher.

Now the large models. XL is first pretrained on ImageNet-22K and reaches 88.0%. H is trained with M3I pretraining on 427 million public images from LAION-400M, YFCC-15M, and CC12M, and reaches 89.6% in the end with 640×640 input. The strongest ViTs and hybrid architectures sit at about 90.5% to 90.9%, using non-public data such as JFT, a gap of about 1 percentage point.

Detection and Segmentation

The gaps on downstream tasks are bigger than on classification. On COCO with Mask R-CNN trained for 12 epochs, InternImage-T reaches 47.2 box AP, against 42.7 for Swin-T and 44.2 for ConvNeXt-T, ahead by 4.5 and 3.0 respectively. With Cascade Mask R-CNN and 36 epochs of multi-scale training, XL gets 56.2 and ConvNeXt-XL 55.2. For ADE20K semantic segmentation with UperNet, InternImage-B gets 50.8 mIoU, against 49.1 for ConvNeXt-B, 49.9 for RepLKNet-31B, and 50.2 for SLaK-B.

The paper's most quoted number is 65.4 box AP on COCO test-dev, 1.2 above the previous best, FD-SwinV2-G, with 27% fewer parameters. A lot is stacked behind that number. The backbone is InternImage-H, first pretrained on 427 million images. A composite-backbone technique then doubles its parameters to 2.18 billion. The detector is DINO, trained first on Objects365 for 26 epochs and then on COCO for 12. The 62.9 mIoU on ADE20K is likewise H paired with Mask2Former, plus multi-scale testing. Every trick that could be stacked was stacked, so these numbers read more like a demonstration that this backbone can handle large-scale training.

Ablation: The Softmax Change

Removing DCNv3's three changes one at a time, compared on InternImage-T:

Table: Excerpted from Table 6 of the paper. COCO uses Mask R-CNN trained for 12 epochs.
SettingImageNet top-1COCO box APCOCO mask AP
Full DCNv383.5%47.242.5
No weight sharing83.6%47.442.6
No grouping82.3%43.840.0
Sigmoid instead of softmax65.7%38.735.6

Sharing weights barely affects accuracy, but the version without it has 66.1% more parameters. Scaled up to H, weight sharing saves 42.0% of the parameters and 84.2% of GPU memory; this change is there so the model can be made big.

Removing grouping drops ImageNet by 1.2 and COCO by 3.4, so detection takes the bigger hit.

Switching softmax back to sigmoid sends ImageNet straight down to 65.7%, a loss of nearly 18 percentage points. Here is where the varying sums discussed earlier show their effect.

The authors also tried larger sampling grids than 3×3. 5×5 gets 83.6%, with parameters rising from 30M to 37M; 7×7 actually drops to 82.8%, with 48M parameters. The sampling points move on their own, so 3×3 is enough.

Four copies of the same photo of a flock of sheep, labeled stage 1 to stage 4, with a blue star fixed on a sheep on the left. In stages 1 and 2, the colored sampling points crowd around the star, with zoomed-in boxes beside them; in stages 3 and 4, the sampling points spread across the whole photo, landing on other sheep and on the grass, with different colors representing different groups
Figure 5 from the paper, excerpted from page 8 of the v4 PDF, CC BY 4.0. The blue star is the query point, and different colors are the sampling locations of different groups.

The distribution of sampling points has layers to it too. In the first two stages they crowd near the query point, looking locally; by the third and fourth stages they spread across the whole image. That's very different from ViT, which is global from the first layer.

The Cost

The biggest cost is speed. In the appendix, the authors measured throughput on a single A100, with batch size 256 for 224×224 and batch size 2 for 800×800:

Table: Excerpted from Table 11 of the paper.
ModelImageNet top-1224×224 (images/s)800×800 (images/s)
ConvNeXt-B83.8%88158
RepLKNet-B83.5%88421
DAT-B84.0%66124
InternImage-B (DCNv2)—31116
InternImage-B84.9%77554

With DCNv3, throughput is 2.5 to 3.4 times that of the DCNv2 version. It's still a bit slower than ConvNeXt-B, 12% lower at 224 and 7% lower at 800. At high resolution, though, it's 2.5 times RepLKNet-B, since large kernels struggle on big images. In their conclusion, the authors also acknowledge that the latency of DCN-style operators remains a problem for downstream tasks that demand speed.

Another experiment varies the amount of data. The authors uniformly sampled 1%, 10%, and all of ImageNet-1K, and trained on each for 300 epochs:

Table: Excerpted from Table 12 of the paper.
Model1%10%100%
ResNet-5012.2%57.5%80.4%
ConvNeXt-T8.4%52.6%82.1%
Swin-TFailed12.1%81.3%
InternImage-T5.9%56.0%83.5%

The authors say InternImage-T is robust on both 1% and 10% of the data. In the 1% column, however, it loses to ResNet-50 and ConvNeXt-T and beats only Swin-T, which failed to train at all; at 10% it still loses to ResNet-50. It does cope with small amounts of data better than Swin-T. When the data shrinks to just 1%, though, ResNet-50 and ConvNeXt-T, with their stronger inductive biases, still come out ahead.

Conclusion

Those record-breaking numbers really were won by brute force. It took 427 million images, a composite backbone with doubled parameters, Objects365 pretraining, and DINO on top to get COCO's 65.4.

But bring the size back down to ordinary scales, with parameters and FLOPs matched to ConvNeXt, and InternImage is still more than 1 percentage point ahead on ImageNet and 1.8 to 3.0 ahead in COCO box AP. Here there's no brute force to lean on; the credit goes to DCNv3 itself.

If you want to run it yourself, you'll first have to get on good terms with that custom CUDA operator. At every checkpoint, whether compiling, deploying, or exporting to TensorRT, it's the first thing you have to get past.

One last little aside. In this paper's ablation, switching softmax back to sigmoid makes accuracy crash from 83.5% to 65.7%. A little over a year later, much the same group released DCNv4, and one of its two main changes was dropping the softmax entirely, which even made it converge faster.

The shelf life of a paper's key design is sometimes just a year.