Anomalib in 15 Minutes#
This section will walk you through the steps to train a model and use it to detect anomalies in a dataset.
Installation#
Anomalib can be installed from PyPI. We recommend using a virtual environment and a modern package installer like uv or pip.
Quick Install#
For a standard installation, you can use uv or pip. This will install the latest version of Anomalib with its core dependencies. PyTorch will be installed based on its default behavior, which usually works for CPU and standard CUDA setups.
# With uv
uv pip install anomalib
# Or with pip
pip install anomalib
For more control over the installation, such as specifying the PyTorch backend or installing extra dependencies, see the advanced options below.
Advanced: Install with Hardware-Specific Extras
To ensure compatibility with your hardware, you can specify a backend during installation. This is the recommended approach for production environments and for hardware other than CPU or standard CUDA.
Using uv:
# To ensure a specific hardware backend, use one of the following extras:
# CPU support (works on all platforms)
uv pip install "anomalib[cpu]"
# CUDA support (Linux/Windows with NVIDIA GPU)
uv pip install "anomalib[cu124]" # CUDA 12.4
uv pip install "anomalib[cu121]" # CUDA 12.1
uv pip install "anomalib[cu118]" # CUDA 11.8
# ROCm support (Linux with AMD GPU)
uv pip install "anomalib[rocm]"
# Intel XPU support (Linux/Windows with Intel GPU)
uv pip install "anomalib[xpu]"
# You can combine extras. For example, to install with CUDA 12.4 and OpenVINO support:
uv pip install "anomalib[openvino,cu124]"
# For a full installation with all optional dependencies on CPU:
uv pip install "anomalib[full,cpu]"
Using pip:
# To ensure a specific hardware backend, you must specify an extra.
# For example, for CPU:
pip install "anomalib[cpu]"
# Or for CUDA 12.4:
pip install "anomalib[cu124]"
# For a full installation with all optional dependencies on CPU:
pip install "anomalib[full,cpu]"
Training#
Anomalib supports both API and CLI-based training. The API is more flexible and allows for more customization, while the CLI training utilizes command line interfaces, and might be easier for those who would like to use anomalib off-the-shelf.
# 1. Import required modules
from anomalib.data import MVTecAD
from anomalib.deploy import ExportType
from anomalib.engine import Engine
from anomalib.models import Patchcore
# 2. Create a dataset
# MVTecAD is a popular dataset for anomaly detection
datamodule = MVTecAD(
root="./datasets/MVTecAD", # Path to download/store the dataset
category="bottle", # MVTec category to use
train_batch_size=32, # Number of images per training batch
eval_batch_size=32, # Number of images per validation/test batch
)
# 3. Initialize the model
# Patchcore is a good choice for beginners
model = Patchcore(
num_neighbors=6, # Override default model settings
)
# 4. Create the training engine
engine = Engine(
max_epochs=1, # Override default trainer settings
)
# 5. Train the model
# This produces a lightning model (.ckpt)
engine.fit(datamodule=datamodule, model=model)
# 6. Test the model performance
test_results = engine.test(datamodule=datamodule, model=model)
# 7. Export the model
# Different formats are available: Torch, OpenVINO, ONNX
engine.export(
model=model,
export_type=ExportType.OPENVINO,
)
# 1. Basic Training
# Train and test a model using default configuration on MVTecAD bottle (default category)
echo "Training with default configuration..."
anomalib train --model Patchcore --data anomalib.data.MVTecAD
# 2. Training with Basic Customization
# Customize basic parameters like batch size and epochs.
# For example `EfficientAd` requires a train batch size of 1
echo -e "\nTraining with custom parameters..."
anomalib train --model EfficientAd --data anomalib.data.MVTecAD \
--data.category hazelnut \
--data.train_batch_size 1 \
--trainer.max_epochs 200
# 3. Train with config file
# Train with a custom config file
echo -e "\nTraining with config file..."
anomalib train --config path/to/config.yaml
# 4. Export a trained model into OpenVINO
echo .e "\nExporting model into OpenVINO..."
anomalib export --model Patchcore \
--ckpt_path /path/to/model.ckpt \
--export_type OPENVINO
Inference#
Anomalib includes multiple inferencing scripts, including Torch, Lightning, Gradio, and OpenVINO inferencers to perform inference using the trained/exported model. Here we show an inference example using the Lightning inferencer.
Lightning Inference
# 1. Import required modules
from anomalib.data import PredictDataset
from anomalib.engine import Engine
from anomalib.models import Patchcore
# 2. Initialize the model and load weights
model = Patchcore()
engine = Engine()
# 3. Prepare test data
# You can use a single image or a folder of images
dataset = PredictDataset(
path="path/to/test/images",
image_size=(256, 256),
)
# 4. Get predictions
predictions = engine.predict(
model=model,
dataset=dataset,
ckpt_path="path/to/model.ckpt",
)
# 5. Access the results
if predictions is not None:
for prediction in predictions:
image_path = prediction.image_path
anomaly_map = prediction.anomaly_map # Pixel-level anomaly heatmap
pred_label = prediction.pred_label # Image-level label (0: normal, 1: anomalous)
pred_score = prediction.pred_score # Image-level anomaly score
#!/usr/bin/env bash
# shellcheck shell=bash
# Copyright (C) 2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# Getting Started with Anomalib Inference
# This example shows how to perform inference using Engine().predict() arguments.
echo "=== Anomalib Inference Examples ==="
echo -e "\n1. Basic Inference with Checkpoint Path"
echo "# Predict using a model checkpoint"
anomalib predict \
--ckpt_path "./results/efficient_ad/mvtecad/bottle/weights/model.ckpt" \
--data_path path/to/image.jpg
echo -e "\n2. Inference with Directory Path"
echo "# Predict on all images in a directory"
anomalib predict \
--ckpt_path "./results/efficient_ad/mvtecad/bottle/weights/model.ckpt" \
--data_path "./datasets/mvtecad/bottle/test"
echo -e "\n3. Inference with Datamodule"
echo "# Use a datamodule for inference"
anomalib predict \
--ckpt_path "./results/my_dataset/weights/model.ckpt" \
--datamodule.class_path anomalib.data.Folder \
--datamodule.init_args.name "my_dataset" \
--datamodule.init_args.root "./datasets/my_dataset" \
--datamodule.init_args.normal_dir "good" \
--datamodule.init_args.abnormal_dir "defect"
echo -e "\n4. Inference with Return Predictions"
echo "# Return predictions instead of saving to disk"
anomalib predict \
--ckpt_path "./results/efficient_ad/mvtecad/bottle/weights/model.ckpt" \
--data_path path/to/image.jpg \
--return_predictions
echo -e "\n=== Example Output ==="
echo '
GPU available: True (cuda), used: True
TPU available: False, using: 0 TPU cores
IPU available: False, using: 0 IPUs
HPU available: False, using: 0 HPUs
[2024-01-01 12:00:00][INFO][anomalib][predict]: Loading model from ./results/my_dataset/weights/model.ckpt
[2024-01-01 12:00:01][INFO][anomalib][predict]: Prediction started
[2024-01-01 12:00:02][INFO][anomalib][predict]: Predictions saved to ./results/my_dataset/predictions'
echo -e "\nNote: Replace paths according to your setup."
echo "The predictions will be saved in the results directory by default unless --return_predictions is used."
Torch Inference
# TorchInferencer is a legacy inferencer. Consider using Engine.predict() instead,
# which provides a more modern and feature-rich interface for model inference.
OpenVINO Inference
# 1. Import required modules
from anomalib.deploy import OpenVINOInferencer
# 2. Initialize the inferencer
inferencer = OpenVINOInferencer(
path="/path/to/openvino/model.bin",
)
# 4. Get predictions
predictions = inferencer.predict(
image="/path/to/image.png",
)
# 5. Access the results
if predictions is not None:
for prediction in predictions:
anomaly_map = prediction.anomaly_map # Pixel-level anomaly heatmap
pred_label = prediction.pred_label # Image-level label (0: normal, 1: anomalous)
pred_score = prediction.pred_score # Image-level anomaly score
Gradio Inference
Hyper-Parameter Optimization#
Anomalib supports hyper-parameter optimization using wandb and comet.ml. Here we show an example of hyper-parameter optimization using both comet and wandb.
# To perform hpo using wandb sweep
anomalib hpo --backend WANDB --sweep_config tools/hpo/configs/wandb.yaml
# To perform hpo using comet.ml sweep
anomalib hpo --backend COMET --sweep_config tools/hpo/configs/comet.yaml
# To be enabled in v1.1
Experiment Management#
Anomalib is integrated with various libraries for experiment tracking such as comet, tensorboard, and wandb through lighting loggers.
To run a training experiment with experiment tracking, you will need the following configuration file:
By using the configuration file above, you can run the experiment with the following command:
Benchmarking#
Anomalib provides a benchmarking tool to evaluate the performance of the anomaly detection models on a given dataset. The benchmarking tool can be used to evaluate the performance of the models on a given dataset, or to compare the performance of multiple models on a given dataset.
Each model in anomalib is benchmarked on a set of datasets, and the results are available in src/anomalib/models/<model_name>README.md. For example, the MVTecAD AD results for the Patchcore model are available in the corresponding README.md file.
To run the benchmarking tool, run the following command:
anomalib benchmark --config tools/benchmarking/benchmark_params.yaml
Reference#
If you use this library and love it, use this to cite it:
@inproceedings{akcay2022anomalib,
title={Anomalib: A deep learning library for anomaly detection},
author={
Akcay, Samet and
Ameln, Dick and
Vaidya, Ashwin and
Lakshmanan, Barath
and Ahuja, Nilesh
and Genc, Utku
},
booktitle={2022 IEEE International Conference on Image Processing (ICIP)},
pages={1706--1710},
year={2022},
organization={IEEE}
}