SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2406.11148 · 2024

Few-Shot Recognition via Stage-Wise Retrieval-Augmented Finetuning

arXiv · PDF · Open in the Atlas

Code that ran

6 of 7 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; 6 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/2406.11148.json · badge: /api/ran/2406.11148.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
tian1327/swat canonical (classifier label)
classifier basis: census
6 ran · 1 no recorded run
FunctionStatusWhere it lives
calculate_scores Ran
ran; our contract draft was wrong, not the code
tian1327/swat/testing.py
code served (permissive licence) · get_code("482ccec6fd43050d")
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 numpy as np

# Create a small confusion matrix for testing
# Using a 3x4 shape to have distinct dimensions (3 classes, but total predictions)
confusion_matrix = np.array([
    [8, 1, 1],
    [2, 7, 1],
    [1, 2, 9]
], dtype=np.float32)

ARGS = {
    'confusion_matrix': confusion_matrix
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy — 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
extract_mined_feats Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
tian1327/swat/retrieval/extract_mined_feature.py
code served (permissive licence) · get_code("2f7d382b8cb5b005")
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. The code mentions cuda, and the harness aliases cuda to the CPU for every sample; whether this run needed that is 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

torch.manual_seed(0)

# Define a minimal tokenizer that has a __call__ method
class MinimalTokenizer:
    def __call__(self, captions):
        # Return a mock tokenized output with a cuda() method and shape
        batch_size = len(captions) if isinstance(captions, list) else 1
        tokens = torch.zeros(batch_size, 5, dtype=torch.long)
        return tokens

# Define a minimal model with encode_text and encode_image methods
class MinimalCLIPModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.text_encoder = nn.Linear(5, 4)
        self.image_encoder = nn.Linear(3, 4)
    
    def encode_text(self, tokens):
        # tokens shape: (batch_size, 5)
        # Return normalized text features of shape (batch_size, 4)
        batch_size = tokens.shape[0]
        feats = torch.randn(batch_size, 4)
        return feats
    
    def encode_image(self, imgs):
        # imgs shape: (batch_size, 3)
        # Return normalized image features of shape (batch_size, 4)
        batch_size = imgs.shape[0]
        feats = torch.randn(batch_size, 4)
        return feats
    
    def eval(self):
        return super().eval()

# Create a minimal dataloader as a list of batches
# Each batch is (imgs, labels, file_path, captions)
dataloader = [
    (
        torch.randn(2, 3),  # imgs: 2 samples, 3 dims
        torch.tensor([0, 1]),  # labels: 2 samples
        ['file1.jpg', 'file2.jpg'],  # file_path
        ['caption1', 'caption2']  # captions
    ),
    (
        torch.randn(2, 3),  # imgs: 2 samples, 3 dims
        torch.tensor([1, 0]),  # labels: 2 samples
        ['file3.jpg', 'file4.jpg'],  # file_path
        ['caption3', 'caption4']  # captions
    )
]

# Create model and tokenizer
model = MinimalCLIPModel()
tokenizer = MinimalTokenizer()

ARGS = {
    'model': model,
    'dataloader': dataloader,
    'tokenizer': tokenizer
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, tqdm — 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
extract_mined_feats_batch Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
tian1327/swat/retrieval/extract_mined_feature.py
code served (permissive licence) · get_code("fdd19b3b01f3ecee")
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. The code mentions cuda, and the harness aliases cuda to the CPU for every sample; whether this run needed that is 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
from torch.utils.data import DataLoader
import tempfile

torch.manual_seed(0)

# Stand-in model that implements encode_text and encode_image
class MockCLIPModel(nn.Module):
    def __init__(self, embed_dim=4):
        super().__init__()
        self.embed_dim = embed_dim
        self.text_encoder = nn.Linear(10, embed_dim)
        self.image_encoder = nn.Linear(12, embed_dim)
    
    def encode_text(self, text_tokens):
        # text_tokens should be a tensor of shape [batch, seq_len]
        batch_size = text_tokens.shape[0]
        return self.text_encoder(text_tokens.float().mean(dim=1, keepdim=True).expand(batch_size, 10))
    
    def encode_image(self, images):
        # images should be a tensor of shape [batch, channels, height, width]
        batch_size = images.shape[0]
        return self.image_encoder(images.float().view(batch_size, -1)[:, :12])

# Stand-in tokenizer
class MockTokenizer:
    def __call__(self, captions):
        # Return a tensor of shape [batch_size, seq_len]
        batch_size = len(captions)
        seq_len = 10
        return torch.randint(0, 100, (batch_size, seq_len))

# Create mock data
def create_mock_batch():
    imgs = torch.randn(2, 3, 4, 4)  # batch_size=2, channels=3, height=4, width=4
    labels = torch.tensor([0, 1])  # batch_size=2
    file_path = ['path/to/img1.jpg', 'path/to/img2.jpg']
    captions = ['caption 1', 'caption 2']
    return (imgs, labels, file_path, captions)

# Create dataloader with 3 batches
mock_data = [create_mock_batch() for _ in range(3)]

# Create model and tokenizer
model = MockCLIPModel(embed_dim=4)

tokenizer = MockTokenizer()

# Create temporary directory
save_dir = tempfile.mkdtemp()

# Create dataloader
dataloader = DataLoader(mock_data, batch_size=2, shuffle=False)

ARGS = {
    'model': model,
    'dataloader': mock_data,  # Using mock_data directly as list instead of DataLoader
    'tokenizer': tokenizer,
    'save_dir': save_dir,
    'batch_size': 2
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, tqdm — 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
set_loss Ran
ran; our contract draft was wrong, not the code
tian1327/swat/utils/losses.py
code served (permissive licence) · get_code("b43abf2d3deaa330")
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 CrossEntropyLoss. The image it ran in was not recorded. The code mentions cuda, and the harness aliases cuda to the CPU for every sample; whether this run needed that is 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 numpy as np

torch.manual_seed(0)

class MockArgs:
    def __init__(self, loss_name='CE', fewshot_weight=1.0, focal_gamma=2, 
                 focal_alpha=1, cls_num_list=None):
        self.loss_name = loss_name
        self.fewshot_weight = fewshot_weight
        self.focal_gamma = focal_gamma
        self.focal_alpha = focal_alpha
        self.cls_num_list = cls_num_list if cls_num_list is not None else [10, 20, 30]
        self.loss = None

ARGS = {
    'args': MockArgs(
        loss_name='CE',
        fewshot_weight=1.0,
        focal_gamma=2,
        focal_alpha=1,
        cls_num_list=[10, 20, 30]
    )
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type CrossEntropyLoss — a CrossEntropyLoss output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a CrossEntropyLoss 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
validate_dataset Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
tian1327/swat/testing.py
code served (permissive licence) · get_code("d825b8ba56586c53")
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 tuple, ndim 1, dtype family float; no output shape is stated. The image it ran in was not recorded. The code mentions cuda, and the harness aliases cuda to the CPU for every sample; whether this run needed that is 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
import numpy as np
from unittest.mock import MagicMock

torch.manual_seed(0)

# Mock args object
class Args:
    def __init__(self):
        self.loss_name = 'CrossEntropyLoss'

args = Args()

# Small model with encode_image method
class TinyModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(4, 3)
    
    def encode_image(self, x):
        return self.linear(x)
    
    def forward(self, x, texts):
        logits = self.linear(x)
        return logits, None

model = TinyModel()

# Classifier head
class TinyClassifierHead(nn.Module):
    def __init__(self, num_classes=3):
        super().__init__()
        self.num_classes = num_classes
        self.linear = nn.Linear(3, num_classes)
    
    def forward(self, x):
        return self.linear(x)

classifier_head = TinyClassifierHead(num_classes=3)

# Create tiny data loader with batches
# Each item: (inputs, labels, texts, source)
data_loader = [
    (
        torch.randn(2, 4),  # inputs: batch_size=2, feature_dim=4
        torch.tensor([0, 1]),  # labels
        ['text1', 'text2'],  # texts
        torch.tensor([0, 1])  # source
    ),
    (
        torch.randn(2, 4),
        torch.tensor([2, 0]),
        ['text3', 'text4'],
        torch.tensor([2, 0])
    )
]

# Loss function
loss_fn = nn.CrossEntropyLoss()

# Logger mock
logger = MagicMock()

# Logit scale parameter
logit_scale = nn.Parameter(torch.tensor(1.0))

ARGS = {
    'args': args,
    'data_loader': data_loader,
    'model': model,
    'logger': logger,
    'loss': loss_fn,
    'logit_scale': logit_scale,
    'classifier_head': classifier_head,
    'show_confusion_matrix': False,
    'device': 'cpu',
    'dataset': 'semi-aves',
    'output_dir': '/tmp',
    'predict_labels': False,
    'predict_split': 'u_train',
    'pre_extracted': False
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, torch, torchmetrics — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple, ndim 1, dtype family float — a tuple output has no array shape of its own; none is stated
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
validate_multitask Ran
ran; our contract draft was wrong, not the code
tian1327/swat/testing.py
code served (permissive licence) · get_code("2c79cde83ec23919")
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 tuple, ndim 1, dtype family float; no output shape is stated. The image it ran in was not recorded. The code mentions cuda, and the harness aliases cuda to the CPU for every sample; whether this run needed that is 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
import numpy as np
from torch.utils.data import DataLoader

torch.manual_seed(0)

# Mock loss function
class MockLoss(nn.Module):
    def __init__(self):
        super().__init__()
    
    def forward(self, logits, labels, source=None):
        return torch.tensor(0.5)

# Mock classifier head
class MockClassifierHead(nn.Module):
    def __init__(self, num_classes=5):
        super().__init__()
        self.num_classes = num_classes
        self.linear = nn.Linear(4, num_classes)
    
    def forward(self, x):
        return self.linear(x)

# Mock model
class MockModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(4, 5)
    
    def encode_image(self, images):
        return self.linear(images)
    
    def forward(self, images, texts):
        logits = self.linear(images)
        return logits, None
    
    def eval(self):
        super().eval()
        return self

# Create mock args object
class MockArgs:
    def __init__(self):
        self.loss = 'CrossEntropy'

# Create data loader with mock data
# Each item: (inputs, labels, texts, source)
data = []
for _ in range(2):
    inputs = torch.randn(2, 4)  # batch_size=2, feature_dim=4
    labels = torch.tensor([0, 1], dtype=torch.long)
    texts = ["text1", "text2"]
    source = torch.tensor([0, 1], dtype=torch.long)
    data.append((inputs, labels, texts, source))

data_loader = data

# Create model and heads
model = MockModel()
classifier_head = MockClassifierHead(num_classes=5)
dataset_classifier_head = MockClassifierHead(num_classes=2)

# Create loss function
loss_fn = MockLoss()

# Create logit scale parameter
logit_scale = nn.Parameter(torch.tensor(1.0))

# Create logger (mock)
logger = None

# Create args
args = MockArgs()

ARGS = {
    'args': args,
    'data_loader': data_loader,
    'model': model,
    'logger': logger,
    'loss': loss_fn,
    'logit_scale': logit_scale,
    'classifier_head': classifier_head,
    'dataset_classifier_head': dataset_classifier_head,
    'show_confusion_matrix': False,
    'device': 'cpu',
    'dataset': 'semi-aves',
    'output_dir': 'output',
    'predict_labels': False,
    'predict_split': 'u_train',
    'pre_extracted': True,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, torch, torchmetrics — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple, ndim 1, dtype family float — a tuple output has no array shape of its own; none is stated
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
extract_test_feats Not yet run
unverified (harvested, no recorded run)
tian1327/swat/retrieval/extract_mined_feature.py
code served (permissive licence) · get_code("5a340cb616c813ca")
How it ran

no invocation recorded.

Also present in other papers' code

Of 7 samples lifted from this paper's linked repositories, 7 carry a function identity and 0 do not. Of the 7 distinct functions with an identity, 0 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 0 later) and 7 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.

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

Few-shot recognition (FSR) aims to train a classification model with only a few labeled examples of each concept concerned by a downstream task, where data annotation cost can be prohibitively high. We develop methods to solve FSR by leveraging a pretrained Vision-Language Model (VLM). We particularly explore retrieval-augmented learning (RAL), which retrieves open data, e.g., the VLM's pretraining dataset, to learn models for better serving downstream tasks. RAL has been studied in zero-shot recognition but remains under-explored in FSR. Although applying RAL to FSR may seem straightforward, we observe interesting and novel challenges and opportunities. First, somewhat surprisingly, finetuning a VLM on a large amount of retrieved data underperforms state-of-the-art zero-shot methods. This is due to the imbalanced distribution of retrieved data and its domain gaps with the few-shot examples in the downstream task. Second, more surprisingly, we find that simply finetuning a VLM solely on few-shot examples significantly outperforms previous FSR methods, and finetuning on the mix of retrieved and few-shot data yields even better results. Third, to mitigate the imbalanced distribution and domain gap issues, we propose Stage-Wise retrieval-Augmented fineTuning (SWAT), which involves end-to-end finetuning on mixed data in the first stage and retraining the classifier on the few-shot data in the second stage. Extensive experiments on nine popular benchmarks demonstrate that SWAT significantly outperforms previous methods by >6% accuracy.

For agents

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

get_harvested_code_for_paper("2406.11148")
get_code_for_paper("2406.11148")
have("2406.11148")

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

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

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

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

Connect an agent — have() is free.