SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2109.01134 · 2021

Learning to Prompt for Vision-Language Models

Chen Change Loy, Ziwei Liu, Kaiyang Zhou, Jingkang Yang

arXiv · PDF · Open in the Atlas

Code that ran

3 of 12 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 2 have no contract verdict; 1 failure of our instrument; 9 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/2109.01134.json · badge: /api/ran/2109.01134.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
hhenryd/tap community
Papers with Code archive
2 ran · 8 no recorded run
ThomasWangY/2024-AAAI-HPT community
Papers with Code archive
1 ran · 0 no recorded run
Vill-Lab/2024-TIP-MetaPrompt community
Papers with Code archive
0 ran · 1 no recorded run
FunctionStatusWhere it lives
CrossAttention Ran
ran on a synthesized input
hhenryd/tap/trainers/TAP.py
code served (permissive licence) · get_code("aa2102c5842a8045")
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, 1, 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

class CrossAttention(nn.Module):

    def __init__(self, dim=512, qkv_bias=True):
        super().__init__()
        self.dim = dim
        self.scale = self.dim ** (-0.5)
        self.q = nn.Linear(dim, dim, bias=qkv_bias)
        self.k = nn.Linear(dim, dim, bias=qkv_bias)
        self.init_weights()

    def init_weights(self):
        for child_name, child_module in self.named_children():
            if isinstance(child_module, nn.Linear):
                nn.init.trunc_normal_(child_module.weight, std=0.02)
                if child_module.bias is not None:
                    nn.init.zeros_(child_module.bias)

    def forward(self, x, attn_mask):
        B, N, C = x.shape
        k = self.k(x[:, 1:, :])
        q = self.q(x[:, 0:1, :])
        q = q * self.scale
        attn = q @ k.transpose(-2, -1)
        attn = attn + (1 - attn_mask[:, 1:]).unsqueeze(1) * torch.finfo(attn.dtype).min
        attn = attn.softmax(dim=-1)
        x = attn @ x[:, 1:, :]
        return x


INIT_ARGS = {
    'dim': 4,
    'qkv_bias': True,
}

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

if __name__ == '__main__':
    model = CrossAttention(**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
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, 1, 4) — shape (2, 1, 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)
PromptLearner Ran
ran on a synthesized input · constructed an object; no result was computed
ThomasWangY/2024-AAAI-HPT/trainers/hpt.py
code served (permissive licence) · get_code("8a2b72f24481ca15")
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, PromptLearner: the run constructed the object and did not call it, so no result was computed. 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 random

torch.manual_seed(0)

# Create a minimal CLIP-like model that has the required attributes
class MinimalCLIPModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.dtype = torch.float32
        ctx_dim = 4
        num_layers = 3
        
        # ln_final needs weight attribute with shape[0] = ctx_dim
        self.ln_final = nn.LayerNorm(ctx_dim)
        
        # transformer.resblocks needs to be indexable with len()
        self.transformer = nn.Module()
        self.transformer.resblocks = nn.ModuleList([
            nn.Linear(ctx_dim, ctx_dim) for _ in range(num_layers)
        ])
        
        # token_embedding for embedding tokenized prompts
        self.token_embedding = nn.Embedding(1000, ctx_dim)
    
    def forward(self, x):
        return x

clip_model = MinimalCLIPModel()

# Create a minimal config object
class MinimalConfig:
    def __init__(self):
        self.TRAINER = type('obj', (object,), {
            'HPT': type('obj', (object,), {
                'N_TPRO': 2,
                'N_SET': 3
            })()
        })()

cfg = MinimalConfig()

# Classnames
classnames = ['class_a', 'class_b']

# info_topo: dict mapping class name to list of dicts with Entities and Attributes
info_topo = {
    'class_a': [
        {
            'Entities': ['entity1', 'entity2'],
            'Attributes': ['attr1', 'attr2']
        },
        {
            'Entities': ['entity3', 'entity4'],
            'Attributes': ['attr3', 'attr4']
        },
        {
            'Entities': ['entity5', 'entity6'],
            'Attributes': ['attr5', 'attr6']
        }
    ],
    'class_b': [
        {
            'Entities': ['entity7', 'entity8'],
            'Attributes': ['attr7', 'attr8']
        },
        {
            'Entities': ['entity9', 'entity10'],
            'Attributes': ['attr9', 'attr10']
        },
        {
            'Entities': ['entity11', 'entity12'],
            'Attributes': ['attr11', 'attr12']
        }
    ]
}

# Create a mock clip.tokenize function
class MockClip:
    @staticmethod
    def tokenize(text, truncate=False):
        # Return a tensor of token indices
        return torch.randint(0, 100, (1, 50))

clip = MockClip()

ARGS = {
    'cfg': cfg,
    'classnames': classnames,
    'info_topo': info_topo,
    'clip_model': clip_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 PromptLearner — 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 PromptLearner 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
make_description_batch Ran
ran; our contract draft was wrong, not the code
hhenryd/tap/trainers/TAP.py
code served (permissive licence) · get_code("c568c664a705cfa6")
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) and returned tuple. 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

torch.manual_seed(0)

# The function expects a dict where:
# - keys are class names (strings)
# - values are 2D tensors of shape (sequence_length, embedding_dim)
# The function computes max_len from the first dimension of these tensors

descriptor_text_prompt = {
    "class_0": torch.randint(0, 100, (5, 4), dtype=torch.long),  # 5 tokens, 4-dim embeddings
    "class_1": torch.randint(0, 100, (3, 4), dtype=torch.long),  # 3 tokens, 4-dim embeddings
    "class_2": torch.randint(0, 100, (7, 4), dtype=torch.long),  # 7 tokens, 4-dim embeddings
}

ARGS = {
    "descriptor_text_prompt": descriptor_text_prompt,
    "max_len_quantile": 1.0,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple — a tuple output has no array shape of its own; none is 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
AttentionPooling Not yet run
unverified (harvested, no recorded run)
hhenryd/tap/trainers/TAP.py
code served (permissive licence) · get_code("e8079fe48af584cb")
How it ran

no invocation recorded.

CustomCLIP_TAP Not yet run
unverified (harvested, no recorded run)
hhenryd/tap/trainers/TAP.py
code served (permissive licence) · get_code("7c02c9c890628418")
How it ran

no invocation recorded.

PromptLearner Not yet run
unverified (harvested, no recorded run)
Vill-Lab/2024-TIP-MetaPrompt/trainers/meta.py
code served (permissive licence) · get_code("39be90830c4c1621")
How it ran

no invocation recorded.

TextEncoder Not yet run
unverified (harvested, no recorded run)
hhenryd/tap/trainers/TAP.py
code served (permissive licence) · get_code("c1fabc9fbf753209")
How it ran

no invocation recorded.

TextPromptLearner Not yet run
unverified (harvested, no recorded run)
hhenryd/tap/trainers/TAP.py
code served (permissive licence) · get_code("0746a2da2f73c0eb")
How it ran

no invocation recorded.

VisualEncoder Not yet run
unverified (harvested, no recorded run)
hhenryd/tap/trainers/TAP.py
code served (permissive licence) · get_code("e1f5a7fb2fb95e19")
How it ran

no invocation recorded.

VisualPromptLearner Not yet run
unverified (harvested, no recorded run)
hhenryd/tap/trainers/TAP.py
code served (permissive licence) · get_code("d75235fc5acba1a6")
How it ran

no invocation recorded.

load_clip_to_cpu Not yet run
unverified (harvested, no recorded run)
hhenryd/tap/trainers/TAP.py
code served (permissive licence) · get_code("0f982cfc0f69d842")
How it ran

no invocation recorded.

load_gpt_descriptions Not yet run
unverified (harvested, no recorded run)
hhenryd/tap/trainers/TAP.py
code served (permissive licence) · get_code("bf5154cf822c8f6a")
How it ran

no invocation recorded.

Also present in other papers' code

Of 12 samples lifted from this paper's linked repositories, 12 carry a function identity and 0 do not. Of the 12 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 12 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

Large pre-trained vision-language models like CLIP have shown great potential in learning representations that are transferable across a wide range of downstream tasks. Different from the traditional representation learning that is based mostly on discretized labels, vision-language pre-training aligns images and texts in a common feature space, which allows zeroshot transfer to a downstream task via prompting, i.e., classification weights are synthesized from natural language describing classes of interest. In this work, we show that a major challenge for deploying such models in practice is prompt engineering, which requires domain expertise and is extremely time-consumingone needs to spend a significant amount of time on words tuning since a slight change in wording could have a huge impact on performance. Inspired by recent advances in prompt learning research in natural language processing (NLP), we propose Context Optimization (CoOp), a simple approach specifically for adapting CLIP-like vision-language models for downstream image recognition. Concretely, CoOp models a prompt's context words with learnable vectors while the entire pre-trained parameters are kept fixed. To handle different image recognition tasks, we provide two

For agents

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

get_harvested_code_for_paper("2109.01134")
get_code_for_paper("2109.01134")
have("2109.01134")

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

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

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

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

Connect an agent — have() is free.