SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2407.15795 · ECCV · 2024

AdaCLIP: Adapting CLIP with Hybrid Learnable Prompts for Zero-Shot Anomaly Detection

Jiangning Zhang, Giacomo Boracchi, Weiming Shen, Yunkang Cao, Luca Frittoli, Yuqi Cheng

arXiv · PDF · Open in the Atlas

Code that ran

20 of 28 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (10 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 1 violated it and 11 have no contract verdict; 8 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/2407.15795.json · badge: /api/ran/2407.15795.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
caoyunkang/adaclip canonical (classifier label)
classifier basis: census
9 ran · 1 no recorded run
caoyunkang/AdaCLIP community
Papers with Code archive
11 ran · 7 no recorded run
FunctionStatusWhere it lives
AttentionalPooler Ran
ran on a synthesized input · constructed an object; no result was computed
caoyunkang/AdaCLIP/method/adaclip.py
code served (permissive licence) · get_code("8933c7b9c7e59316")
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, AttentionalPooler: 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

torch.manual_seed(0)

ARGS = {
    "d_model": 4,
    "context_dim": 3,
    "n_head": 2,
    "n_queries": 5,
    "norm_layer": nn.LayerNorm,
}
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 AttentionalPooler — 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 AttentionalPooler 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
CLIPTextCfg Ran
ran on a synthesized input · constructed an object; no result was computed
caoyunkang/AdaCLIP/method/adaclip.py
code served (permissive licence) · get_code("d53cfe614e64f0f8")
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, CLIPTextCfg: 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
import torch.nn as nn
from dataclasses import dataclass
from typing import Optional

torch.manual_seed(0)

@dataclass
class CLIPTextCfg:
    context_length: int = 77
    vocab_size: int = 49408
    width: int = 512
    heads: int = 8
    layers: int = 12
    ls_init_value: Optional[float] = None
    hf_model_name: str = None
    hf_tokenizer_name: str = None
    hf_model_pretrained: bool = True
    proj: str = 'mlp'
    pooler_type: str = 'mean_pooler'
    embed_cls: bool = False
    pad_id: int = 0
    output_tokens: bool = False

ARGS = {
    'context_length': 77,
    'vocab_size': 49408,
    'width': 512,
    'heads': 8,
    'layers': 12,
    'ls_init_value': None,
    'hf_model_name': None,
    'hf_tokenizer_name': None,
    'hf_model_pretrained': True,
    'proj': 'mlp',
    'pooler_type': 'mean_pooler',
    'embed_cls': False,
    'pad_id': 0,
    'output_tokens': False,
}
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 CLIPTextCfg — 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 CLIPTextCfg 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
CLIPVisionCfg Ran
ran on a synthesized input · constructed an object; no result was computed
caoyunkang/AdaCLIP/method/adaclip.py
code served (permissive licence) · get_code("358336605882f8ac")
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, CLIPVisionCfg: 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
import torch.nn as nn
from dataclasses import dataclass
from typing import Union, List, Optional, Tuple

torch.manual_seed(0)

@dataclass
class CLIPVisionCfg:
    layers: Union[Tuple[int, int, int, int], int] = 12
    width: int = 768
    head_width: int = 64
    mlp_ratio: float = 4.0
    patch_size: int = 16
    image_size: Union[Tuple[int, int], int] = 224
    ls_init_value: Optional[float] = None
    patch_dropout: float = 0.0
    input_patchnorm: bool = False
    global_average_pool: bool = False
    attentional_pool: bool = False
    n_queries: int = 256
    attn_pooler_heads: int = 8
    timm_model_name: str = None
    timm_model_pretrained: bool = False
    timm_pool: str = 'avg'
    timm_proj: str = 'linear'
    timm_proj_bias: bool = False
    timm_drop: float = 0.0
    timm_drop_path: Optional[float] = None
    output_tokens: bool = False

ARGS = {
    'layers': (3, 4, 6, 3),
    'width': 768,
    'head_width': 64,
    'mlp_ratio': 4.0,
    'patch_size': 16,
    'image_size': (224, 224),
    'ls_init_value': None,
    'patch_dropout': 0.0,
    'input_patchnorm': False,
    'global_average_pool': False,
    'attentional_pool': False,
    'n_queries': 256,
    'attn_pooler_heads': 8,
    'timm_model_name': None,
    'timm_model_pretrained': False,
    'timm_pool': 'avg',
    'timm_proj': 'linear',
    'timm_proj_bias': False,
    'timm_drop': 0.0,
    'timm_drop_path': None,
    'output_tokens': False,
}
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 CLIPVisionCfg — 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 CLIPVisionCfg 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
HybridSemanticFusion Ran
ran on a synthesized input · constructed an object; no result was computed
caoyunkang/AdaCLIP/method/adaclip.py
code served (permissive licence) · get_code("7fef9e3e704a163e")
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, HybridSemanticFusion: 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
from torch.nn import functional as F
from sklearn.cluster import KMeans

torch.manual_seed(0)

class HybridSemanticFusion(nn.Module):

    def __init__(self, k_clusters):
        super(HybridSemanticFusion, self).__init__()
        self.k_clusters = k_clusters
        self.n_aggregate_patch_tokens = k_clusters * 5
        self.cluster_performer = KMeans(n_clusters=self.k_clusters, n_init='auto')

    def forward(self, patch_tokens: list, anomaly_maps: list):
        anomaly_map = torch.mean(torch.stack(anomaly_maps, dim=1), dim=1)
        anomaly_map = torch.softmax(anomaly_map, dim=2)[:, :, 1]
        selected_abnormal_tokens = []
        k = min(anomaly_map.shape[1], self.n_aggregate_patch_tokens)
        top_k_indices = torch.topk(anomaly_map, k=k, dim=1).indices
        for layer in range(len(patch_tokens)):
            selected_tokens = patch_tokens[layer].gather(dim=1, index=top_k_indices.unsqueeze(-1).expand(-1, -1, patch_tokens[layer].shape[-1]))
            selected_abnormal_tokens.append(selected_tokens)
        stacked_data = torch.cat(selected_abnormal_tokens, dim=2)
        batch_cluster_centers = []
        for b in range(stacked_data.shape[0]):
            cluster_labels = self.cluster_performer.fit_predict(stacked_data[b, :, :].detach().cpu().numpy())
            cluster_centers = []
            for cluster_id in range(self.k_clusters):
                collected_cluster_data = []
                for abnormal_tokens in selected_abnormal_tokens:
                    cluster_data = abnormal_tokens[b, :, :][cluster_labels == cluster_id]
                    collected_cluster_data.append(cluster_data)
                collected_cluster_data = torch.cat(collected_cluster_data, dim=0)
                cluster_center = torch.mean(collected_cluster_data, dim=0, keepdim=True)
                cluster_centers.append(cluster_center)
            cluster_centers = torch.cat(cluster_centers, dim=0)
            cluster_centers = torch.mean(cluster_centers, dim=0)
            batch_cluster_centers.append(cluster_centers)
        batch_cluster_centers = torch.stack(batch_cluster_centers, dim=0)
        batch_cluster_centers = F.normalize(batch_cluster_centers, dim=1)
        return batch_cluster_centers


k_clusters = 3

patch_tokens = [
    torch.randn(2, 5, 4),
    torch.randn(2, 5, 6),
    torch.randn(2, 5, 8),
]

anomaly_maps = [
    torch.randn(2, 5, 2),
    torch.randn(2, 5, 2),
]

ARGS = {
    "k_clusters": k_clusters,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
sklearn, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type HybridSemanticFusion — 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 HybridSemanticFusion 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
LayerNorm Ran
ran on a synthesized input
caoyunkang/AdaCLIP/method/adaclip.py
code served (permissive licence) · get_code("60328965616e6752")
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 2, 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
from torch import nn
from torch.nn import functional as F

class LayerNorm(nn.LayerNorm):
    """Subclass torch's LayerNorm (with cast back to input dtype)."""

    def forward(self, x: torch.Tensor):
        orig_type = x.dtype
        x = F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
        return x.to(orig_type)


INIT_ARGS = {
    'normalized_shape': (4,),
    'eps': 1e-5,
    'elementwise_affine': True,
}

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

if __name__ == '__main__':
    layer_norm = LayerNorm(**INIT_ARGS)
    output = layer_norm(**ARGS)
    print(f"Input shape: {ARGS['x'].shape}")
    print(f"Output shape: {output.shape}")
    print(f"Output dtype: {output.dtype}")
    print(f"Output:\n{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 2, 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)
LayerNormFp32 Ran
ran on a synthesized input · constructed an object; no result was computed
caoyunkang/AdaCLIP/method/adaclip.py
code served (permissive licence) · get_code("7a539f31051f66e9")
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, LayerNormFp32: 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
from torch.nn import functional as F

torch.manual_seed(0)

class LayerNormFp32(nn.LayerNorm):
    """Subclass torch's LayerNorm to handle fp16 (by casting to float32 and back)."""

    def forward(self, x: torch.Tensor):
        orig_type = x.dtype
        x = F.layer_norm(x.to(torch.float32), self.normalized_shape, self.weight, self.bias, self.eps)
        return x.to(orig_type)

# Construct arguments for LayerNormFp32
# LayerNormFp32 inherits from nn.LayerNorm, which has the signature:
# nn.LayerNorm(normalized_shape, eps=1e-05, elementwise_affine=True, bias=True, device=None, dtype=None)

normalized_shape = (4,)
eps = 1e-5
elementwise_affine = True
bias = True

ARGS = {
    'normalized_shape': normalized_shape,
    'eps': eps,
    'elementwise_affine': elementwise_affine,
    'bias': bias,
}
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 LayerNormFp32 — 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 LayerNormFp32 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
PatchDropout Ran
ran on a synthesized input · constructed an object; no result was computed
caoyunkang/AdaCLIP/method/adaclip.py
code served (permissive licence) · get_code("a47771f643ef84d8")
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, PatchDropout: 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

torch.manual_seed(0)

# PatchDropout.__init__ parameters:
# - prob: float between 0 and 1 (exclusive of 1)
# - exclude_first_token: bool

ARGS = {
    "prob": 0.5,
    "exclude_first_token": True,
}
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 PatchDropout — 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 PatchDropout 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
ProjectLayer Ran
ran on a synthesized input · constructed an object; no result was computed
caoyunkang/AdaCLIP/method/adaclip.py
code served (permissive licence) · get_code("9bb8bb245a3e6712")
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, ProjectLayer: 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

torch.manual_seed(0)

# Test case 1: is_array=True, stack=False
tokens_array = [
    torch.randn(2, 5, 4),  # batch_size=2, seq_len=5, input_dim=4
    torch.randn(2, 5, 4),
    torch.randn(2, 5, 4),
]

ARGS = {
    "input_dim": 4,
    "output_dim": 3,
    "num_replicas": 3,
    "stack": False,
    "is_array": True,
}

# Create an instance and test it works
layer = nn.Module()
layer.__class__ = type('ProjectLayer', (nn.Module,), {
    '__init__': lambda self, input_dim, output_dim, num_replicas, stack=False, is_array=True: (
        super(type(self), self).__init__(),
        setattr(self, 'head', nn.ModuleList([nn.Linear(input_dim, output_dim) for _ in range(num_replicas)])),
        setattr(self, 'num_replicas', num_replicas),
        setattr(self, 'stack', stack),
        setattr(self, 'is_array', is_array),
    )[-1],
    'forward': lambda self, tokens: (
        (out_tokens := [self.head[i](tokens[i][:, 1:, :]) if self.is_array else self.head[i](tokens) for i in range(self.num_replicas)]),
        torch.stack(list(out_tokens), dim=1) if self.stack else list(out_tokens)
    )[-1]
})

# Simpler approach - just define the setup without worrying about instantiation verification
ARGS = {
    "input_dim": 4,
    "output_dim": 3,
    "num_replicas": 3,
    "stack": False,
    "is_array": True,
}
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 ProjectLayer — 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 ProjectLayer 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
PromptLayer Ran
ran on a synthesized input · constructed an object; no result was computed
caoyunkang/AdaCLIP/method/adaclip.py
code served (permissive licence) · get_code("baa7068d196ec4c6")
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, PromptLayer: 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

torch.manual_seed(0)

# Create a minimal resblock mock that satisfies the interface used in forward methods
class MinimalResblock(nn.Module):
    def __init__(self):
        super().__init__()
    
    def forward(self, q_x, k_x=None, v_x=None, attn_mask=None):
        # Return (x, attn_tmp) as expected by the code
        return (q_x, torch.tensor([]))

# Set up arguments for PromptLayer
ARGS = {
    'channel': 4,
    'length': 3,
    'depth': 2,
    'is_text': True,
    'prompting_type': 'SD',
    'enabled': True,
}
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 PromptLayer — 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 PromptLayer 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
ResidualAttentionBlock Ran
ran on a synthesized input · constructed an object; no result was computed
caoyunkang/AdaCLIP/method/adaclip.py
code served (permissive licence) · get_code("7affcf897896a315")
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, ResidualAttentionBlock: 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
import torch.nn as nn
from torch.nn import functional as F
from collections import OrderedDict

torch.manual_seed(0)

# Define custom classes as in the function
class LayerNorm(nn.LayerNorm):
    """Subclass torch's LayerNorm (with cast back to input dtype)."""

    def forward(self, x: torch.Tensor):
        orig_type = x.dtype
        x = F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
        return x.to(orig_type)

class LayerScale(nn.Module):

    def __init__(self, dim, init_values=1e-05, inplace=False):
        super().__init__()
        self.inplace = inplace
        self.gamma = nn.Parameter(init_values * torch.ones(dim))

    def forward(self, x):
        return x.mul_(self.gamma) if self.inplace else x * self.gamma

class ResidualAttentionBlock(nn.Module):

    def __init__(self, d_model: int, n_head: int, mlp_ratio: float=4.0, ls_init_value: float=None, act_layer=nn.GELU, norm_layer=LayerNorm, is_cross_attention: bool=False, idx: int=12):
        super().__init__()
        self.idx = idx
        self.ln_1 = norm_layer(d_model)
        self.attn = nn.MultiheadAttention(d_model, n_head)
        self.ls_1 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity()
        if is_cross_attention:
            self.ln_1_kv = norm_layer(d_model)
        self.ln_2 = norm_layer(d_model)
        mlp_width = int(d_model * mlp_ratio)
        self.mlp = nn.Sequential(OrderedDict([('c_fc', nn.Linear(d_model, mlp_width)), ('gelu', act_layer()), ('c_proj', nn.Linear(mlp_width, d_model))]))
        self.ls_2 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity()

    def attention(self, q_x: torch.Tensor, k_x=None, v_x=None, attn_mask=None):
        k_x = k_x if k_x is not None else q_x
        v_x = v_x if v_x is not None else q_x
        attn_mask = attn_mask.to(q_x.dtype) if attn_mask is not None else None
        return self.attn(q_x, k_x, v_x, need_weights=True, attn_mask=attn_mask)

    def forward(self, q_x: torch.Tensor, k_x=None, v_x=None, attn_mask=None):
        k_x = self.ln_1_kv(k_x) if hasattr(self, 'ln_1_kv') and k_x is not None else None
        v_x = self.ln_1_kv(v_x) if hasattr(self, 'ln_1_kv') and v_x is not None else None
        tmp, attn = self.attention(q_x=self.ln_1(q_x), k_x=k_x, v_x=v_x, attn_mask=attn_mask)
        x = q_x + self.ls_1(tmp)
        x = x + self.ls_2(self.mlp(self.ln_2(x)))
        return (x, attn)

# Create valid arguments
d_model = 8
n_head = 2

ARGS = {
    'd_model': d_model,
    'n_head': n_head,
    'mlp_ratio': 4.0,
    'ls_init_value': 1e-5,
    'act_layer': nn.GELU,
    'norm_layer': LayerNorm,
    'is_cross_attention': False,
    'idx': 12,
}
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 ResidualAttentionBlock — 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 ResidualAttentionBlock 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
TextTransformer Ran
ran on a synthesized input · constructed an object; no result was computed
caoyunkang/AdaCLIP/method/adaclip.py
code served (permissive licence) · get_code("f60673dd45a8761e")
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, TextTransformer: 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
import torch.nn as nn

torch.manual_seed(0)

# Define ARGS dict with all parameters for TextTransformer
ARGS = {
    'context_length': 77,
    'vocab_size': 49408,
    'width': 512,
    'heads': 8,
    'layers': 12,
    'ls_init_value': 1e-5,
    'output_dim': 512,
    'act_layer': nn.GELU,
    'norm_layer': nn.LayerNorm,
    'embed_cls': False,
    'pad_id': 0,
    'output_tokens': False,
}
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 TextTransformer — 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 TextTransformer 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
basic_clean Ran
ran; our contract draft was wrong, not the code
caoyunkang/adaclip/method/simple_tokenizer.py
pointer only (licence: MIT); the stored copy get_code serves, from ltpwy/MSCI, is pointer only (licence: NONE) · get_code("98f385d847636a3e")
How it ran

The body of this sample is withheld: this paper's link allows the body inline (MIT), but get_code serves the stored copy, first harvested from ltpwy/MSCI, and GitHub detected no licence in that repository when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

convert_to_custom_text_state_dict Ran
ran, violated the contract we drafted
caoyunkang/adaclip/method/clip_model.py
pointer only (licence: MIT); the stored copy get_code serves, from deep-real/dcp, is pointer only (licence: NONE) · get_code("f19962ebb134b3d7")
How it ran

The body of this sample is withheld: this paper's link allows the body inline (MIT), but get_code serves the stored copy, first harvested from deep-real/dcp, and GitHub detected no licence in that repository when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

freeze_batch_norm_2d Ran
ran; our contract draft was wrong, not the code
caoyunkang/adaclip/method/utils.py
pointer only (licence: MIT); the stored copy get_code serves, from mahmoodlab/CONCH, is pointer only (licence: NOASSERTION) · get_code("9b5765523c6d17fd")
How it ran

The body of this sample is withheld: this paper's link allows the body inline (MIT), but get_code serves the stored copy, first harvested from mahmoodlab/CONCH, and GitHub could not classify the licence of that repository (NOASSERTION). The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

get_cast_dtype Ran
ran; our contract draft was wrong, not the code
caoyunkang/adaclip/method/clip_model.py
code served (permissive licence) · get_code("dcd422d66b0581d8")
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 dtype. 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

torch.manual_seed(0)

ARGS = {
    "precision": "bf16"
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type dtype — a dtype output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a dtype 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
get_pairs Ran
ran; our contract draft was wrong, not the code
caoyunkang/adaclip/method/simple_tokenizer.py
code served (permissive licence) · get_code("d919ae32e5e4e616")
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 set. 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

torch.manual_seed(0)

# The function get_pairs takes a word parameter
# A word is represented as a tuple of symbols (variable-length strings)
# The function iterates through the word and creates pairs of consecutive symbols

word = ("hello", "world", "test")

ARGS = {
    "word": word
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type set — a set output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a set 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
list_pretrained Ran
ran; our contract draft was wrong, not the code
caoyunkang/adaclip/method/custom_clip.py
code served (permissive licence) · get_code("c213fb0a0028da05")
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 list, ndim 2, 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

ARGS = {
    'as_str': False
}
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 list, ndim 2, dtype family float — a list 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
list_pretrained_models_by_tag Ran
ran; our contract draft was wrong, not the code
caoyunkang/adaclip/method/custom_clip.py
code served (permissive licence) · get_code("63bcf6e40f415106")
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 list, ndim 1, 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

# Based on the function `list_pretrained_models_by_tag(tag: str)`,
# it only takes a single parameter: `tag` which is a string.
# The function converts the tag to lowercase and replaces hyphens with underscores,
# then searches through the _PRETRAINED dict keys to find matching models.

ARGS = {
    'tag': 'laion2b_s34b_b88k'
}
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 list, ndim 1, dtype family float — a list 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
list_pretrained_tags_by_model Ran
ran; our contract draft was wrong, not the code
caoyunkang/adaclip/method/custom_clip.py
code served (permissive licence) · get_code("1fe3bf9de033fd8f")
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 list, ndim 1, 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.

# Setup code for list_pretrained_tags_by_model

ARGS = {
    'model': 'ViT-B-32'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
none outside the standard library — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type list, ndim 1, dtype family float — a list 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
whitespace_clean Ran
ran; our contract draft was wrong, not the code
caoyunkang/adaclip/method/simple_tokenizer.py
pointer only (licence: MIT); the stored copy get_code serves, from ltpwy/MSCI, is pointer only (licence: NONE) · get_code("9542161e9640b858")
How it ran

The body of this sample is withheld: this paper's link allows the body inline (MIT), but get_code serves the stored copy, first harvested from ltpwy/MSCI, and GitHub detected no licence in that repository when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

AdaCLIP Not yet run
unverified (harvested, no recorded run)
caoyunkang/AdaCLIP/method/adaclip.py
code served (permissive licence) · get_code("ccef093b595414f9")
How it ran

no invocation recorded.

CLIP Not yet run
unverified (harvested, no recorded run)
caoyunkang/AdaCLIP/method/adaclip.py
code served (permissive licence) · get_code("7dd2e9759231f093")
How it ran

no invocation recorded.

TextEmbebddingLayer Not yet run
unverified (harvested, no recorded run)
caoyunkang/AdaCLIP/method/adaclip.py
code served (permissive licence) · get_code("6e78fb5e970d4a0b")
How it ran

no invocation recorded.

Transformer Not yet run
unverified (harvested, no recorded run)
caoyunkang/AdaCLIP/method/adaclip.py
code served (permissive licence) · get_code("2480af5fe5844d5b")
How it ran

no invocation recorded.

VisionTransformer Not yet run
unverified (harvested, no recorded run)
caoyunkang/AdaCLIP/method/adaclip.py
code served (permissive licence) · get_code("51acd62f8b9ee4da")
How it ran

no invocation recorded.

_build_text_tower Not yet run
unverified (harvested, no recorded run)
caoyunkang/AdaCLIP/method/adaclip.py
code served (permissive licence) · get_code("432535468a1356fd")
How it ran

no invocation recorded.

_build_vision_tower Not yet run
unverified (harvested, no recorded run)
caoyunkang/AdaCLIP/method/adaclip.py
code served (permissive licence) · get_code("98b01b93d323fa78")
How it ran

no invocation recorded.

build_model_from_openai_state_dict Not yet run
unverified (harvested, no recorded run)
caoyunkang/adaclip/method/clip_model.py
code served (permissive licence) · get_code("5d5046aaa43f74c7")
How it ran

no invocation recorded.

Also present in other papers' code

Of 28 samples lifted from this paper's linked repositories, 28 carry a function identity and 0 do not. Of the 28 distinct functions with an identity, 13 are also present in other papers whose code we hold (13 with at least one paper dated earlier, 6 the same month, 11 later) and 15 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_pairs
brick of this paper's assembly: helper
258 other papers
164 dated earlier, 4 the same month, 82 later, 7 same year, order not determinable, 1 undated · 4 only as an assembly brick
1802.06474 (2018-02)
A Closed-form Solution to Photorealistic Image Stylization
1803.01128 (2018-03)
Seq2Sick: Evaluating the Robustness of Sequence-to-Sequence Models with Adversarial Examples
1809.00125 (2018-09)
Simple Fusion: Return of the Language Model
and 255 more not named here
whitespace_clean
brick of this paper's assembly: helper
231 other papers
143 dated earlier, 4 the same month, 76 later, 7 same year, order not determinable, 1 undated · 4 only as an assembly brick
1901.07441 (2019-01)
PadChest: A large chest x-ray image dataset with multi-label annotated reports
2107.06383 (2021-07)
How Much Can CLIP Benefit Vision-and-Language Tasks?
2108.10904 (2021-08)
SimVLM: Simple Visual Language Model Pretraining with Weak Supervision
and 228 more not named here
basic_clean
brick of this paper's assembly: helper
218 other papers
144 dated earlier, 4 the same month, 62 later, 7 same year, order not determinable, 1 undated · 4 only as an assembly brick
1901.07441 (2019-01)
PadChest: A large chest x-ray image dataset with multi-label annotated reports
2107.06383 (2021-07)
How Much Can CLIP Benefit Vision-and-Language Tasks?
2108.10904 (2021-08)
SimVLM: Simple Visual Language Model Pretraining with Weak Supervision
and 215 more not named here
get_cast_dtype 66 other papers
36 dated earlier, 2 the same month, 27 later, 1 same year, order not determinable
2103.00020 (2021-03)
Learning Transferable Visual Models From Natural Language Supervision
2210.08402 (2022-10)
LAION-5B: An open large-scale dataset for training next generation image-text models
2212.07143 (2022-12)
Reproducible scaling laws for contrastive language-image learning
and 63 more not named here
convert_to_custom_text_state_dict 49 other papers
29 dated earlier, 1 the same month, 18 later, 1 same year, order not determinable
2103.00020 (2021-03)
Learning Transferable Visual Models From Natural Language Supervision
2210.08402 (2022-10)
LAION-5B: An open large-scale dataset for training next generation image-text models
2212.07143 (2022-12)
Reproducible scaling laws for contrastive language-image learning
and 46 more not named here
build_model_from_openai_state_dict 30 other papers
18 dated earlier, 1 the same month, 10 later, 1 same year, order not determinable
2301.07094 (2023-01)
Learning Customized Visual Models with Retrieval-Augmented Knowledge
2302.03668 (2023-02)
Hard Prompts Made Easy: Gradient-Based Discrete Optimization for Prompt Tuning and Discovery
2303.14814 (2023-03)
WinCLIP: Zero-/Few-Shot Anomaly Classification and Segmentation
and 27 more not named here
freeze_batch_norm_2d 16 other papers
12 dated earlier, 4 later · 3 only as an assembly brick
2102.05918 (2021-02)
Scaling Up Visual and Vision-Language Representation Learning With Noisy Text Supervision
2303.07240 (2023-03)
PMC-CLIP: Contrastive Language-Image Pre-training using Biomedical Documents
2305.10415 (2023-05)
PMC-VQA: Visual Instruction Tuning for Medical Visual Question Answering
and 13 more not named here
LayerNorm
brick of this paper's assembly: helper
7 other papers
3 dated earlier, 4 later · 3 only as an assembly brick
2102.05918 (2021-02)
Scaling Up Visual and Vision-Language Representation Learning With Noisy Text Supervision
2306.09200 (2023-06)
ChessGPT: Bridging Policy Learning and Language Modeling
2308.08428 (2023-08)
ALIP: Adaptive Language-Image Pre-training with Synthetic Caption
and 4 more not named here
list_pretrained 6 other papers
5 dated earlier, 1 later
2301.07094 (2023-01)
Learning Customized Visual Models with Retrieval-Augmented Knowledge
2307.12732 (2023-07)
CLIP-KD: An Empirical Study of CLIP Model Distillation
2311.17048 (2023-11)
Zero-shot Referring Expression Comprehension via Structural Similarity Between Images and Captions
and 3 more not named here
list_pretrained_tags_by_model 4 other papers
4 dated earlier
2301.07094 (2023-01)
Learning Customized Visual Models with Retrieval-Augmented Knowledge
2307.12732 (2023-07)
CLIP-KD: An Empirical Study of CLIP Model Distillation
2309.03904 (2023-09)
Exploring Sparse MoE in GANs for Text-conditioned Image Synthesis
and 1 more not named here
LayerNormFp32
brick of this paper's assembly: helper
3 other papers
1 dated earlier, 2 later · 2 only as an assembly brick
2306.09200 (2023-06)
ChessGPT: Bridging Policy Learning and Language Modeling
2411.03313 (2024-11)
Classification Done Right for Vision-Language Pre-Training
2503.08048 (2025-03)
LongProLIP: A Probabilistic Vision-Language Model with Long Context Text
list_pretrained_models_by_tag 3 other papers
3 dated earlier
2301.07094 (2023-01)
Learning Customized Visual Models with Retrieval-Augmented Knowledge
2309.03904 (2023-09)
Exploring Sparse MoE in GANs for Text-conditioned Image Synthesis
2404.05231 (2024-04)
PromptAD: Learning Prompts with only Normal Samples for Few-Shot Anomaly Detection
PatchDropout
brick of this paper's assembly: helper
2 other papers
1 dated earlier, 1 later · 2 only as an assembly brick
2306.09200 (2023-06)
ChessGPT: Bridging Policy Learning and Language Modeling
2411.03313 (2024-11)
Classification Done Right for Vision-Language Pre-Training

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

Zero-shot anomaly detection (ZSAD) targets the identification of anomalies within images from arbitrary novel categories. This study introduces AdaCLIP for the ZSAD task, leveraging a pre-trained visionlanguage model (VLM), CLIP. AdaCLIP incorporates learnable prompts into CLIP and optimizes them through training on auxiliary annotated anomaly detection data. Two types of learnable prompts are proposed: static and dynamic. Static prompts are shared across all images, serving to preliminarily adapt CLIP for ZSAD. In contrast, dynamic prompts are generated for each test image, providing CLIP with dynamic adaptation capabilities. The combination of static and dynamic prompts is referred to as hybrid prompts, and yields enhanced ZSAD performance. Extensive experiments conducted across 14 real-world anomaly detection datasets from industrial and medical domains indicate that AdaCLIP outperforms other ZSAD methods and can generalize better to different categories and even domains. Finally, our analysis highlights the importance of diverse auxiliary data and optimized prompts for enhanced generalization capacity. Code is available at https://github.com/caoyunkang/AdaCLIP.

For agents

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

get_harvested_code_for_paper("2407.15795")
get_code_for_paper("2407.15795")
have("2407.15795")

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

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

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

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

Connect an agent — have() is free.