SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2106.00515 · 2021

KVT: k-NN Attention for Boosting Vision Transformers

arXiv · PDF · Open in the Atlas

Code that ran

3 of 4 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 0 have no contract verdict; 3 failures of our instrument; 1 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/2106.00515.json · badge: /api/ran/2106.00515.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
damo-cv/kvt canonical (classifier label)
classifier basis not recorded on the link
3 ran · 1 no recorded run
FunctionStatusWhere it lives
build_transform Ran
ran; our contract draft was wrong, not the code
damo-cv/kvt/datasets.py
code served (permissive licence) · get_code("3bc74137ab36aa79")
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 Compose. 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
import numpy as np
from torchvision import transforms

torch.manual_seed(0)

class ArgsConfig:
    def __init__(self):
        self.input_size = 224
        self.color_jitter = 0.4
        self.aa = "rand-m9-mstd0.5"
        self.train_interpolation = "bicubic"
        self.reprob = 0.25
        self.remode = "pixel"
        self.recount = 2

ARGS = {
    "is_train": True,
    "args": ArgsConfig()
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, timm, torch, torchvision — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Compose — a Compose output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a Compose 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
checkpoint_filter_fn Ran
ran; our contract draft was wrong, not the code
damo-cv/kvt/KNN_VisionTransformer.py
code served (permissive licence) · get_code("0b3795f9775ce118")
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 dict. 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
import torch.nn as nn
import math

torch.manual_seed(0)

# Build a minimal model that has the attributes accessed in checkpoint_filter_fn
class MinimalModel(nn.Module):
    def __init__(self):
        super().__init__()
        # patch_embed.proj needs to be a Conv2d with weight shape (O, I, H, W)
        self.patch_embed = nn.Module()
        self.patch_embed.proj = nn.Conv2d(3, 16, kernel_size=4, stride=4)
        
        # pos_embed needs to match the shape that will be checked
        # For a model with 64x64 input, 4x4 patches, we get 16x16 = 256 patches
        # Plus 1 for class token = 257 tokens, embed_dim=8
        self.pos_embed = torch.randn(1, 257, 8)

model = MinimalModel()

# Create a state_dict that will be processed
# Include a pos_embed with different shape to trigger resize_pos_embed
# Old pos_embed: 1 cls token + 100 grid tokens (10x10 grid) = 101 tokens, dim 8
old_pos_embed = torch.randn(1, 101, 8)

state_dict = {
    'pos_embed': old_pos_embed,
    'patch_embed.proj.weight': torch.randn(16, 3, 4, 4),
    'some_other_param': torch.randn(10, 10),
}

ARGS = {
    'state_dict': state_dict,
    'model': model,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type dict — a dict output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a dict 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
resize_pos_embed Ran
ran; our contract draft was wrong, not the code
damo-cv/kvt/KNN_VisionTransformer.py
code served (permissive licence) · get_code("109c74bc1997c975")
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 Tensor, ndim 3, dtype family float, shape (1, 10, 8) 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 math
import logging
import torch
import torch.nn.functional as F

torch.manual_seed(0)

# Setup logging
logging.basicConfig(level=logging.INFO)

# Create position embeddings
# posemb: [batch, num_tokens, embed_dim]
# The function expects:
# - posemb[:, :1] to be the token embedding (CLS token)
# - posemb[0, 1:] to be the grid embeddings
# For a 4x4 grid, we need 1 + 16 = 17 tokens
# Let's use a smaller grid: 2x2 = 4 grid tokens + 1 cls token = 5 total tokens

embed_dim = 8
old_grid_size = 2  # 2x2 grid
num_old_tokens = 1 + old_grid_size * old_grid_size  # 1 cls + 4 grid = 5
posemb = torch.randn(1, num_old_tokens, embed_dim)

# Create new position embedding with different grid size
# Let's resize to a 3x3 grid: 1 + 9 = 10 tokens
new_grid_size = 3  # 3x3 grid
num_new_tokens = 1 + new_grid_size * new_grid_size  # 1 cls + 9 grid = 10
posemb_new = torch.randn(1, num_new_tokens, embed_dim)

ARGS = {
    'posemb': posemb,
    'posemb_new': posemb_new,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
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, shape (1, 10, 8) — shape (1, 10, 8) 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: none by the harness; any seed is in the setup block
build_dataset Not yet run
unverified (harvested, no recorded run)
damo-cv/kvt/datasets.py
code served (permissive licence) · get_code("9153241c4331eb1a")
How it ran

no invocation recorded.

Also present in other papers' code

Of 4 samples lifted from this paper's linked repositories, 4 carry a function identity and 0 do not. Of the 4 distinct functions with an identity, 4 are also present in other papers whose code we hold (2 with at least one paper dated earlier, 2 the same month, 4 later) and 0 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
build_transform 37 other papers
2 dated earlier, 1 the same month, 34 later
2104.05707 (2021-04)
LocalViT: Analyzing Locality in Vision Transformers
2104.13840 (2021-04)
Twins: Revisiting the Design of Spatial Attention in Vision Transformers
2106.01401 (2021-06)
Container: Context Aggregation Network
and 34 more not named here
build_dataset 25 other papers
1 dated earlier, 1 the same month, 23 later
2104.05707 (2021-04)
LocalViT: Analyzing Locality in Vision Transformers
2106.01401 (2021-06)
Container: Context Aggregation Network
2108.01390 (2021-08)
Evo-ViT: Slow-Fast Token Evolution for Dynamic Vision Transformer
and 22 more not named here
resize_pos_embed 8 other papers
8 later
2107.00645 (2021-07)
Global Filter Networks for Image Classification
2108.01390 (2021-08)
Evo-ViT: Slow-Fast Token Evolution for Dynamic Vision Transformer
2112.05230 (2021-12)
Injecting Semantic Concepts into End-to-End Image Captioning
and 5 more not named here
checkpoint_filter_fn 7 other papers
7 later
2107.00645 (2021-07)
Global Filter Networks for Image Classification
2108.01390 (2021-08)
Evo-ViT: Slow-Fast Token Evolution for Dynamic Vision Transformer
2112.05230 (2021-12)
Injecting Semantic Concepts into End-to-End Image Captioning
and 4 more not named here

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

Convolutional Neural Networks (CNNs) have dominated computer vision for years, due to its ability in capturing locality and translation invariance. Recently, many vision transformer architectures have been proposed and they show promising performance. A key component in vision transformers is the fully-connected self-attention which is more powerful than CNNs in modelling long range dependencies. However, since the current dense self-attention uses all image patches (tokens) to compute attention matrix, it may neglect locality of images patches and involve noisy tokens (e.g., clutter background and occlusion), leading to a slow training process and potential degradation of performance. To address these problems, we propose the $k$-NN attention for boosting vision transformers. Specifically, instead of involving all the tokens for attention matrix calculation, we only select the top-$k$ similar tokens from the keys for each query to compute the attention map. The proposed $k$-NN attention naturally inherits the local bias of CNNs without introducing convolutional operations, as nearby tokens tend to be more similar than others. In addition, the $k$-NN attention allows for the exploration of long range correlation and at the same time filters out irrelevant tokens by choosing the most similar tokens from the entire image. Despite its simplicity, we verify, both theoretically and empirically, that $k$-NN attention is powerful in speeding up training and distilling noise from input tokens. Extensive experiments are conducted by using 11 different vision transformer architectures to verify that the proposed $k$-NN attention can work with any existing transformer architectures to improve its prediction performance. The codes are available at \url{https://github.com/damo-cv/KVT}.

For agents

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

get_harvested_code_for_paper("2106.00515")
get_code_for_paper("2106.00515")
have("2106.00515")

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

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

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

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

Connect an agent — have() is free.