SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2510.00495 · NeurIPS · 2025

Normal-Abnormal Guided Generalist Anomaly Detection

Jimin Xiao, Xiaolei Wang, Yuexin Wang, Yizheng Gong

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 (5 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 6 have no contract verdict; 0 failures of our instrument; 1 no recorded run), measured 2026-11-22; 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/2510.00495.json · badge: /api/ran/2510.00495.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
JasonKyng/NAGL community
Papers with Code archive
6 ran · 1 no recorded run
FunctionStatusWhere it lives
BinaryDiceLoss Ran
ran on a synthesized input · constructed an object; no result was computed
JasonKyng/NAGL/models/model.py
code served (permissive licence) · get_code("1f1232cc8350d48f")
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, BinaryDiceLoss: 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)

# Construct arguments for BinaryDiceLoss
# The __init__ method takes one parameter: smooth (with default value 1)
# The forward method takes inputs and targets (both tensors)

# Create small tensors for testing
# inputs: predictions (batch_size=2, spatial dimensions=4x3)
# targets: ground truth (same shape as inputs)
batch_size = 2
height = 4
width = 3

inputs = torch.rand(batch_size, height, width)
targets = torch.randint(0, 2, (batch_size, height, width)).float()

ARGS = {
    "smooth": 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 BinaryDiceLoss — 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 BinaryDiceLoss 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
CrossAttentionLayer Ran
ran on a synthesized input · constructed an object; no result was computed
JasonKyng/NAGL/models/model.py
code served (permissive licence) · get_code("b56ef1055cbbd597")
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, CrossAttentionLayer: 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
import torch.nn.functional as F
from typing import Optional

torch.manual_seed(0)

# Set up the model
d_model = 8
nhead = 2
dropout = 0.1
activation = 'relu'
normalize_before = False

model = nn.Module()

# Set up batch tensors with distinct dimensions
batch_size = 2
seq_len_tgt = 3
seq_len_memory = 5

# Query/target tensor (batch, seq_len, d_model)
tgt = torch.randn(seq_len_tgt, batch_size, d_model)

# Key tensor for memory (batch, seq_len, d_model)
memory_key = torch.randn(seq_len_memory, batch_size, d_model)

# Value tensor for memory (batch, seq_len, d_model)
memory_value = torch.randn(seq_len_memory, batch_size, d_model)

# Optional masks and positional embeddings
memory_mask = None
memory_key_padding_mask = None
pos = torch.randn(seq_len_memory, batch_size, d_model)
query_pos = torch.randn(seq_len_tgt, batch_size, d_model)
value_pos = torch.randn(seq_len_memory, batch_size, d_model)

ARGS = {
    'd_model': d_model,
    'nhead': nhead,
    'dropout': dropout,
    'activation': activation,
    'normalize_before': normalize_before,
}
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 CrossAttentionLayer — 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 CrossAttentionLayer 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
DiceLoss Ran
ran on a synthesized input · constructed an object; no result was computed
JasonKyng/NAGL/models/model.py
code served (permissive licence) · get_code("72a5bef735c74fae")
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, DiceLoss: 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)

class BinaryDiceLoss(nn.Module):

    def __init__(self, smooth=1):
        super(BinaryDiceLoss, self).__init__()
        self.smooth = smooth

    def forward(self, inputs, targets):
        N = targets.size()[0]
        input_flat = inputs.view(N, -1)
        targets_flat = targets.view(N, -1)
        intersection = input_flat * targets_flat
        N_dice_eff = (2 * intersection.sum(1) + self.smooth) / (input_flat.sum(1) + targets_flat.sum(1) + self.smooth)
        loss = 1 - N_dice_eff.sum() / N
        return loss

def smooth(arr, lamda1):
    new_array = arr
    arr2 = torch.zeros_like(arr)
    arr2[:, :-1, :] = arr[:, 1:, :]
    arr2[:, -1, :] = arr[:, -1, :]
    new_array2 = torch.zeros_like(new_array)
    new_array2[:, :, :-1] = new_array[:, :, 1:]
    new_array2[:, :, -1] = new_array[:, :, -1]
    loss = (torch.sum((arr2 - arr) ** 2) + torch.sum((new_array2 - new_array) ** 2)) / 2
    return lamda1 * loss

class DiceLoss(nn.Module):

    def __init__(self, smooth=1):
        super(DiceLoss, self).__init__()
        self.smooth = smooth
        self.b_dice = BinaryDiceLoss(smooth)

    def forward(self, inputs, targets):
        assert inputs.size() == targets.size(), 'inputs and targets must have the same shape'
        N = targets.size(1)
        if inputs.dim() == 3:
            loss = self.b_dice(inputs, targets)
        else:
            log_inputs = inputs.log_softmax(dim=1).exp()
            loss = 0
            for i in range(N):
                loss += self.b_dice(log_inputs[:, i, :, :], targets[:, i, :, :])
        return loss

# Setup for DiceLoss forward call with 3D inputs
batch_size = 2
height = 4
width = 3

inputs_3d = torch.rand(batch_size, height, width)
targets_3d = torch.rand(batch_size, height, width)

# Setup for DiceLoss forward call with 4D inputs
num_classes = 5
inputs_4d = torch.rand(batch_size, num_classes, height, width)
targets_4d = torch.rand(batch_size, num_classes, height, width)

ARGS = {
    "smooth": 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 DiceLoss — 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 DiceLoss 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
FocalLoss Ran
ran on a synthesized input
JasonKyng/NAGL/models/model.py
code served (permissive licence) · get_code("3969c47a428beeeb")
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 0, 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
from torchvision.ops import sigmoid_focal_loss

class FocalLoss(nn.Module):

    def __init__(self, gamma=2, alpha=0.25):
        super(FocalLoss, self).__init__()
        self.gamma = gamma
        self.alpha = alpha

    def forward(self, inputs, target):
        assert inputs.size() == target.size(), 'input and target must have the same shape'
        return sigmoid_focal_loss(inputs, target, self.alpha, self.gamma, reduction='mean')


INIT_ARGS = {
    'gamma': 2.0,
    'alpha': 0.25,
}

ARGS = {
    'inputs': torch.randn(2, 4),
    'target': torch.randint(0, 2, (2, 4)).float(),
}

if __name__ == '__main__':
    focal_loss = FocalLoss(**INIT_ARGS)
    output = focal_loss(**ARGS)
    print(f"Output: {output}")
    print(f"Output shape: {output.shape}")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
torch, torchvision — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 0, 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)
PositionEmbeddingSine Ran
ran on a synthesized input · constructed an object; no result was computed
JasonKyng/NAGL/models/model.py
code served (permissive licence) · get_code("7f02c425d460a256")
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, PositionEmbeddingSine: 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
import math

torch.manual_seed(0)

# Create a minimal valid input tensor
# The function expects shape (B, N, HW, C)
# where HW must be a perfect square (e.g., 4, 9, 16, etc.)
B = 2  # batch size
N = 3  # number of items
HW = 4  # spatial dimension (2x2 grid)
C = 8  # channel dimension

x = torch.randn(B, N, HW, C)

# Optionally create a mask with compatible shape
mask = torch.zeros((B, N, HW, 1), dtype=torch.bool)

# Define arguments for PositionEmbeddingSine.__init__
ARGS = {
    "num_pos_feats": 64,
    "temperature": 10000,
    "normalize": False,
    "scale": None,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
einops, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type PositionEmbeddingSine — 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 PositionEmbeddingSine 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
SelfAttentionLayer Ran
ran on a synthesized input · constructed an object; no result was computed
JasonKyng/NAGL/models/model.py
code served (permissive licence) · get_code("664e5431c96995da")
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, SelfAttentionLayer: 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
import torch.nn.functional as F
from typing import Optional
from torch import Tensor

torch.manual_seed(0)

def _get_activation_fn(activation):
    """Return an activation function given a string"""
    if activation == 'relu':
        return F.relu
    if activation == 'gelu':
        return F.gelu
    if activation == 'glu':
        return F.glu
    raise RuntimeError(f'activation should be relu/gelu, not {activation}.')

class SelfAttentionLayer(nn.Module):

    def __init__(self, d_model, nhead, dropout=0.0, activation='relu', normalize_before=False):
        super().__init__()
        self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
        self.norm = nn.LayerNorm(d_model)
        self.dropout = nn.Dropout(dropout)
        self.activation = _get_activation_fn(activation)
        self.normalize_before = normalize_before
        self._reset_parameters()

    def _reset_parameters(self):
        for p in self.parameters():
            if p.dim() > 1:
                nn.init.xavier_uniform_(p)

    def with_pos_embed(self, tensor, pos: Optional[Tensor]):
        return tensor if pos is None else tensor + pos

    def forward_post(self, tgt, tgt_mask: Optional[Tensor]=None, tgt_key_padding_mask: Optional[Tensor]=None, query_pos: Optional[Tensor]=None):
        q = k = self.with_pos_embed(tgt, query_pos)
        tgt2 = self.self_attn(q, k, value=tgt, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0]
        tgt = tgt + self.dropout(tgt2)
        tgt = self.norm(tgt)
        return tgt

    def forward_pre(self, tgt, tgt_mask: Optional[Tensor]=None, tgt_key_padding_mask: Optional[Tensor]=None, query_pos: Optional[Tensor]=None):
        tgt2 = self.norm(tgt)
        q = k = self.with_pos_embed(tgt2, query_pos)
        tgt2 = self.self_attn(q, k, value=tgt2, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0]
        tgt = tgt + self.dropout(tgt2)
        return tgt

    def forward(self, tgt, tgt_mask: Optional[Tensor]=None, tgt_key_padding_mask: Optional[Tensor]=None, query_pos: Optional[Tensor]=None):
        if self.normalize_before:
            return self.forward_pre(tgt, tgt_mask, tgt_key_padding_mask, query_pos)
        return self.forward_post(tgt, tgt_mask, tgt_key_padding_mask, query_pos)

d_model = 4
nhead = 2
dropout = 0.1
activation = 'relu'
normalize_before = False

layer = SelfAttentionLayer(
    d_model=d_model,
    nhead=nhead,
    dropout=dropout,
    activation=activation,
    normalize_before=normalize_before
)

tgt = torch.randn(3, 2, d_model)
query_pos = torch.randn(3, 2, d_model)

ARGS = {
    'd_model': d_model,
    'nhead': nhead,
    'dropout': dropout,
    'activation': activation,
    'normalize_before': normalize_before
}
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 SelfAttentionLayer — 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 SelfAttentionLayer 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
NAGL Not yet run
unverified (harvested, no recorded run)
JasonKyng/NAGL/models/model.py
code served (permissive licence) · get_code("23f2d5ff92e8cd05")
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, 2 are also present in other papers whose code we hold (2 with at least one paper dated earlier, 0 the same month, 1 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
CrossAttentionLayer
brick of this paper's assembly: model
2 other papers
1 dated earlier, 1 later
2402.17726 (2024-02)
VRP-SAM: SAM with Visual Reference Prompt
2602.00635 (2026-02)
S 3 POT: Contrast-Driven Face Occlusion Segmentation via Self-Supervised Prompt Learning
SelfAttentionLayer
brick of this paper's assembly: model
1 other paper
1 dated earlier
2402.17726 (2024-02)
VRP-SAM: SAM with Visual Reference Prompt

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

Generalist Anomaly Detection (GAD) aims to train a unified model on an original domain that can detect anomalies in new target domains. Previous GAD methods primarily use only normal samples as references, overlooking the valuable information contained in anomalous samples that are often available in real-world scenarios. To address this limitation, we propose a more practical approach: normal-abnormalguided generalist anomaly detection, which leverages both normal and anomalous samples as references to guide anomaly detection across diverse domains. We introduce the Normal-Abnormal Generalist Learning (NAGL) framework, consisting of two key components: Residual Mining (RM) and Anomaly Feature Learning (AFL). RM extracts abnormal patterns from normal-abnormal reference residuals to establish transferable anomaly representations, while AFL adaptively learns anomaly features in query images through residual mapping to identify instance-aware anomalies. Our approach effectively utilizes both normal and anomalous references for more accurate and efficient cross-domain anomaly detection. Extensive experiments across multiple benchmarks demonstrate that our method significantly outperforms existing GAD approaches. This work represents the first to adopt a mixture of normal and abnormal samples as references in generalist anomaly detection. The code and datasets are available at https://github.com/JasonKyng/NAGL.

For agents

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

get_harvested_code_for_paper("2510.00495")
get_code_for_paper("2510.00495")
have("2510.00495")

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

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

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

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

Connect an agent — have() is free.