Docs /Templates/ sinapsis-anomalib

FoundADTrain

sinapsis-anomalibAnomalibanomalibanomaly_detectiondynamicmodels

Python template · sinapsis_anomalib.templates.anomalib_train

Overview

Training implementation for Anomalib models.

FoundAD — inherited documentation

FoundAD Lightning Module.

Trains a lightweight manifold projector on a frozen DINOv2 encoder with CutPaste augmentation. Only the projector parameters are learned.

Args: encoder_name: DINOv2 model name. Defaults to ``"dinov2_vit_base_14"``. pred_depth: Number of projector transformer blocks. Defaults to ``6``. pred_emb_dim: Projector internal dimension. Defaults to ``384``. n_layer: Encoder layer to extract features from (n-th from last). Defaults to ``3``. top_k: Top-K patches for image-level scoring. Defaults to ``10``. dropout: Dropout on features before projector. Defaults to ``0.2``. feat_normed: L2-normalize features. Defaults to ``False``. use_pos_embed: Use positional encoding in projector. Defaults to ``False``. image_size: Input image size. Defaults to ``518`` for DINOv2 (37*14, patch size 14) or ``512`` for DINOv3 (32*16, patch size 16) encoders. Smaller values like ``224`` speed up inference at cost of resolution, but must stay divisible by the encoder's patch size. lr: Learning rate. Defaults to ``1e-3``. weight_decay: Weight decay for AdamW. Defaults to ``1e-4``. color_jitter: CutPaste color jitter strength. Defaults to ``0.5``. use_few_shot_augmentation: Apply random orientation (flip/rotate) and appearance (color jitter/grayscale/blur) augmentation to the base training images before CutPaste. This matches the paper's default training protocol and is important for expanding the diversity of a tiny (1/2/4-shot) training set; disabling it will hurt few-shot results. Defaults to ``True``. pre_processor: Pre-processor configuration. post_processor: Post-processor configuration. evaluator: Evaluator configuration. visualizer: Visualizer configuration.

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

>>> model = FoundAD() >>> datamodule = MVTecAD() >>> engine = Engine() >>> engine.fit(model, datamodule=datamodule) # doctest: +SKIP

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
metadata
sinapsis_core.template_base.base_models.TemplateMetadata | None
Optional
Default: null
callbacks
list[lightning.pytorch.callbacks.callback.Callback] | None
Optional
Default: null
ckpt_path

Path to checkpoint for resuming training. If None, starts training from scratch.

str | pathlib._local.Path | 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
train_root
str | pathlib._local.Path | None
Optional
Default: null
foundad_initRequired
__init__Attributes
Required
Default: null
lr
float
Optional
Default: 0.001
top_k
int
Optional
Default: 10
dropout
float
Optional
Default: 0.2
n_layer
int
Optional
Default: 3
evaluator
typing.Union[anomalib.metrics.evaluator.Evaluator, bool]
Optional
Default: true
image_size
typing.Optional[int]
Optional
Default: null
pred_depth
int
Optional
Default: 6
visualizer
typing.Union[anomalib.visualization.base.Visualizer, bool]
Optional
Default: true
feat_normed
bool
Optional
Default: false
color_jitter
float
Optional
Default: 0.5
encoder_name
str
Optional
Default: "dinov2_vit_base_14"
pred_emb_dim
int
Optional
Default: 384
weight_decay
float
Optional
Default: 0.0001
pre_processor
typing.Union[anomalib.pre_processing.pre_processor.PreProcessor, bool]
Optional
Default: true
use_pos_embed
bool
Optional
Default: false
post_processor
typing.Union[anomalib.post_processing.post_processor.PostProcessor, bool]
Optional
Default: true
use_few_shot_augmentation
bool
Optional
Default: true
trainer_args
(TrainerConfig): General trainer arguments. For more details see: https://lightning.ai/docs/pytorch/stable/common/trainer.html#trainer-flags foundad_init encoder_name <class 'str'>: default: dinov2_vit_base_14… Read full field description

(TrainerConfig): General trainer arguments. For more details see: https://lightning.ai/docs/pytorch/stable/common/trainer.html#trainer-flags foundad_init encoder_name <class 'str'>: default: dinov2_vit_base_14 pred_depth <class 'int'>: default: 6 pred_emb_dim <class 'int'>: default: 384 n_layer <class 'int'>: default: 3 top_k <class 'int'>: default: 10 dropout <class 'float'>: default: 0.2 feat_normed <class 'bool'>: default: False use_pos_embed <class 'bool'>: default: False image_size typing.Optional[int]: default: None lr <class 'float'>: default: 0.001 weight_decay <class 'float'>: default: 0.0001 color_jitter <class 'float'>: default: 0.5 use_few_shot_augmentation <class 'bool'>: default: True pre_processor typing.Union[anomalib.pre_processing.pre_processor.PreProcessor, bool]: default: True post_processor typing.Union[anomalib.post_processing.post_processor.PostProcessor, bool]: default: True evaluator typing.Union[anomalib.metrics.evaluator.Evaluator, bool]: default: True visualizer typing.Union[anomalib.visualization.base.Visualizer, bool]: default: True

TrainerConfig
Optional
Default: null
devices

The devices to use for training (e.g., 1, [0, 1], "auto"). Defaults to "auto".

int | list[int] | str | None
Optional
Default: "auto"
max_epochs

The maximum number of epochs to train for. Defaults to 5.

int | None
Optional
Default: 5
min_epochs

The minimum number of epochs to train for. Defaults to 1.

int
Optional
Default: 1
accelerator

The hardware accelerator to use. Defaults to "auto".

typing.Literal['cpu', 'gpu', 'tpu', 'hpu', 'auto']
Optional
Default: "cpu"
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
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

Configuration example

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

yaml
templates:
  - template_name: "FoundADTrain"
    class_name: "FoundADTrain"
    attributes:
      logger: null
      callbacks: null
      ckpt_path: null
      threshold: null
      train_root: null
      foundad_init:
        lr: 0.001
        top_k: 10
        dropout: 0.2
        n_layer: 3
        evaluator: true
        image_size: null
        pred_depth: 6
        visualizer: true
        feat_normed: false
        color_jitter: 0.5
        encoder_name: "dinov2_vit_base_14"
        pred_emb_dim: 384
        weight_decay: 0.0001
        pre_processor: true
        use_pos_embed: false
        post_processor: true
        use_few_shot_augmentation: true
      trainer_args:
        devices: "auto"
        max_epochs: 5
        min_epochs: 1
        accelerator: "cpu"
      image_metrics: null
      normalization: null
      pixel_metrics: null
      logger_configs: null
      callback_configs: 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
View original docstring example

The source example references CfaTrain, not FoundADTrain.

yaml
agent:
    name: my_test_agent
    templates:
    - template_name: InputTemplate
    class_name: InputTemplate
    attributes: {}
    - template_name: CfaTrain
    class_name: CfaTrain
    template_input: InputTemplate
    attributes:
        folder_attributes_config_path: 'path/to/config.yaml'
        generic_key: 'my_generic_key'
        callbacks: null
        normalization: null
        threshold: null
        image_metrics: null
        pixel_metrics: null
        logger: null
        callback_configs: null
        logger_configs: null
        ckpt_path: null
        trainer_args:
            devices: "0"
            accelerator: gpu
            max_epochs: 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.

Inheritance

Immediate parent: sinapsis_anomalib.templates.anomalib_train.AnomalibTrain

Environment variables

Environment definitions belong to their canonical Python modules.

ANOMALIB_ROOT_DIR · defined elsewhereSINAPSIS_BUILD_DOCS · defined elsewhere