AnomalibModule#

AnomalibModule is the base Lightning module used by Anomalib models. It coordinates preprocessing, post-processing, training, validation, testing, prediction, and model export.

Model implementations normally subclass AnomalibModule and provide their model-specific feature extraction, loss, and anomaly-score logic.

API Reference#

class anomalib.models.components.base.anomalib_module.AnomalibModule(pre_processor=True, post_processor=True, evaluator=True, visualizer=True)#

Bases: ExportMixin, LightningModule, ABC

Base class for all anomaly detection modules in anomalib.

This class provides the core functionality for training, validation, testing and inference of anomaly detection models. It handles data pre-processing, post-processing, evaluation and visualization.

Parameters:
  • pre_processor (Module | bool) – Pre-processor instance or flag to use default. Defaults to True.

  • post_processor (Module | bool) – Post-processor instance or flag to use default. Defaults to True.

  • evaluator (Evaluator | bool) – Evaluator instance or flag to use default. Defaults to True.

  • visualizer (Visualizer | bool) – Visualizer instance or flag to use default. Defaults to True.

model#

PyTorch model to be trained

Type:

nn.Module

loss#

Loss function for training

Type:

nn.Module

callbacks#

List of callbacks

Type:

list[Callback]

pre_processor#

Component for pre-processing inputs

Type:

PreProcessor | None

post_processor#

Component for post-processing outputs

Type:

PostProcessor | None

evaluator#

Component for computing metrics

Type:

Evaluator | None

visualizer#

Component for visualization

Type:

Visualizer | None

Example

Create a model with default components:

>>> model = AnomalibModule()

Create a model with custom components:

>>> from anomalib.pre_processing import PreProcessor
>>> from anomalib.post_processing import PostProcessor
>>> model = AnomalibModule(
...     pre_processor=PreProcessor(),
...     post_processor=PostProcessor(),
...     evaluator=True,
...     visualizer=True
... )

Disable certain components:

>>> model = AnomalibModule(
...     pre_processor=False,
...     post_processor=False,
...     evaluator=False,
...     visualizer=False
... )
classmethod checkpoint_safe_globals()#

Model-specific types persisted in hyper_parameters.

Override in subclasses that save non-shared enums (or similar) into checkpoints. Keep this to small first-party types only; shared enums belong in ANOMALIB_SAFE_GLOBALS.

Returns:

Extra types to allowlist under weights_only=True.

Return type:

Sequence[Any]

configure_callbacks()#

Configure callbacks for the model.

Returns:

List of callbacks including components

that inherit from Callback

Return type:

Sequence[Callback] | Callback

Example

>>> model = AnomalibModule()
>>> callbacks = model.configure_callbacks()
>>> isinstance(callbacks, (Sequence, Callback))
True
static configure_evaluator()#

Configure the default evaluator.

The default evaluator includes metrics for both image-level and pixel-level evaluation. Override this method to provide custom metrics for the model.

Returns:

Configured evaluator with default metrics

Return type:

Evaluator

Example

>>> evaluator = AnomalibModule.configure_evaluator()
>>> isinstance(evaluator, Evaluator)
True
configure_post_processor()#

Configure the default post-processor.

The default post-processor is based on the model’s learning type. Override this method to provide a custom post-processor for the model.

Returns:

Configured post-processor based on learning type

Return type:

PostProcessor | None

Raises:

NotImplementedError – If no default post-processor exists for the model’s learning type

Example

>>> model = AnomalibModule()
>>> post_processor = model.configure_post_processor()
>>> isinstance(post_processor, PostProcessor)
True
static configure_pre_processor(image_size=None)#

Configure the default pre-processor.

The default pre-processor resizes images and normalizes using ImageNet statistics. Override this method to provide a custom pre-processor for the model.

Parameters:

image_size (tuple[int, int] | None) – Target size for resizing. Defaults to (256, 256).

Returns:

Configured pre-processor

Return type:

PreProcessor

Example

>>> preprocessor = AnomalibModule.configure_pre_processor((512, 512))
>>> isinstance(preprocessor, PreProcessor)
True
classmethod configure_visualizer()#

Configure the default visualizer.

Override this method to provide a custom visualizer for the model.

Returns:

Default image visualizer instance

Return type:

ImageVisualizer

Example

>>> visualizer = AnomalibModule.configure_visualizer()
>>> isinstance(visualizer, ImageVisualizer)
True
forward(batch, *args, **kwargs)#

Perform forward pass through the model pipeline.

The input batch is passed through: 1. Pre-processor (if configured) 2. Model 3. Post-processor (if configured)

Parameters:
  • batch (Tensor) – Input batch

  • *args – Additional positional arguments (unused)

  • **kwargs – Additional keyword arguments (unused)

Returns:

Processed batch with model predictions

Return type:

InferenceBatch

Example

>>> model = AnomalibModule()
>>> batch = torch.randn(1, 3, 256, 256)
>>> output = model(batch)
>>> isinstance(output, InferenceBatch)
True
classmethod from_config(config_path, **kwargs)#

Create a model instance from a configuration file.

Parameters:
  • config_path (str | Path) – Path to the model configuration file

  • **kwargs – Additional arguments to override config values

Returns:

Instantiated model

Return type:

AnomalibModule

Raises:
  • FileNotFoundError – If config file does not exist

  • ValueError – If instantiated model is not AnomalibModule

Example

>>> model = AnomalibModule.from_config("examples/configs/model/patchcore.yaml")
>>> isinstance(model, AnomalibModule)
True

Override config values: >>> model = AnomalibModule.from_config( … “examples/configs/model/patchcore.yaml”, … model__backbone=”resnet18” … )

property input_size: tuple[int, int] | None#

Get the effective input size of the model.

Returns:

Height and width of model input after

pre-processing, or None if size cannot be determined

Return type:

tuple[int, int] | None

Example

>>> model = AnomalibModule()
>>> model.input_size  # Returns size after pre-processing
(256, 256)
abstract property learning_type: LearningType#

Get learning type of the model.

Returns:

Type of learning (e.g. one-class, supervised)

Return type:

LearningType

Raises:

NotImplementedError – If not implemented by subclass

classmethod load_from_checkpoint(checkpoint_path, map_location=None, hparams_file=None, strict=None, weights_only=True, **kwargs)#

Load a model from a Lightning checkpoint.

Wraps lightning.pytorch.LightningModule.load_from_checkpoint() so first-party enums in hyper_parameters can unpickle under weights_only=True. Trainer ckpt_path restores use AnomalibCheckpointIO instead of this method.

Parameters:
  • checkpoint_path (str | Path) – Path to the checkpoint file.

  • map_location (Union[device, str, int, Callable[[UntypedStorage, str], Optional[UntypedStorage]], dict[Union[device, str, int], Union[device, str, int]], None]) – Device mapping passed to torch.load. Defaults to None.

  • hparams_file (str | Path | None) – Optional YAML/CSV file of hyperparameters. Defaults to None.

  • strict (bool | None) – Whether to strictly enforce state-dict key matching. Defaults to None.

  • weights_only (bool) – If True, restrict unpickling to tensors and allowlisted types. Defaults to True.

  • **kwargs – Extra or overriding hyperparameters passed to the model constructor.

Returns:

Model instantiated from the checkpoint.

Return type:

AnomalibModule

property name: str#

Get name of the model.

Returns:

Name of the model class

Return type:

str

on_load_checkpoint(checkpoint)#

Restore component configuration from safe plain data.

Return type:

None

on_save_checkpoint(checkpoint)#

Save safe component configuration and plain-data hyperparameters.

Return type:

None

predict_step(batch, batch_idx, dataloader_idx=0)#

Perform prediction step.

This method is called during the predict stage of training. It calls the model’s forward method to ensure consistency with exported model behavior, then merges the predictions into the batch for post-processing.

Parameters:
  • batch (Batch) – Input batch

  • batch_idx (int) – Index of the batch

  • dataloader_idx (int) – Index of the dataloader. Defaults to 0.

Returns:

Updated batch with model predictions

Return type:

Union[Tensor, Mapping[str, Any], None]

test_step(batch, batch_idx, *args, **kwargs)#

Perform test step.

This method is called during the test stage of training. It calls the model’s forward method to ensure consistency with exported model behavior, then merges the predictions into the batch for post-processing.

Parameters:
  • batch (Batch) – Input batch

  • batch_idx (int) – Index of the batch

  • *args – Additional positional arguments (unused)

  • **kwargs – Additional keyword arguments (unused)

Returns:

Updated batch with model predictions

Return type:

Union[Tensor, Mapping[str, Any], None]

abstract property trainer_arguments: dict[str, Any]#

Get trainer arguments specific to this model.

Returns:

Dictionary of trainer arguments

Return type:

dict[str, Any]

Raises:

NotImplementedError – If not implemented by subclass