SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2508.13560 · ICCV · 2025

DictAS: A Framework for Class-Generalizable Few-Shot Anomaly Segmentation via Dictionary Lookup

Ucla, Guiguang Ding, Fei Shen, Xinyi Gong, Xingang Wang, Mukesh Prasad, Zhen Qu, Xian Tao, Shichen Qu, Zhengtao Zhang, Xiaopei Zhang

arXiv · PDF · Open in the Atlas

Code that ran

5 of 6 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (3 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 5 have no contract verdict; 0 failures of our instrument; 1 no recorded run), measured 2026-11-24; 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/2508.13560.json · badge: /api/ran/2508.13560.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
xiaozhen228/DictAS community
Papers with Code archive
5 ran · 1 no recorded run
FunctionStatusWhere it lives
Attn_Block Ran
ran on a synthesized input · constructed an object; no result was computed
xiaozhen228/DictAS/models/DictAS.py
code served (permissive licence) · get_code("4ff80bccfc42ae35")
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, Attn_Block: 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 the MLP and Attn_Block classes as provided
class MLP(nn.Module):
    def __init__(self, dim, proj_drop=0.1):
        super().__init__()
        self.linear1 = nn.Linear(dim, dim)
        self.drop = nn.Dropout(proj_drop)
        self.linear2 = nn.Linear(dim, dim)
        self.norm = nn.LayerNorm(dim)
        self.linear3 = nn.Linear(dim, dim, bias=False)

    def forward(self, x, res):
        x = self.linear1(x)
        x = self.drop(x)
        x = x + res
        x = self.linear2(x)
        x = self.norm(x)
        x = self.linear3(x)
        return x

class Attn_Block(nn.Module):
    def __init__(self, dim, num_heads=4, qkv_bias=False, qk_scale=None, proj_drop=0.1):
        super().__init__()
        self.num_heads = num_heads
        head_dim = dim // num_heads
        self.scale = qk_scale or head_dim ** (-0.5)
        self.q_proj = nn.Linear(dim, dim, bias=qkv_bias)
        self.k_proj = nn.Linear(dim, dim, bias=qkv_bias)
        self.v_proj = nn.Linear(dim, dim, bias=qkv_bias)
        self.norm1 = nn.LayerNorm(dim)
        self.TwoLayerMLP = MLP(dim, 0.1)

    def forward(self, fea):
        q = k = v = self.norm1(fea)
        res = q.clone()
        B, N, C = q.shape
        assert k.shape == v.shape
        B, M, C = k.shape
        q = self.q_proj(q).reshape(B, N, self.num_heads, C // self.num_heads)
        k = self.k_proj(k).reshape(B, M, self.num_heads, C // self.num_heads)
        v = self.v_proj(v).reshape(B, M, self.num_heads, C // self.num_heads)
        q = q.transpose(1, 2)
        k = k.transpose(1, 2)
        v = v.transpose(1, 2)
        from torch.nn.functional import scaled_dot_product_attention
        x = scaled_dot_product_attention(q, k, v, is_causal=False)
        x = x.transpose(1, 2).reshape(B, N, C)
        x = self.TwoLayerMLP(x, res)
        return x

# Construct valid arguments for Attn_Block.__init__
ARGS = {
    'dim': 8,
    'num_heads': 2,
    'qkv_bias': False,
    'qk_scale': None,
    'proj_drop': 0.1
}
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 Attn_Block — 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 Attn_Block 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
GenValue Ran
ran on a synthesized input · constructed an object; no result was computed
xiaozhen228/DictAS/models/DictAS.py
code served (permissive licence) · get_code("adade1d43a80dcdb")
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, GenValue: 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)

# Create a minimal config dict with the required structure
config = {
    'vision_cfg': {
        'width': 8
    }
}

# Create a small input tensor: (batch=2, sequence_length=3, dim=8)
x = torch.randn(2, 3, 8)

ARGS = {
    'config': config
}
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 GenValue — 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 GenValue 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
Global_Feature Ran
ran on a synthesized input · constructed an object; no result was computed
xiaozhen228/DictAS/models/DictAS.py
code served (permissive licence) · get_code("bdc2cec973f04ac5")
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, Global_Feature: 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)

class Global_Feature(nn.Module):

    def __init__(self, dim_i, dim_hid, dim_out, k):
        super(Global_Feature, self).__init__()
        self.fuse_modules = nn.Linear(dim_i * k, dim_hid)
        self.compress = nn.Linear(dim_hid, 1)
        self.post_process = nn.Linear(dim_hid, dim_out)

    def forward(self, inps):
        x = torch.cat(inps, dim=2)
        x = self.fuse_modules(x)
        x_temp = self.compress(x)
        attention_weights = nn.Softmax(dim=1)(x_temp)
        x = torch.sum(attention_weights * x, dim=1)
        x = self.post_process(x)
        return x


dim_i = 4
dim_hid = 8
dim_out = 5
k = 3

# Create test inputs: list of k tensors, each of shape (batch_size, seq_len, dim_i)
# batch_size=2, seq_len=3, dim_i=4
inps = [torch.randn(2, 3, 4) for _ in range(k)]

ARGS = {
    'dim_i': dim_i,
    'dim_hid': dim_hid,
    'dim_out': dim_out,
    'k': k
}
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 Global_Feature — 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 Global_Feature 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
MLP Ran
ran on a synthesized input
xiaozhen228/DictAS/models/DictAS.py
code served (permissive licence) · get_code("452d4c731921f622")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned Tensor, ndim 3, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import numpy as np
from torch import Tensor, nn

INIT_ARGS = {
    "dim": 4,
    "proj_drop": 0.1,
}

# Create input tensors for forward pass
batch_size = 2
seq_len = 3
dim = INIT_ARGS["dim"]

# Input tensor x: (batch_size, seq_len, dim)
x = torch.randn(batch_size, seq_len, dim)

# Residual tensor res: same shape as x
res = torch.randn(batch_size, seq_len, dim)

ARGS = {
    "x": x,
    "res": res,
}
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 3, dtype family float — no output shape is stated: observe_signature.py observed this class with its constructor sizes canonicalised where it could, which the node does not record, so its shape is not stated as this setup block's
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
Sparse_Lookup Ran
ran on a synthesized input
xiaozhen228/DictAS/models/DictAS.py
code served (permissive licence) · get_code("fe46200877a9944e")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned Tensor, ndim 3, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
from torch import nn

class Sparse_Lookup(nn.Module):

    def __init__(self, dim=None):
        super(Sparse_Lookup, self).__init__()
        self.dim = -1 if dim is None else dim

    def forward(self, input, adim):
        """Forward function.

        Args:
            input (torch.Tensor): Input tensor. First dimension should be the batch size

        Returns:
            torch.Tensor: [batch_size x number_of_logits] Output tensor

        """
        input = input.transpose(0, adim)
        original_size = input.size()
        input = input.reshape(input.size(0), -1)
        input = input.transpose(0, 1)
        dim = 1
        number_of_logits = input.size(dim)
        input = input - torch.max(input, dim=dim, keepdim=True)[0].expand_as(input)
        zs = torch.sort(input=input, dim=dim, descending=True)[0]
        range = torch.arange(start=1, end=number_of_logits + 1, step=1, device=input.device, dtype=input.dtype).view(1, -1)
        range = range.expand_as(zs)
        bound = 1 + range * zs
        cumulative_sum_zs = torch.cumsum(zs, dim)
        is_gt = torch.gt(bound, cumulative_sum_zs).type(input.type())
        k = torch.max(is_gt * range, dim, keepdim=True)[0]
        zs_sparse = is_gt * zs
        taus = (torch.sum(zs_sparse, dim, keepdim=True) - 1) / k
        taus = taus.expand_as(input)
        self.output = torch.max(torch.zeros_like(input), input - taus)
        output = self.output
        output = output.transpose(0, 1)
        output = output.reshape(original_size)
        output = output.transpose(0, adim)
        return output

    def backward(self, grad_output):
        """Backward function."""
        dim = 1
        nonzeros = torch.ne(self.output, 0)
        sum = torch.sum(grad_output * nonzeros, dim=dim) / torch.sum(nonzeros, dim=dim)
        self.grad_input = nonzeros * (grad_output - sum.expand_as(grad_output))
        return self.grad_input


INIT_ARGS = {
    'dim': None
}

ARGS = {
    'input': torch.randn(2, 3, 4),
    'adim': 1
}

if __name__ == '__main__':
    model = Sparse_Lookup(**INIT_ARGS)
    output = model(**ARGS)
    print("Output shape:", output.shape)
    print("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 — 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)
MyDictionary Not yet run
unverified (harvested, no recorded run)
xiaozhen228/DictAS/models/DictAS.py
code served (permissive licence) · get_code("fbffe3769b455a92")
How it ran

no invocation recorded.

Also present in other papers' code

Of 6 samples lifted from this paper's linked repositories, 6 carry a function identity and 0 do not. Of the 6 distinct functions with an identity, 1 are also present in other papers whose code we hold (1 with at least one paper dated earlier, 0 the same month, 0 later) and 5 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
Global_Feature
brick of this paper's assembly: helper
1 other paper
1 dated earlier
2503.10080 (2025-03)
Bayesian Prompt Flow Learning for Zero-Shot Anomaly Detection

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

Repositories linked to this paper

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

Abstract

Recent vision-language models (e.g., CLIP) have demonstrated remarkable class-generalizable ability to unseen classes in few-shot anomaly segmentation (FSAS), leveraging supervised prompt learning or fine-tuning on seen classes. However, their cross-category generalization largely depends on prior knowledge of real seen anomaly samples. In this paper, we propose a novel framework, namely DictAS, which enables a unified model to detect visual anomalies in unseen object categories without any retraining on the target data, only employing a few normal reference images as visual prompts. The insight behind Dic-tAS is to transfer dictionary lookup capabilities to the FSAS task for unseen classes via self-supervised learning, instead of merely memorizing the normal and abnormal feature patterns from the training set. Specifically, DictAS mainly consists of three components: (1) Dictionary Constructionto simulate the index and content of a real dictionary using features from normal reference images. (2) Dictionary Lookup -to retrieve queried region features from the dictionary via a sparse lookup strategy. When a query feature cannot be retrieved, it is classified as an anomaly. (3) Query Discrimination Regularizationto enhance anomaly discrimination by making abnormal features harder to retrieve from the dictionary. To achieve this, Contrastive Query Constraint and Text Alignment Constraint are further proposed. Extensive experiments on seven public industrial and medical datasets demonstrate that DictAS consistently outperforms state-of-the-art FSAS methods.

For agents

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

get_harvested_code_for_paper("2508.13560")
get_code_for_paper("2508.13560")
have("2508.13560")

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

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

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

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

Connect an agent — have() is free.