SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2303.15446 · ICCV · 2023

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

Ming-Hsuan Yang, Abdelrahman Shaker, Salman Khan, Hanoona Rasheed, Muhammad Maaz, Fahad Shahbaz Khan

arXiv · PDF · Open in the Atlas

Code that ran

4 of 5 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (1 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 4 have no contract verdict; 0 failures of our instrument; 1 no recorded run), measured 2026-11-23; repository links from the Papers with Code archive attributed under CC BY-SA, no affiliation; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2303.15446.json · badge: /api/ran/2303.15446.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
amshaker/swiftformer marked official in Papers with Code
Papers with Code archive
3 ran · 1 no recorded run
mmaaz60/EdgeNeXt community
Papers with Code archive
1 ran · 0 no recorded run
FunctionStatusWhere it lives
EfficientAdditiveAttnetion Ran
ran on a synthesized input
amshaker/swiftformer/models/swiftformer.py
code served (permissive licence) · get_code("89118f335469da66")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned Tensor, ndim 3, dtype family float, shape (2, 5, 3) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn
import einops

class EfficientAdditiveAttnetion(nn.Module):
    """
    Efficient Additive Attention module for SwiftFormer.
    Input: tensor in shape [B, N, D]
    Output: tensor in shape [B, N, D]
    """

    def __init__(self, in_dims=512, token_dim=256, num_heads=2):
        super().__init__()
        self.to_query = nn.Linear(in_dims, token_dim * num_heads)
        self.to_key = nn.Linear(in_dims, token_dim * num_heads)
        self.w_g = nn.Parameter(torch.randn(token_dim * num_heads, 1))
        self.scale_factor = token_dim ** (-0.5)
        self.Proj = nn.Linear(token_dim * num_heads, token_dim * num_heads)
        self.final = nn.Linear(token_dim * num_heads, token_dim)

    def forward(self, x):
        query = self.to_query(x)
        key = self.to_key(x)
        query = torch.nn.functional.normalize(query, dim=-1)
        key = torch.nn.functional.normalize(key, dim=-1)
        query_weight = query @ self.w_g
        A = query_weight * self.scale_factor
        A = torch.nn.functional.normalize(A, dim=1)
        G = torch.sum(A * query, dim=1)
        G = einops.repeat(G, 'b d -> b repeat d', repeat=key.shape[1])
        out = self.Proj(G * key) + query
        out = self.final(out)
        return out


INIT_ARGS = {
    'in_dims': 4,
    'token_dim': 3,
    'num_heads': 2,
}

ARGS = {
    'x': torch.randn(2, 5, 4),
}

if __name__ == '__main__':
    model = EfficientAdditiveAttnetion(**INIT_ARGS)
    output = model(**ARGS)
    print(f"Output shape: {output.shape}")
    print(f"Expected shape: (2, 5, 3)")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
einops, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 3, dtype family float, shape (2, 5, 3) — shape (2, 5, 3) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
Mlp Ran
ran on a synthesized input
amshaker/swiftformer/models/swiftformer.py
code served (permissive licence) · get_code("2dc33d1c31b0ba12")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned Tensor, ndim 4, dtype family float, shape (2, 4, 3, 5) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn
from timm.models.layers import DropPath, trunc_normal_

class Mlp(nn.Module):
    """
    Implementation of MLP layer with 1*1 convolutions.
    Input: tensor with shape [B, C, H, W]
    Output: tensor with shape [B, C, H, W]
    """

    def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0):
        super().__init__()
        out_features = out_features or in_features
        hidden_features = hidden_features or in_features
        self.norm1 = nn.BatchNorm2d(in_features)
        self.fc1 = nn.Conv2d(in_features, hidden_features, 1)
        self.act = act_layer()
        self.fc2 = nn.Conv2d(hidden_features, out_features, 1)
        self.drop = nn.Dropout(drop)
        self.apply(self._init_weights)

    def _init_weights(self, m):
        if isinstance(m, nn.Conv2d):
            trunc_normal_(m.weight, std=0.02)
            if m.bias is not None:
                nn.init.constant_(m.bias, 0)

    def forward(self, x):
        x = self.norm1(x)
        x = self.fc1(x)
        x = self.act(x)
        x = self.drop(x)
        x = self.fc2(x)
        x = self.drop(x)
        return x


INIT_ARGS = {
    'in_features': 4,
    'hidden_features': 8,
    'out_features': 4,
    'act_layer': nn.GELU,
    'drop': 0.1,
}

ARGS = {
    'x': torch.randn(2, 4, 3, 5),
}

if __name__ == '__main__':
    mlp = Mlp(**INIT_ARGS)
    mlp.eval()
    output = mlp(**ARGS)
    print(f"Input shape: {ARGS['x'].shape}")
    print(f"Output shape: {output.shape}")
    print("Success!")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
timm, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 4, dtype family float, shape (2, 4, 3, 5) — shape (2, 4, 3, 5) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
SDTAEncoder Ran
ran on a synthesized input · constructed an object; no result was computed
mmaaz60/EdgeNeXt/models/sdta_encoder.py
code served (permissive licence) · get_code("931f6c94679945e2")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, SDTAEncoder: the run constructed the object and did not call it, so no result was computed. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
from torch import nn
import math

torch.manual_seed(0)

ARGS = {
    "dim": 4,
    "drop_path": 0.1,
    "layer_scale_init_value": 1e-6,
    "expan_ratio": 4,
    "use_pos_emb": True,
    "num_heads": 2,
    "qkv_bias": True,
    "attn_drop": 0.0,
    "drop": 0.0,
    "scales": 2,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
timm, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type SDTAEncoder — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a SDTAEncoder output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
SwiftFormerLocalRepresentation Ran
ran on a synthesized input
amshaker/swiftformer/models/swiftformer.py
code served (permissive licence) · get_code("be926696e202a1ce")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned Tensor, ndim 4, dtype family float, shape (2, 4, 3, 5) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn
from timm.models.layers import DropPath, trunc_normal_

class SwiftFormerLocalRepresentation(nn.Module):
    """
    Local Representation module for SwiftFormer that is implemented by 3*3 depth-wise and point-wise convolutions.
    Input: tensor in shape [B, C, H, W]
    Output: tensor in shape [B, C, H, W]
    """

    def __init__(self, dim, kernel_size=3, drop_path=0.0, use_layer_scale=True):
        super().__init__()
        self.dwconv = nn.Conv2d(dim, dim, kernel_size=kernel_size, padding=kernel_size // 2, groups=dim)
        self.norm = nn.BatchNorm2d(dim)
        self.pwconv1 = nn.Conv2d(dim, dim, kernel_size=1)
        self.act = nn.GELU()
        self.pwconv2 = nn.Conv2d(dim, dim, kernel_size=1)
        self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
        self.use_layer_scale = use_layer_scale
        if use_layer_scale:
            self.layer_scale = nn.Parameter(torch.ones(dim).unsqueeze(-1).unsqueeze(-1), requires_grad=True)
        self.apply(self._init_weights)

    def _init_weights(self, m):
        if isinstance(m, nn.Conv2d):
            trunc_normal_(m.weight, std=0.02)
            if m.bias is not None:
                nn.init.constant_(m.bias, 0)

    def forward(self, x):
        input = x
        x = self.dwconv(x)
        x = self.norm(x)
        x = self.pwconv1(x)
        x = self.act(x)
        x = self.pwconv2(x)
        if self.use_layer_scale:
            x = input + self.drop_path(self.layer_scale * x)
        else:
            x = input + self.drop_path(x)
        return x


INIT_ARGS = {
    'dim': 4,
    'kernel_size': 3,
    'drop_path': 0.1,
    'use_layer_scale': True,
}

ARGS = {
    'x': torch.randn(2, 4, 3, 5),
}

if __name__ == '__main__':
    module = SwiftFormerLocalRepresentation(**INIT_ARGS)
    output = module(**ARGS)
    print(f"Input shape: {ARGS['x'].shape}")
    print(f"Output shape: {output.shape}")
    print("Success!")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
timm, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 4, dtype family float, shape (2, 4, 3, 5) — shape (2, 4, 3, 5) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
SwiftFormerEncoder Not yet run
unverified (harvested, no recorded run)
amshaker/swiftformer/models/swiftformer.py
code served (permissive licence) · get_code("02ce32529d3451dd")
How it ran

no invocation recorded.

Also present in other papers' code

Of 5 samples lifted from this paper's linked repositories, 5 carry a function identity and 0 do not. Of the 5 distinct functions with an identity, 1 are also present in other papers whose code we hold (1 with at least one paper dated earlier, 0 the same month, 0 later) and 4 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

FunctionAlso present inEarliest-datedOthers named
SDTAEncoder
brick of this paper's assembly: entry
1 other paper
1 dated earlier
2110.02178 (2021-10)
MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-23.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

Self-attention has become a defacto choice for capturing global context in various vision applications. However, its quadratic computational complexity with respect to image resolution limits its use in real-time applications, especially for deployment on resource-constrained mobile devices. Although hybrid approaches have been proposed to combine the advantages of convolutions and self-attention for a better speed-accuracy trade-off, the expensive matrix multiplication operations in self-attention remain a bottleneck. In this work, we introduce a novel efficient additive attention mechanism that effectively replaces the quadratic matrix multiplication operations with linear element-wise multiplications. Our design shows that the key-value interaction can be replaced with a linear layer without sacrificing any accuracy. Unlike previous state-of-the-art methods, our efficient formulation of self-attention enables its usage at all stages of the network. Using our proposed efficient additive attention, we build a series of models called "Swift-Former" which achieves state-of-the-art performance in terms of both accuracy and mobile inference speed. Our small variant achieves 78.5% top-1 ImageNet-1K accuracy with only 0.8 ms latency on iPhone 14, which is more accurate and 2× faster compared to MobileViT-v2. Our code and models: https://tinyurl.com/5ft8v46w

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("2303.15446")
get_code_for_paper("2303.15446")
have("2303.15446")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/2303.15446.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/2303.15446.svg)](https://syntology.ai/paper/2303.15446)

Connect an agent — have() is free.