wikillm

Paper · 2023-03-27 · cs.CV

SwiftFormer: Efficient Additive Attention for Transformer-based Real-time Mobile Vision Applications

SwiftFormer replaces the matrix products in self-attention with element-wise products over one pooled global query plus a linear layer, so cost grows linearly with tokens. It uses this block in all four stages of a hybrid CNN-transformer. Author-reported: 78.5% ImageNet-1K top-1 at 0.8 ms on iPhone 14 (SwiftFormer-S), and 83.0% at 1.9 ms (SwiftFormer-L3).

Efficient vision backbonesLinear attentionVision Transformer (ViT) backbonesKnowledge distillationvision-transformermobile-inferenceefficient-attentionimage-classificationobject-detectionsemantic-segmentation

arXivPDFCodeMarkdown15 min read

AI-compiled by claude-haiku-5-5 on 2026-11-05, not yet reviewed by a human. Every claim cites its source; check it when a detail matters.

In plain words

Transformer models let every patch of an image look at every other patch. That is powerful, but the work grows with the square of the number of patches, and the big matrix multiplications behind it are slow on a phone. Convolutional networks are fast on phones but see only a local neighbourhood at a time.

SwiftFormer keeps the "every patch can look at the whole image" idea but changes how it is computed. First it condenses all the queries into one summary vector for the image, using learned weights that decide how much each patch contributes. It then multiplies that summary element by element with the keys, which are the per-patch descriptors, and passes the result through one small linear layer. Only element-wise products and linear layers are needed, so the cost grows in a straight line with the number of patches instead of with its square.

The network uses this block in every stage, combined with cheap convolutions that handle local detail. The authors report that the resulting models are more accurate than comparable phone-oriented networks at similar speed on an iPhone, and that they also transfer to detection and segmentation.

TL;DR

  • Replaces the query-key matrix product of self-attention with a pooled global query, an element-wise product with keys, and a linear layer. Cost is linear in the number of tokens §3.2 eq. 4-6.
  • A hybrid network: a convolutional encoder plus this additive attention block, applied in all four stages §3.3 fig. 3.
  • Author-reported: SwiftFormer-S gives 78.5% ImageNet-1K top-1 at 0.8 ms on iPhone 14 (CoreML, Neural Engine) tab. 2.
  • Relevant if you need global context in a vision backbone on a phone-class device. The paper reports no positional encoding and no attention bias.

Problem

Self-attention costs O(n²·d) in the number of tokens n, which limits it on high-resolution inputs and on resource-constrained devices §3.1. Hybrid designs keep attention only in late, low-resolution stages §2. Earlier linear variants (transpose attention, separable attention, low-rank factorisation) still contain matrix products or explicit key-value interactions that the authors find slow on mobile hardware §2 §3.1 fig. 2. The paper argues that FLOP and parameter savings do not always become faster phone inference, so it optimises measured latency instead §2 §3.

Method

Attention variants compared §3.1 fig. 2 eq. 1-3. Standard self-attention is softmax(Q K^T / sqrt(d)) V eq. 1. Transpose attention (EdgeNeXt) applies attention across channels instead of tokens eq. 2. Separable attention (MobileViT-v2) computes a per-token context score from Q, a context vector from K weighted by those scores, and multiplies it element-wise with V eq. 3.

Efficient additive attention §3.2 fig. 2 (d). The method drops the key-value interaction entirely and keeps only query-key interaction, followed by a linear layer. Steps:

  1. Project tokens to queries and keys with two learned d × d matrices §3.2.
  2. Normalise the query matrix; call the result Q-hat eq. 6. The paper does not state the norm.
  3. Score each token with a learned vector w_a, scaled by 1/sqrt(d) eq. 4.
  4. Pool the queries with these scores into one global query vector q of size d eq. 5.
  5. Multiply the keys element-wise by q eq. 6.
  6. Apply a linear transform T to that product and add Q-hat; the output is Q-hat + T(K * q) eq. 6.

The paper states that this is linear in the token count and needs no key-value matrix product §3.2. It also states that no positional encoding or attention bias is used app. F.

Pseudocode
# Efficient additive attention  [§3.2] [eq. 4-6]
# Input:  x (B, N, d) token features
# Output: (B, N, d)
# Params: W_q, W_k (d, d); w_a (d,); T linear (d, d)

def efficient_additive_attention(x):
    # Query and key projections  [§3.2]
    queries = x @ W_q                                  # (B, N, d)
    keys = x @ W_k                                     # (B, N, d)

    # Normalised query matrix Q-hat; norm not named in the paper  [eq. 6]
    # The code also normalises keys (see "Paper vs code")
    queries = normalize(queries, dim=-1)               # (B, N, d)

    # One score per token from the query  [eq. 4]
    # Normalisation over tokens is not stated (see Pitfalls)
    scores = (queries @ w_a) / sqrt(d)                 # (B, N)
    weights = normalize(scores, dim=1)                 # (B, N)

    # Pool the queries into one global query per image  [eq. 5]
    global_query = sum(weights[..., None] * queries, dim=1)  # (B, d)

    # Element-wise query-key interaction  [eq. 6]
    interaction = keys * global_query[:, None, :]      # (B, N, d)
    # Linear transform T, plus the normalised query  [eq. 6]
    return queries + T(interaction)                    # (B, N, d)

Architecture §3.3 tab. 4 fig. 3. Four stages at strides 4, 8, 16 and 32. A patch embedding (two stride-2 3 × 3 convolutions) produces the stride-4 map. Between stages, a 3 × 3 stride-2 convolution downsamples and changes the width tab. 4. Each stage is a run of convolutional encoder blocks followed by one SwiftFormer encoder block as its last block §3.3 tab. 4. The stage layout for the four variants is below. Depths and widths are also in swiftformer.py.

Stage (output)BlockXSSL1L3
stem (H/4)two 3×3 stride-2 convs, final width C48484864
1 (H/4)C; conv blocks N_conv + 1 SwiftFormer encoder48; 2+148; 2+148; 3+164; 3+1
2 (H/8)C; conv blocks + 1 SwiftFormer encoder56; 2+164; 2+196; 2+1128; 3+1
3 (H/16)C; conv blocks + 1 SwiftFormer encoder112; 5+1168; 8+1192; 9+1320; 11+1
4 (H/32)C; conv blocks + 1 SwiftFormer encoder220; 3+1224; 5+1384; 4+1512; 5+1
GMACs / paramstab. 40.6G / 3.5M1.0G / 6.1M1.6G / 12.1M4.0G / 28.5M

The stem and downsampling widths in the table come from tab. 4. The per-stage block counts add up to the depths in swiftformer.py. The expansion ratio of 4 in the convolutional encoder is stated in app. A.

Convolutional encoder block §3.3 eq. 7. A 3 × 3 depth-wise convolution followed by BatchNorm, then a 1 × 1 convolution expanding to 4C, GELU, a 1 × 1 convolution back to C, and a skip connection eq. 7 app. A.

Pseudocode
# Convolutional encoder block  [§3.3] [eq. 7] [app. A]
# Input/Output: x (B, C, H, W); hidden width 4C
# The code also applies a per-channel layer scale (init 1); see Pitfalls

def conv_encoder(x):
    # 3x3 depth-wise conv, then BatchNorm  [eq. 7]
    y = batch_norm(depthwise_conv3x3(x))               # (B, C, H, W)
    # 1x1 conv to 4C, GELU, 1x1 conv back to C  [eq. 7] [app. A]
    y = conv1x1(gelu(conv1x1(y)))                      # (B, C, H, W)
    # Skip connection  [eq. 7]
    return x + y                                       # (B, C, H, W)

SwiftFormer encoder block §3.3 eq. 8. Local mixing, then efficient additive attention, then a linear block with two 1 × 1 convolutions, BatchNorm and GELU §3.3 eq. 8. The code version is shown here, because it differs from eq. 8 in the local mixing step (see Paper vs code).

Pseudocode
# SwiftFormer encoder block  [§3.3] [eq. 8]
# Input/Output: x (B, C, H, W)

def swiftformer_encoder(x):
    # Local representation: dw 3x3 conv, BN, 1x1 conv, GELU, 1x1 conv
    # Residual with layer scale init 1  [code: models/swiftformer.py#L211-L222]
    x = local_representation(x)                        # (B, C, H, W)
    # Efficient additive attention over the H*W tokens  [§3.2] [eq. 6]
    # Residual with layer scale init 1e-5  [code: models/swiftformer.py#L252-L265]
    tokens = flatten_to_tokens(x)                      # (B, H*W, C)
    x = x + layer_scale_1 * unflatten(efficient_additive_attention(tokens))
    # Linear block: BN, 1x1 conv to 4C, GELU, 1x1 conv back  [§3.3] [eq. 8]
    x = x + layer_scale_2 * mlp(x)                     # (B, C, H, W)
    return x

Training recipe for classification §4.1 app. B. Trained from scratch on ImageNet-1K for 300 epochs with AdamW, a cosine schedule and a linear warm-up over 5 epochs. Hard distillation from a RegNetY-16GF teacher. The full values are in the hyperparameter table below.

Hyperparameters

Values are from the paper unless marked as code. "not stated" means the paper does not give the value, so the code's value is shown separately.

NameValueWhereNotes
Training dataImageNet-1K§4.1
Epochs300§4.1 main.py
OptimizerAdamW§4.1code default adamw main.py
Learning rate1e-3 initial§4.1code default 2e-3 main.py; see Paper vs code
LR schedulecosine§4.1code default cosine main.py
Warm-uplinear, 5 epochs§4.1 main.pywarm-up LR 1e-6 in code main.py
Batch size2048 totalapp. B128 per GPU × 16 GPUs in released slurm script slurm_train.sh slurm_train.sh
Resolution224 × 224 train and test§4.1
Hardware8 × NVIDIA A100§4.1 app. Babout 36 h per classification run app. B
FrameworkPyTorch 1.12§4.1code pins torch 1.11.0 requirements.txt
Colour jitter0.4app. Bmain.py
RandAugmentmagnitude 9, std 0.5app. Bmain.py
Gradient clipping0.01app. Bcode clip mode agc (adaptive) main.py
Mixup"1" (percentage)app. Bcode default 0.8 main.py; see Paper vs code
CutMix"0.8" (percentage)app. Bcode default 1.0 main.py; see Paper vs code
Label smoothing0.1app. Bmain.py
Random erasingprobability 0.25app. Bmain.py
TeacherRegNetY-16GF, 82.9% top-1app. Bcode uses regnety_160 main.py
Distillationhardapp. Bmain.py
Distillation weightnot stated—code α = 0.5 main.py, loss at losses.py
Weight decaynot stated—code default 0.025 main.py
Model EMAnot stated—code on by default, decay 0.99996 main.py
Layer-scale initnot stated—code 1e-5 for encoder blocks swiftformer.py; 1 for conv blocks swiftformer.py
Attention headsnot stated—code uses 1 swiftformer.py
Expansion ratio (conv encoder)4app. A
Detection / instance seg.Mask R-CNN, COCO 2017§4.4118K train, 5K val images §4.4
Detection fine-tune12 epochs, 1333 × 800, batch 32, AdamW, LR 2e-4§4.4pre-trained ImageNet backbone; no training code in repo
Segmentationsemantic FPN, ADE20K§4.520K train, 2K val, 150 classes §4.5
Segmentation fine-tune512 × 512, 40K iterations, batch 32, AdamW, poly LR, initial LR 2e-4§4.5poly power and weight decay not stated; no training code in repo

Results

Author-reported. Setup: ImageNet-1K classification, top-1 accuracy with 224 × 224 input §4.1 §4.3. Latency is measured on an iPhone 14 Neural Engine (iOS 16), CoreML, batch size 1; throughput on an A100 at batch size 128 §4.1 tab. 2. The paper gives an error of less than ±0.1 ms for latency tab. 2.

Ablation on ImageNet-1K, built from EfficientFormer-L1 tab. 1 §4.2:

MethodLatency (ms, iPhone 14)Top-1 (%)
EfficientFormer-L1 (baseline)1.179.2
+ replace pool mixer by conv encoder1.179.9
+ replace self-attention by efficient additive attention1.079.7
+ SwiftFormer block in all stages (SwiftFormer-L1)1.180.9

The text notes that the additive attention alone costs 0.2 points of accuracy against the baseline, and that placing the block in all stages recovers accuracy at unchanged latency §4.2. Appendix C reports, without a table, that removing the key-value interaction gives about 10% lower latency and 0.4 points higher top-1 app. C.

Comparison on ImageNet-1K tab. 2 §4.3:

NetworkFamilyLatency, ms (lower is better)A100 img/s (higher)Size, M (lower)GMACs (lower)Uses NASImageNet top-1 % (higher)
MobileNet-v2 ×1.0ConvNet0.898893.50.3no71.8
MobileNet-v3-Large ×0.75ConvNet0.8109344.00.2yes73.3
EdgeViT-XXSHybrid1.759654.10.6no74.4
MobileViT-XSHybrid1.537072.30.7no74.8
SwiftFormer-XSHybrid0.760343.50.6no75.7
MobileNet-v2 ×1.4ConvNet0.974476.10.6no74.7
MobileNet-v3-LargeConvNet0.9103515.40.3yes75.1
EfficientNet-b0ConvNet1.385375.30.4yes77.1
DeiT-TTransformer3.858605.73.8no72.2
EdgeViT-XSHybrid2.748126.71.1no77.5
MobileViT-v2 ×1.0Hybrid1.732014.91.8no78.1
SwiftFormer-SHybrid0.850516.11.0no78.5
MobileFormer-508MHybrid3.0444314.00.5no79.3
PoolFormer-S12Pool1.2322712.01.8no77.2
EfficientFormer-L1Hybrid1.1504612.31.3yes79.2
MobileViT-v2 ×1.5Hybrid3.4235610.64.0no80.4
SwiftFormer-L1Hybrid1.1446912.11.6no80.9
ResNet-50ConvNet1.9483525.54.1no78.5
PoolFormer-S36Pool2.8111431.05.0no81.4
ConvNeXt-TConvNet2.5323528.64.5no82.1
DeiT-STransformer9.9299022.54.5no81.8
Swin-TTransformerNA263528.34.5no81.3
MobileViT-v2 ×2.0Hybrid5.0190618.57.5no81.2
EfficientFormer-L3Hybrid2.0269131.33.9yes82.4
SwiftFormer-L3Hybrid1.9289028.54.0no83.0

Bold rows are SwiftFormer variants. Swin-T latency is reported as NA tab. 2.

Dense prediction tab. 3 §4.4 §4.5: backbone-only comparison, with the backbone features passed to Mask R-CNN (COCO) or semantic FPN (ADE20K).

BackboneAP boxAP box 50AP box 75AP maskAP mask 50AP mask 75mIoU (%)
ResNet1834.054.036.731.251.032.732.9
PoolFormer-S1237.359.040.134.655.836.937.2
EfficientFormer-L137.960.341.035.457.337.338.9
SwiftFormer-L141.263.244.838.160.240.741.4
ResNet5038.058.641.434.455.136.736.7
PoolFormer-S2440.162.243.437.059.139.640.3
EfficientFormer-L341.463.944.738.161.040.443.5
SwiftFormer-L342.764.446.739.161.741.843.9

Headline claims in the text: SwiftFormer-S is 1.6 × faster than EfficientNet-b0 and 1.4 points more accurate §4.3; SwiftFormer-L3 is 2.6 × faster than MobileViT-v2 ×2.0 with 1.8 points more accuracy §4.3. These are the authors' comparisons on their own measurement setup.

Paper vs code

Code: repository Amshaker/SwiftFormer at commit 4aa6cd67527baae00390b58134fa8954e06c5431, Apache-2.0 LICENSE. Owner is the first author. The repo has classification training and evaluation only; the README says so and gives no detection or segmentation code README.md.

  • Query and key normalisation. Paper: only the query matrix is normalised, as Q-hat eq. 6. Code: both queries and keys are L2-normalised before use swiftformer.py.
  • Score normalisation. Paper: α = Q·w_a/sqrt(d), with no normalisation over tokens stated eq. 4. Code: scales by token_dim^-0.5 swiftformer.py, then L2-normalises the scores over the token axis swiftformer.py. Because the last step is scale-invariant, the 1/sqrt(d) factor has no effect on the output in the code.
  • Output layers. Paper: a single linear transform T in x̂ = Q-hat + T(K * q) eq. 6. Code: Proj on K * G, plus the query, then a further linear layer final on the sum swiftformer.py. Both layers have biases.
  • Local representation. Paper: first line of the encoder is X̂ = Conv1(DWConv_BN(X̂)), with one point-wise conv and no residual eq. 8. Code: depth-wise conv, BN, 1×1 conv, GELU, 1×1 conv, with layer scale and a residual swiftformer.py.
  • Stem. Paper: two stride-2 3×3 convolutions §3.3. Code: each convolution is followed by BN and ReLU swiftformer.py.
  • Convolutional encoder. Paper: no layer scale eq. 7. Code: a learnable per-channel layer scale, initialised to 1, multiplies the branch swiftformer.py swiftformer.py. Hidden width 4C matches the paper's expansion ratio swiftformer.py.
  • Layer scale, encoder block. Not stated in the paper. Code: initial value 1e-5 for both branches swiftformer.py swiftformer.py.
  • Heads. Not stated in the paper. Code: a single head swiftformer.py.
  • Architecture depths and widths. Match Table 4 for all four variants swiftformer.py tab. 4.
  • Mixup and CutMix. Paper: "percentages of 1 and 0.8, respectively" for Mixup and CutMix app. B. Code defaults: Mixup 0.8 main.py, CutMix 1.0 main.py. The two values appear swapped relative to the paper's order.
  • Augmentation per variant. Paper: one augmentation recipe for all models app. B. Released scripts: dist_train.sh disables RandAugment and Mixup/CutMix for XS, and Mixup/CutMix for S dist_train.sh dist_train.sh. The slurm script's note says the same slurm_train.sh.
  • Learning rate. Paper: initial 1e-3 §4.1. Code: default 2e-3 main.py. No script in the repo passes --lr.
  • Batch and GPUs. Paper: 8 × A100 with total batch 2048 §4.1 app. B. That implies 256 per GPU. Code: default 128 per GPU main.py. The slurm script requests 16 GPUs at 128 each, summing to 2048 slurm_train.sh slurm_train.sh slurm_train.sh. The dist script takes the GPU count as an argument dist_train.sh.
  • Weight decay, EMA, gradient-clip mode. Not stated in the paper. Code: weight decay 0.025 main.py, model EMA on with decay 0.99996 main.py, clip mode agc main.py.
  • Distillation. Paper: hard distillation app. B; weighting not stated. Code: loss = (1 − α)·CE(class head, labels) + α·CE(distillation head, teacher argmax) with α = 0.5 by default losses.py main.py.
  • Teacher. Paper: RegNetY-16GF with 82.9% top-1 app. B. Code: timm name regnety_160 with a DeiT-hosted checkpoint main.py. The two are assumed to be the same network; the weights were not checked against the 82.9% figure.
  • Evaluation. Not stated in the paper. Code: at test time the class and distillation head logits are averaged swiftformer.py.
  • Detection and segmentation. Paper: Mask R-CNN and semantic FPN settings §4.4 §4.5. Code: no training or evaluation code for these tasks in the clone; the only mention is a comment about mmdetection swiftformer.py. These results cannot be checked here.
  • Latency. Paper: iPhone 14 CoreML measurements tab. 2. Code: no latency or CoreML export script in the clone; the README points to the Xcode 14 benchmark tool README.md.
  • Ablations. Table 1 and the Appendix C numbers have no ablation code in the repo.

Pitfalls

  • Scale factor is a no-op in the code. The 1/sqrt(d) term in eq. 4 cancels against the token-wise L2 normalisation swiftformer.py. Keep it if you follow the paper literally; it changes nothing.
  • Token normalisation is unstated. The paper gives α without a normalisation or softmax eq. 4. The code uses an L2 normalisation over tokens. A softmax over tokens would be a different operation. Implement the code's version when you need the released weights to load and match.
  • Key normalisation is unstated. The paper normalises only the query. The code normalises the keys too swiftformer.py. Without it the released weights will not reproduce the reported behaviour.
  • Two output layers. The released model has an extra linear layer after the residual sum swiftformer.py. Plan the parameter count accordingly; the paper's eq. 6 does not show it.
  • Positional information. The discussion says no positional encoding or attention bias is used app. F. Spatial mixing comes from the depth-wise convolutions only.
  • Layer scales are load-bearing. The encoder's attention branch starts at 1e-5, so early training behaves almost like the identity swiftformer.py. A reimplementation without layer scale will train differently.
  • Stem normalisation. BN and ReLU inside the stem are not in the paper's text §3.3 swiftformer.py.
  • Recipe conflicts. The Mixup and CutMix values are swapped against the code defaults, and the released scripts disable some augmentations for XS and S. Use the scripts' values for those variants, and treat the paper's blanket recipe as the default case only.
  • Batch size and LR. The paper's recipe (2048, 1e-3) does not match the code defaults (128 per GPU, 2e-3). The effective batch depends on your GPU count; check the scaling before reproducing.
  • Latency is not throughput. The A100 throughput is measured at batch size 128 tab. 2. It does not transfer to batch-1 phone latency, and the phone numbers come from a CoreML/Neural Engine pipeline that is not in the repo.
  • Dense-task numbers are unverifiable here. The Mask R-CNN and semantic FPN training code is not in the repo; the settings in §4.4 and §4.5 come from the paper alone.
  • Compute. The paper reports about 36 h per classification run on 8 × A100 app. B. Hardware and cost for detection and segmentation are not stated.
  • Equation numbers above are counted from the LaTeX source in order; if they disagree with a rendered PDF, cite the section instead.

Lineage

  • Builds on: EfficientFormer, which provides the baseline, the training recipe and the teacher model §3.3 §4.1. Related: additive attention in NLP (Fastformer, arXiv:2108.09084), whose form uses three sequential steps with key-value interaction; this paper drops that key-value interaction §3.2.
  • Compared against: MobileViT-v2 (separable self-attention), MobileViT, EdgeViT, EdgeNeXt (transpose attention), PoolFormer, MobileNet-v2/v3, EfficientNet, DeiT, Swin and ConvNeXt tab. 2 §2.
  • Superseded by: not stated in this card's sources.

Source and license

Adapted from “SwiftFormer: Efficient Additive Attention for Transformer-based Real-time Mobile Vision Applications” by Abdelrahman Shaker, Muhammad Maaz, Hanoona Rasheed, Salman Khan, Ming-Hsuan Yang, Fahad Shahbaz Khan (arXiv:2303.15446), used under CC BY 4.0. Changes: condensed and restructured for implementation, with tables, equations and algorithms taken from the paper and its code, each cited to its source. Not affiliated with or endorsed by the authors. Code citations refer to https://github.com/Amshaker/SwiftFormer at commit 4aa6cd67527b (Apache-2.0). Any quoted code is shown under that license.