SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2412.04786 · NeurIPS · 2024

Slicing Vision Transformer for Flexible Inference

Huan Wang, Yun Fu, Xu Ma, Yitian Zhang, Derek Hu, Stephen Chen, Huseyin Coskun, Ke Ma

arXiv · PDF · Open in the Atlas

Code that ran

2 of 10 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (0 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 2 have no contract verdict; 0 failures of our instrument; 8 no recorded run), measured 2026-11-22; 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/2412.04786.json · badge: /api/ran/2412.04786.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
BeSpontaneous/Scala-pytorch marked official in Papers with Code
Papers with Code archive
2 ran · 8 no recorded run
FunctionStatusWhere it lives
Attention Ran
ran on a synthesized input
BeSpontaneous/Scala-pytorch/models_scala.py
code served (permissive licence) · get_code("7a9dd4ed0208fd2f")
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; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim 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

# INIT_ARGS for Attention.__init__
INIT_ARGS = {
    'smallest_ratio': 0.5,
    'largest_ratio': 1.0,
    'dim': 8,
    'num_heads': 2,
    'qkv_bias': True,
    'attn_drop': 0.1,
    'proj_drop': 0.1
}

# ARGS for Attention.forward
ARGS = {
    'x': torch.randn(2, 5, 8),  # (batch_size=2, num_tokens=5, dim=8)
    'ratio': 1.0  # Using largest_ratio for this call
}
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
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 — no output shape is stated: observe_signature.py observed this class with its constructor sizes canonicalised where it could, which the node does not record, so its shape is not stated as this setup block's
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)
PatchEmbed Ran
ran on a synthesized input
BeSpontaneous/Scala-pytorch/models_scala.py
code served (permissive licence) · get_code("8264b58dfb638456")
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, 16, 4) 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 trunc_normal_

from typing import Callable, List, Optional, Tuple, Union
from enum import Enum
import torch.nn.functional as F
from timm.models.layers import DropPath, trunc_normal_, lecun_normal_, to_2tuple

class Format(str, Enum):
    NCHW = 'NCHW'
    NHWC = 'NHWC'
    NCL = 'NCL'
    NLC = 'NLC'

def _assert(condition: bool, message: str):
    assert condition, message

def nchw_to(x, fmt: Format):
    if fmt == Format.NHWC:
        return x.permute(0, 2, 3, 1)
    elif fmt == Format.NLC:
        return x.flatten(2).transpose(1, 2)
    else:
        return x

class PatchEmbed(nn.Module):
    """ 2D Image to Patch Embedding
    """
    output_fmt: Format

    def __init__(self, smallest_ratio: float=0.25, largest_ratio: float=1.0, img_size: Optional[int]=224, patch_size: int=16, in_chans: int=3, embed_dim: int=768, norm_layer: Optional[Callable]=None, flatten: bool=True, output_fmt: Optional[str]=None, bias: bool=True, strict_img_size: bool=True):
        super().__init__()
        self.smallest_ratio = smallest_ratio
        self.largest_ratio = largest_ratio
        self.stride = patch_size
        self.patch_size = to_2tuple(patch_size)
        if img_size is not None:
            self.img_size = to_2tuple(img_size)
            self.grid_size = tuple([s // p for s, p in zip(self.img_size, self.patch_size)])
            self.num_patches = self.grid_size[0] * self.grid_size[1]
        else:
            self.img_size = None
            self.grid_size = None
            self.num_patches = None
        if output_fmt is not None:
            self.flatten = False
            self.output_fmt = Format(output_fmt)
        else:
            self.flatten = flatten
            self.output_fmt = Format.NCHW
        self.strict_img_size = strict_img_size
        self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias)
        self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
        self.norm_layer = norm_layer
        self.embed_dim = embed_dim

    def forward(self, x, ratio):
        embed_dim_channels = int(ratio * self.embed_dim)
        B, C, H, W = x.shape
        if self.img_size is not None:
            if self.strict_img_size:
                _assert(H == self.img_size[0], f"Input height ({H}) doesn't match model ({self.img_size[0]}).")
                _assert(W == self.img_size[1], f"Input width ({W}) doesn't match model ({self.img_size[1]}).")
            else:
                _assert(H % self.patch_size[0] == 0, f'Input height ({H}) should be divisible by patch size ({self.patch_size[0]}).')
                _assert(W % self.patch_size[1] == 0, f'Input width ({W}) should be divisible by patch size ({self.patch_size[1]}).')
        if ratio == self.smallest_ratio or ratio == self.largest_ratio:
            weight_proj = self.proj.weight[:embed_dim_channels, :, :, :]
            bias_proj = self.proj.bias[:embed_dim_channels]
        else:
            weight_proj = self.proj.weight[-embed_dim_channels:, :, :, :]
            bias_proj = self.proj.bias[-embed_dim_channels:]
        x = F.conv2d(x, weight_proj, bias_proj, self.stride)
        if self.flatten:
            x = x.flatten(2).transpose(1, 2)
        elif self.output_fmt != Format.NCHW:
            x = nchw_to(x, self.output_fmt)
        if self.norm_layer:
            if ratio == self.smallest_ratio or ratio == self.largest_ratio:
                weight_norm = self.norm.weight[:embed_dim_channels]
                bias_norm = self.norm.bias[:embed_dim_channels]
            else:
                weight_norm = self.norm.weight[-embed_dim_channels:]
                bias_norm = self.norm.bias[-embed_dim_channels:]
            x = F.layer_norm(x, [embed_dim_channels], weight_norm, bias_norm)
        else:
            x = self.norm(x)
        return x

INIT_ARGS = {
    'smallest_ratio': 0.25,
    'largest_ratio': 1.0,
    'img_size': 32,
    'patch_size': 8,
    'in_chans': 3,
    'embed_dim': 16,
    'norm_layer': nn.LayerNorm,
    'flatten': True,
    'output_fmt': None,
    'bias': True,
    'strict_img_size': True,
}

ARGS = {
    'x': torch.randn(2, 3, 32, 32),
    'ratio': 0.25,
}

if __name__ == '__main__':
    model = PatchEmbed(**INIT_ARGS)
    output = model(**ARGS)
    print(f"Output shape: {output.shape}")
    print(f"Output: {output}")
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 3, dtype family float, shape (2, 16, 4) — shape (2, 16, 4) 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)
Block Not yet run
unverified (harvested, no recorded run)
BeSpontaneous/Scala-pytorch/models_scala.py
code served (permissive licence) · get_code("3ab7a1aca590784e")
How it ran

no invocation recorded.

Format Not yet run
unverified (harvested, no recorded run)
BeSpontaneous/Scala-pytorch/models_scala.py
code served (permissive licence) · get_code("128790adb097edba")
How it ran

no invocation recorded.

LayerScale Not yet run
unverified (harvested, no recorded run)
BeSpontaneous/Scala-pytorch/models_scala.py
code served (permissive licence) · get_code("722ebc6a6b34ca4d")
How it ran

no invocation recorded.

Mlp Not yet run
unverified (harvested, no recorded run)
BeSpontaneous/Scala-pytorch/models_scala.py
code served (permissive licence) · get_code("3a08e0b2bc5ced4b")
How it ran

no invocation recorded.

VisionTransformer_scala Not yet run
unverified (harvested, no recorded run)
BeSpontaneous/Scala-pytorch/models_scala.py
code served (permissive licence) · get_code("9040806f1a5cf930")
How it ran

no invocation recorded.

_assert Not yet run
unverified (harvested, no recorded run)
BeSpontaneous/Scala-pytorch/models_scala.py
code served (permissive licence) · get_code("dcc5c2638565f2e5")
How it ran

no invocation recorded.

get_init_weights_vit Not yet run
unverified (harvested, no recorded run)
BeSpontaneous/Scala-pytorch/models_scala.py
code served (permissive licence) · get_code("ac707dd1c89e5865")
How it ran

no invocation recorded.

init_weights_vit_timm Not yet run
unverified (harvested, no recorded run)
BeSpontaneous/Scala-pytorch/models_scala.py
code served (permissive licence) · get_code("38a6c338916f95c8")
How it ran

no invocation recorded.

Also present in other papers' code

Of 10 samples lifted from this paper's linked repositories, 10 carry a function identity and 0 do not. Of the 10 distinct functions with an identity, 2 are also present in other papers whose code we hold (1 with at least one paper dated earlier, 0 the same month, 2 later) and 8 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
get_init_weights_vit
brick of this paper's assembly: helper
25 other papers
22 dated earlier, 3 later · 1 only as an assembly brick
2112.08654 (2021-12)
Learning to Prompt for Continual Learning
2207.12819 (2022-07)
S-Prompts Learning with Pre-trained Transformers: An Occam's Razor for Domain Incremental Learning
2210.08823 (2022-10)
Scaling & Shifting Your Features: A New Baseline for Efficient Model Tuning
and 22 more not named here
init_weights_vit_timm
brick of this paper's assembly: helper
1 other paper
1 later
2604.04420 (2026-04)
Is Prompt Selection Necessary for Task-Free Online Continual Learning?

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-22.

Repositories linked to this paper

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

Abstract

Vision Transformers (ViT) is known for its scalability. In this work, we target to scale down a ViT to fit in an environment with dynamic-changing resource constraints. We observe that smaller ViTs are intrinsically the sub-networks of a larger ViT with different widths. Thus, we propose a general framework, named Scala, to enable a single network to represent multiple smaller ViTs with flexible inference capability, which aligns with the inherent design of ViT to vary from widths. Concretely, Scala activates several subnets during training, introduces Isolated Activation to disentangle the smallest sub-network from other subnets, and leverages Scale Coordination to ensure each sub-network receives simplified, steady, and accurate learning objectives. Comprehensive empirical validations on different tasks demonstrate that with only one-shot training, Scala learns slimmable representation without modifying the original ViT structure and matches the performance of Separate Training. Compared with the prior art, Scala achieves an average improvement of 1.6% on ImageNet-1K with fewer parameters. Code is available at here.

For agents

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

get_harvested_code_for_paper("2412.04786")
get_code_for_paper("2412.04786")
have("2412.04786")

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

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

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

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

Connect an agent — have() is free.