Docs /Templates/ sinapsis-anomalib

RadExport

sinapsis-anomalibAnomalibanomalibanomaly_detectiondynamicmodels

Python template · sinapsis_anomalib.templates.anomalib_export

Overview

Export functionality for trained Anomalib models.

Rad — inherited documentation

RAD Lightning Module for anomaly detection.

Implements Retrieval-based Anomaly Detection (RAD), a training-free framework that stores anomaly-free features in a multi-layer memory bank and detects anomalies through image-level retrieval followed by position-aware patch matching.

Args: backbone (str): Name of the ViT backbone from timm. Defaults to ``"vit_base_patch16_dinov3"``. layers (list[int] | None): Block indices (0-based) to extract features from. Defaults to ``[3, 6, 9, 11]``. pre_trained (bool): Whether to use pre-trained backbone weights. Defaults to ``True``. k_image (int): Number of nearest-neighbor training images retrieved per test image. The paper uses ``150`` for MVTec-AD, ``900`` for VisA and Real-IAD, and ``48`` for 3D-ADAM. Defaults to ``150``. use_positional_bank (bool): Enable position-aware patch matching. Defaults to ``True``. pos_radius (int): Spatial neighborhood radius (in patch units). The paper uses ``1`` for MVTec-AD and 3D-ADAM, ``2`` for VisA, and ``0`` for Real-IAD. Defaults to ``1``. max_ratio (float): Fraction of highest anomaly pixels pooled for image-level score. ``0`` means use max. Defaults to ``0.01``. layer_weights (list[float] | None): Per-layer score fusion weights. ``None`` means uniform. Defaults to ``None``. bank_dtype (torch.dtype | str | None): Storage dtype of the memory bank. ``None`` keeps the backbone dtype. ``torch.float16`` halves bank memory and checkpoint size and speeds up scoring, at the cost of a small perturbation of the scores. Defaults to ``None``. pre_processor (PreProcessor | bool): Pre-processor instance or flag. Defaults to ``True``. post_processor (PostProcessor | bool): Post-processor instance or flag. Defaults to ``True``. evaluator (Evaluator | bool): Evaluator instance or flag. Defaults to ``True``. visualizer (Visualizer | bool): Visualizer instance or flag. Defaults to ``True``.

Note: RAD is training-free: fitting only fills the memory bank. The bank is stored in the model state, so checkpoints grow with the size of the anomaly-free training set.

Example: >>> from anomalib.data import MVTecAD >>> from anomalib.models import Rad >>> from anomalib.engine import Engine

>>> datamodule = MVTecAD() >>> model = Rad( ... backbone="vit_base_patch16_dinov3", ... layers=[3, 6, 9, 11], ... k_image=150, ... )

>>> engine = Engine() >>> engine.fit(model=model, datamodule=datamodule)

Capabilities

Capabilities: not set

Installation

Install the published package using pip or uv.

Terminalbash
pip install sinapsis-anomalib==1.0.0
uv pip install sinapsis-anomalib==1.0.0
uv add sinapsis-anomalib==1.0.0

Configuration

Effective fields from the inspector schema, including nested Pydantic model fields.

logger
lightning.pytorch.loggers.logger.Logger | collections.abc.Iterable[lightning.pytorch.loggers.logger.Logger] | bool | None
Optional
Default: null
metric

Metric used for compression calibration.

torchmetrics.metric.Metric | str | None
Optional
Default: null
ov_args

OpenVINO-specific export arguments.

sinapsis_anomalib.helpers.configs.OpenVINOArgs | None
Optional
Default: null
verbose
bool
Optional
Default: false
compress_to_fp16

If True, compresses the model weights to FP16 precision. Defaults to None. Print detailed information about conversion.

bool | None
Optional
Default: null
metadata
sinapsis_core.template_base.base_models.TemplateMetadata | None
Optional
Default: null
rad_initRequired
__init__Attributes
Required
Default: null
layers
NoneType
Optional
Default: null
k_image
int
Optional
Default: 150
backbone
str
Optional
Default: "vit_base_patch16_dinov3"
evaluator
typing.Union[anomalib.metrics.evaluator.Evaluator, bool]
Optional
Default: true
max_ratio
float
Optional
Default: 0.01
bank_dtype
typing.Union[torch.dtype, str, NoneType]
Optional
Default: null
pos_radius
int
Optional
Default: 1
visualizer
typing.Union[anomalib.visualization.base.Visualizer, bool]
Optional
Default: true
pre_trained
bool
Optional
Default: true
layer_weights
NoneType
Optional
Default: null
pre_processor
typing.Union[torch.nn.modules.module.Module, bool]
Optional
Default: true
post_processor
typing.Union[torch.nn.modules.module.Module, bool]
Optional
Default: true
use_positional_bank
bool
Optional
Default: true
callbacks
list[lightning.pytorch.callbacks.callback.Callback] | None
Optional
Default: null
ckpt_path

Explicit path to model checkpoint.

str | None
Optional
Default: null
threshold
anomalib.metrics.threshold.base.Threshold | tuple[anomalib.metrics.threshold.base.Threshold, anomalib.metrics.threshold.base.Threshold] | omegaconf.dictconfig.DictConfig | omegaconf.listconfig.ListConfig | list[dict[str, str | float]] | str | None
Optional
Default: null
input_size

Expected input dimensions (height, width).

tuple[int, int] | None
Optional
Default: null
export_root

Root directory for exported files.

str | pathlib._local.Path | None
Optional
Default: null
export_type

Target export format. Defaults to TORCH.

ExportType
Optional
Default: "torch"
image_metrics
list[str] | str | dict[str, dict[str, typing.Any]] | None
Optional
Default: null
normalization
anomalib.utils.normalization.NormalizationMethod | omegaconf.dictconfig.DictConfig | lightning.pytorch.callbacks.callback.Callback | str | None
Optional
Default: null
pixel_metrics
list[str] | str | dict[str, dict[str, typing.Any]] | None
Optional
Default: null
logger_configs
dict[str, dict[str, typing.Any]] | None
Optional
Default: null
callback_configs
dict[str, dict[str, typing.Any]] | None
Optional
Default: null
compression_type

Quantization/compression method.

anomalib.deploy.export.CompressionType | None
Optional
Default: null
folder_attributes
sinapsis_anomalib.helpers.configs.FolderConfig | None
Optional
Default: null
nameRequired

A descriptive name for the dataset.

str
Required
Default: null
root

The root directory where the dataset is located.

str | pathlib._local.Path | None
Optional
Default: null
seed

A random seed for reproducibility in data splitting.

int | None
Optional
Default: null
mask_dir
str | pathlib._local.Path | collections.abc.Sequence[str | pathlib._local.Path] | None
Optional
Default: null
extensions
list[str] | None
Optional
Default: null
normal_dirRequired

Path to the directory containing normal images.

str | pathlib._local.Path | collections.abc.Sequence[str | pathlib._local.Path]
Required
Default: null
num_workers

The number of subprocesses to use for data loading. Defaults to 8.

int
Optional
Default: 8
abnormal_dir

Path to the directory for abnormal images.

str | pathlib._local.Path | collections.abc.Sequence[str | pathlib._local.Path] | None
Optional
Default: null
val_split_mode
anomalib.data.utils.split.ValSplitMode | str
Optional
Default: "from_test"
eval_batch_size

The number of samples per batch for evaluation. Defaults to 32.

int
Optional
Default: 32
normal_test_dir
str | pathlib._local.Path | collections.abc.Sequence[str | pathlib._local.Path] | None
Optional
Default: null
test_split_mode
anomalib.data.utils.split.TestSplitMode | str
Optional
Default: "from_dir"
val_split_ratio
float
Optional
Default: 0.5
test_split_ratio
float
Optional
Default: 0.2
train_batch_size

The number of samples per batch for training. Defaults to 32.

int
Optional
Default: 32
normal_split_ratio
float
Optional
Default: 0.2
generic_key_chkpt
Key to retrieve training results. rad_init backbone <class 'str'>: default: vit_base_patch16_dinov3 layers <class 'NoneType'>: default: None pre_trained <class 'bool'>: default: True k_image <class 'int'>: default: 150… Read full field description

Key to retrieve training results. rad_init backbone <class 'str'>: default: vit_base_patch16_dinov3 layers <class 'NoneType'>: default: None pre_trained <class 'bool'>: default: True k_image <class 'int'>: default: 150 use_positional_bank <class 'bool'>: default: True pos_radius <class 'int'>: default: 1 max_ratio <class 'float'>: default: 0.01 layer_weights <class 'NoneType'>: default: None bank_dtype typing.Union[torch.dtype, str, NoneType]: default: None pre_processor typing.Union[torch.nn.modules.module.Module, bool]: default: True post_processor typing.Union[torch.nn.modules.module.Module, bool]: default: True evaluator typing.Union[anomalib.metrics.evaluator.Evaluator, bool]: default: True visualizer typing.Union[anomalib.visualization.base.Visualizer, bool]: default: True

str | None
Optional
Default: null

Configuration example

Generated from documented defaults. Replace any placeholders and complete required nested settings before running.

yaml
templates:
  - template_name: "RadExport"
    class_name: "RadExport"
    attributes:
      logger: null
      metric: null
      ov_args:
        verbose: false
        compress_to_fp16: null
      rad_init:
        layers: null
        k_image: 150
        backbone: "vit_base_patch16_dinov3"
        evaluator: true
        max_ratio: 0.01
        bank_dtype: null
        pos_radius: 1
        visualizer: true
        pre_trained: true
        layer_weights: null
        pre_processor: true
        post_processor: true
        use_positional_bank: true
      callbacks: null
      ckpt_path: null
      threshold: null
      input_size: null
      export_root: null
      export_type: {}
      image_metrics: null
      normalization: null
      pixel_metrics: null
      logger_configs: null
      callback_configs: null
      compression_type: null
      folder_attributes:
        name: "<required>"
        root: null
        seed: null
        mask_dir: null
        extensions: null
        normal_dir: "<required>"
        num_workers: 8
        abnormal_dir: null
        val_split_mode: "from_test"
        eval_batch_size: 32
        normal_test_dir: null
        test_split_mode: "from_dir"
        val_split_ratio: 0.5
        test_split_ratio: 0.2
        train_batch_size: 32
        normal_split_ratio: 0.2
      generic_key_chkpt: null
View original docstring example

The source example references CfaExport, not RadExport.

yaml
agent:
    name: my_test_agent
    templates:
    - template_name: InputTemplate
    class_name: InputTemplate
    attributes: {}
    - template_name: CfaExport
    class_name: CfaExport
    template_input: InputTemplate
    attributes:
        folder_attributes_config_path: null
        generic_key: 'my_generic_key'
        callbacks: null
        normalization: null
        threshold: null
        task: null
        image_metrics: null
        pixel_metrics: null
        logger: null
        callback_configs: null
        logger_configs: null
        export_type: 'openvino'
        export_root: null
        input_size: null
        transform: null
        compression_type: null
        metric: null
        ov_args: null
        ckpt_path: null
        generic_key_chkpt: null
        cfa_init:
            backbone: wide_resnet50_2
            gamma_c: 1
            gamma_d: 1
            num_nearest_neighbors: 3
            num_hard_negative_features: 3
            radius: 1.0e-05

For a full list of options use the sinapsis cli: sinapsis info --all-template-names
If you want to see all available models, please visit:
https://anomalib.readthedocs.io/en/v1.2.0/markdown/guides/reference/models/image/index.html

Notes:
    - Supports multiple export formats via ExportType
    - Enables model compression through CompressionType.
    - Can load models from checkpoints or previous training results.

Inheritance

Immediate parent: sinapsis_anomalib.templates.anomalib_export.AnomalibExport

Environment variables

Environment definitions belong to their canonical Python modules.

ANOMALIB_ROOT_DIR · defined elsewhereSINAPSIS_BUILD_DOCS · defined elsewhere