Docs /Templates/ sinapsis-anomalib

L2BTTrain

sinapsis-anomalibAnomalibanomalibanomaly_detectiondynamicmodels

Python template · sinapsis_anomalib.templates.anomalib_train

Overview

Training implementation for Anomalib models.

L2BT — inherited documentation

Learning to Be a Transformer algorithm.

The L2BT model consists of a pre-trained Vision Transformer teacher that extracts patch embeddings and two shallow student MLPs (backward_net and forward_net) that learn to match the teacher's patch embeddings. The model detects anomalies by comparing the student's ability to reconstruct teacher embeddings on normal images, where degradation indicates anomalies.

Args: lr (float): Learning rate for student network optimization. Defaults to ``1e-4``. layers (Sequence[int]): Indices of Vision Transformer layers used for feature extraction. Must be a sequence of exactly two indices. Defaults to ``(7, 11)``. blur_w_l (int): Lower bound for blur kernel width in augmentation. Defaults to ``5``. blur_w_u (int): Upper bound for blur kernel width in augmentation. Defaults to ``7``. blur_pad_l (int): Lower bound for blur padding in augmentation. Defaults to ``2``. blur_pad_u (int): Upper bound for blur padding in augmentation. Defaults to ``3``. blur_repeats_l (int): Number of repetitions for lower blur kernel. Defaults to ``3``. blur_repeats_u (int): Number of repetitions for upper blur kernel. Defaults to ``5``. topk_ratio (float): Fraction of highest anomaly-map values to use for image-level anomaly scoring. Defaults to ``0.001``. pre_processor (PreProcessor | bool, optional): Pre-processor to transform input data before passing to model. If ``True``, uses default. Defaults to ``True``. post_processor (PostProcessor | bool, optional): Post-processor to generate predictions from model outputs. If ``True``, uses default. Defaults to ``True``. evaluator (Evaluator | bool, optional): Evaluator to compute metrics. If ``True``, uses default. Defaults to ``True``. visualizer (Visualizer | bool, optional): Visualizer to display results. If ``True``, uses default. Defaults to ``True``.

Example: >>> from anomalib.models.image import L2BT >>> from anomalib.data import MVTecAD >>> from anomalib.engine import Engine >>> datamodule = MVTecAD() >>> model = L2BT( ... layers=(7, 11), ... topk_ratio=0.001 ... ) >>> engine = Engine(model=model, datamodule=datamodule) >>> engine.fit() # doctest: +SKIP >>> predictions = engine.predict() # doctest: +SKIP

See Also: - :class:`anomalib.models.image.l2bt.torch_model.L2BTModel`: PyTorch implementation of the model architecture

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
l2bt_initRequired
__init__Attributes
Required
Default: null
lr
float
Optional
Default: 0.0001
layers
typing.Sequence[int]
Optional
Default: [7,11]
blur_w_l
int
Optional
Default: 5
blur_w_u
int
Optional
Default: 7
evaluator
Any
Optional
Default: true
blur_pad_l
int
Optional
Default: 2
blur_pad_u
int
Optional
Default: 3
topk_ratio
float
Optional
Default: 0.001
visualizer
Any
Optional
Default: true
pre_processor
Any
Optional
Default: true
blur_repeats_l
int
Optional
Default: 5
blur_repeats_u
int
Optional
Default: 3
post_processor
Any
Optional
Default: true
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
trainer_args
(TrainerConfig): General trainer arguments. For more details see: https://lightning.ai/docs/pytorch/stable/common/trainer.html#trainer-flags l2bt_init lr <class 'float'>: default: 0.0001 layers typing.Sequence[int]:… Read full field description

(TrainerConfig): General trainer arguments. For more details see: https://lightning.ai/docs/pytorch/stable/common/trainer.html#trainer-flags l2bt_init lr <class 'float'>: default: 0.0001 layers typing.Sequence[int]: default: (7, 11) blur_w_l <class 'int'>: default: 5 blur_w_u <class 'int'>: default: 7 blur_pad_l <class 'int'>: default: 2 blur_pad_u <class 'int'>: default: 3 blur_repeats_l <class 'int'>: default: 5 blur_repeats_u <class 'int'>: default: 3 topk_ratio <class 'float'>: default: 0.001 pre_processor typing.Any: default: True post_processor typing.Any: default: True evaluator typing.Any: default: True visualizer typing.Any: 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: "L2BTTrain"
    class_name: "L2BTTrain"
    attributes:
      logger: null
      callbacks: null
      ckpt_path: null
      l2bt_init:
        lr: 0.0001
        layers: [7, 11]
        blur_w_l: 5
        blur_w_u: 7
        evaluator: true
        blur_pad_l: 2
        blur_pad_u: 3
        topk_ratio: 0.001
        visualizer: true
        pre_processor: true
        blur_repeats_l: 5
        blur_repeats_u: 3
        post_processor: true
      threshold: null
      train_root: null
      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 L2BTTrain.

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