Image Anomaly Detection with PyTorch using Intel® Transfer Learning Tool¶
This notebook demonstrates anomaly detection using the Intel Transfer Learning Toolkit. It performs defect analysis with the MVTec dataset using PyTorch. The workflow uses a pretrained ResNet50 v1.5 model from torchvision.
Intel® Gaudi® AI accelerator¶
To use HPU training and inference with Gaudi, follow these steps to install required HPU drivers and software from README or the official Habana Docs
1. Import dependencies and setup parameters¶
This notebook assumes that you have already followed the instructions to setup a PyTorch environment with all the dependencies required to run the notebook.
[ ]:
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import PIL.Image as Image
import torch, torchvision
from torchvision.transforms.functional import InterpolationMode
import requests
from io import BytesIO
# tlt imports
from tlt.datasets import dataset_factory
from tlt.models import model_factory
from tlt.utils.file_utils import download_and_extract_tar_file, download_file
# Specify a directory for the dataset to be downloaded
dataset_dir = os.environ["DATASET_DIR"] if "DATASET_DIR" in os.environ else \
os.path.join(os.environ["HOME"], "dataset")
# Specify a directory for output
output_dir = os.environ["OUTPUT_DIR"] if "OUTPUT_DIR" in os.environ else \
os.path.join(os.environ["HOME"], "output")
print("Dataset directory:", dataset_dir)
print("Output directory:", output_dir)
2. Get or load the model¶
In this step, we use the model factory to get the desired model. The get_model
function returns a pretrained model object from a public model hub, while the load_model
function loads a pretrained model from a checkpoint on your local disk or in memory.
Here we are getting the pretrained resnet50
model from Torchvision:
[ ]:
model_factory.print_supported_models(framework="pytorch", use_case="anomaly_detection", verbose = False,
markdown=False)
[ ]:
# Set device="hpu" to use Gaudi. If no HPU hardware or installs are detected, device will default to "cpu"
model = model_factory.get_model(model_name="resnet50", framework="pytorch", use_case='anomaly_detection', device="cpu")
To load a previously trained model from a file, use this:
model = model_factory.load_model(model_name="resnet50", model=<PATH_TO_MODEL_FILE>, framework="pytorch",
use_case='anomaly_detection')
3. Get the dataset¶
To use MVTec or your own image dataset for anomaly detection, your image files (.jpg
or .png
) should be arranged in one of two ways.
Method 1: Category Folders¶
Arrange them in folders in the root dataset directory like this:
hazelnut
└── crack
└── cut
└── good
└── hole
└── print
IMPORTANT: There must be a subfolder named good
and at least one other folder of defective examples. It does not matter what the names of the other folders are or how many there, as long as there is at least one. This would also be an acceptable Method 1 layout:
toothbrush
└── defective
└── good
TLT will encode all of the non-good images as “bad” and use the “good” images in the training set and a mix of good and bad images in the validation set.
Method 2: Train & Test Folders with Category Subfolders¶
Arrange them in folders in the root dataset directory like this:
hazelnut
└── train
└── good
└── test
└── crack
└── cut
└── good
└── hole
└── print
When using this layout, TLT will use the exact defined split for train and validation subsets unless you use the shuffle_split
method to re-shuffle and split up the “good” images with certain percentages.
[ ]:
img_dir = os.path.join(dataset_dir, 'hazelnut')
[ ]:
dataset = dataset_factory.load_dataset(img_dir,
use_case='image_anomaly_detection',
framework="pytorch")
print(dataset._dataset)
print("Class names:", str(dataset.class_names))
print("Defect names:", dataset.defect_names)
Note: The defects argument can be used to filter the validation set to use only a subset of defect types. For example:
dataset = dataset_factory.load_dataset(img_dir,
use_case='image_anomaly_detection',
framework="pytorch",
defects=['crack', 'hole'])
4. Prepare the dataset¶
Once you have your dataset, use the following cells to split and preprocess the data. We split them into training and test subsets, then resize the images to match the selected model, and then batch the images. Pass in optional arguments to customize the Resize or Normalize transforms. Data augmentation can be applied to the
training set by specifying the augmentations to be applied in the add_aug
parameter. Supported augmentations are given below: 1. hflip - RandomHorizontalFlip 2. rotate - RandomRotate
[ ]:
# If using Method 1 layout, split the dataset into training and test subsets.
if dataset._validation_type is None:
dataset.shuffle_split(train_pct=.75, val_pct=0.0, test_pct=0.25)
For cutpaste feature extractor, cutpaste_type can be specified in the dataset.preprocess() method as follows. The option available are - normal, scar, 3way and union. Default is normal.
dataset.preprocess(224, batch_size=batch_size, interpolation=InterpolationMode.LANCZOS, cutpaste_type='normal')
[ ]:
# Preprocess with an image size that matches the model, batch size 32, and the desired interpolation method
batch_size = 64
cutpaste_type = 'normal'
dataset.preprocess(image_size=224, batch_size=batch_size, interpolation=InterpolationMode.LANCZOS, cutpaste_type=cutpaste_type)
5. Visualize samples from the dataset¶
We get a single batch from our training and test subsets and visualize the images as a sanity check.
[ ]:
def plot_images(images, labels, sup_title, predictions=None):
plt.figure(figsize=(18,14))
plt.subplots_adjust(hspace=0.5)
for n in range(min(batch_size, 30)):
plt.subplot(6,5,n+1)
inp = images[n]
inp = inp.numpy().transpose((1, 2, 0))
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
inp = std * inp + mean
inp = np.clip(inp, 0, 1)
plt.imshow(inp)
if predictions:
correct_prediction = labels[n] == predictions[n]
color = "darkgreen" if correct_prediction else "crimson"
title = predictions[n] if correct_prediction else "{}".format(predictions[n])
else:
good_sample = labels[n] == 'good'
color = "darkgreen" if labels[n] == 'good' else ("crimson" if labels[n] == 'bad' else "black")
title = labels[n]
plt.title(title, fontsize=14, color=color)
plt.axis('off')
_ = plt.suptitle(sup_title, fontsize=20)
plt.show()
[ ]:
# Plot some images from the training set
images, labels = dataset.get_batch()
labels = [dataset.class_names[id] for id in labels]
plot_images(images, labels, 'Training Samples')
[ ]:
# Plot some images from the test set
images, labels = dataset.get_batch(subset='test')
labels = [dataset.class_names[id] for id in labels]
plot_images(images, labels, 'Test Samples')
6. Training and Evaluation¶
This step calls the model’s train function with the dataset that was just prepared. The training function will get the torchvision feature extractor for the user’s desired layer and extract features from the training set. The extracted features are used to perform a principal component analysis. The model’s evaluate function returns the AUROC metric (area under the roc curve) calculated from the dataset’s test subset.
Feature Extraction¶
There are three feature extractor options available within the model.train()
function. 1. No fine-tuning - To use a pretrained ResNet50/ResNet18 model for feature extraction, simply do not change the default simsiam=False
input argument. 2. SimSiam - A self-supervised neural network based on Siamese networks. It learns a meaningful representation of dataset without using any labels. If selected, SimSiam generates quality features that can help
differentiate between regular and anomaly images in a given context. SimSiam produces two different augmented images from one underlying image. The end goal is to train the network to produce the same features for both images. It takes a ResNet model as the backbone and fine-tunes the model on the augmented dataset to get a better feature embedding. To use this feature extractor, download the SimSiam weights based on ResNet50 -
https://dl.fbaipublicfiles.com/simsiam/models/100ep-256bs/pretrain/checkpoint_0099.pth.tar - set simsiam=True
, and set initial_checkpoints
to the path of the downloaded checkpoints in the model.train()
function. 3. Cut-paste - A self-supervised method for Anomaly Detection and Localization that takes ResNet50/ ResNet18 model as backbone and fine-tune the model on custom dataset to get better feature embedding. data augmentation strategy that
cuts an image patch and pastes at a random location of a large image. To use this feature extractor, set cutpaste=True
in the model.train()
function.
Optional: The SimSiam TwoCropTransform¶
To train a Simsiam model, it is required to apply a TwoCropTransform augmentation technique on the dataset used for training. You can preview this augmentation on a sample batch after preprocessing by using get_batch(simsiam=True)
and then use them for simsiam training by using simsiam=True
in model.train()
also.
[ ]:
# Get a batch of training data with the simsiam transform applied to it
simsiam_images, _ = dataset.get_batch(simsiam=True)
# Plot the "A" samples showing the first set of augmented images
plot_images(simsiam_images[0], ['{}A'.format(i) for i in range(batch_size)], 'SimSiam "A" Samples')
[ ]:
# Now plot the "B" samples showing the second set of augmented images based on the same underlying originals
plot_images(simsiam_images[1], ['{}B'.format(i) for i in range(batch_size)], 'SimSiam "B" Samples')
Optional: The Cut-paste Transforms¶
To train a model with Cut-paste , it is required to apply one of the four augmentations - CutPasteNormal, CutPasteScar, CutPaste3Way, CutPasteUnion on the dataset used for training. You can preview this augmentation on a sample batch after preprocessing by using get_batch(cutpaste=True)
and then use them for cutpaste training by using cutpaste=True
in model.train()
also.
[ ]:
# Get a batch of training data with the cutpaste transform applied to it
cutpaste_images, _ = dataset.get_batch(cutpaste=True)
# Plot the "A" samples showing the first set of augmented images
plot_images(cutpaste_images[1], ['{}A'.format(i) for i in range(batch_size)], 'CutPaste "A" Samples')
[ ]:
if cutpaste_type == '3way':
# Now plot the "B" samples showing the third set of augmented images based on the same underlying originals
plot_images(cutpaste_images[2], ['{}B'.format(i) for i in range(batch_size)], 'CutPaste "B" Samples')
There is no fine-tuning being demonstrated here, but you can use simsiam
or cutpaste
if desired.
To use simsiam, set simsiam=True
and pass the checkpoint file to model.train()
as follows
pca_components, trained_model = model.train(dataset, output_dir, epochs=2, feature_dim=1000,
pred_dim=250, initial_checkpoints=<PATH_TO_CHECKPOINTS_FILE>,
pooling='avg', kernel_size=2, pca_threshold=0.99, simsiam=True,
generate_checkpoints=False, precision='float32')
To use cutpaste, set cutpaste=True
. Optionally, to load a pretrained checkpoint pass the checkpoint file to model.train()
as follows.
pca_components, trained_model = model.train(dataset, output_dir, optim='sgd', epochs=2, freeze_resnet=20,
head_layer=2, cutpaste_type='normal', initial_checkpoints=<PATH_TO_CHECKPOINTS_FILE>,
pooling='avg', kernel_size=2, pca_threshold=0.99, cutpaste=True,
generate_checkpoints=False, precision='float32')
Train Arguments¶
Required¶
dataset (ImageAnomalyDetectionDataset, required): Dataset to use when training the model
output_dir (str): Path to a writeable directory
Optional¶
generate_checkpoints (bool): Whether to save/preserve the best weights during SimSiam training (default: True)
initial_checkpoints (str): The path to a starting weights file
layer_name (str): The layer name whose output is desired for the extracted features
pooling (str): Pooling to be applied on the extracted layer (‘avg’ or ‘max’) (default: ‘avg’)
kernel_size (int): Kernel size in the pooling layer (default: 2)
pca_threshold (float): Threshold to apply to PCA model (default: 0.99)
ipex_optimize (bool): Use Intel Extension for PyTorch for fine-turning (default: True)
enable_auto_mixed_precision (bool or None): Enable auto mixed precision for fine-tuning. Mixed precision uses both 16-bit and 32-bit floating point types to make training run faster and use less memory. It is recommended to enable auto mixed precision training when running on platforms that support bfloat16 (Intel third or fourth generation Xeon processors). If it is enabled on a platform that does not support bfloat16, it can be detrimental to the training performance. If enable_auto_mixed_precision is set to None, auto mixed precision will be automatically enabled when running with Intel fourth generation Xeon processors, and disabled for other platforms. (default: None)
device (str): Enter
"cpu"
or"hpu"
to specify which hardware device to run training on. Ifdevice="hpu"
is specified, but no HPU hardware or installs are detected, CPU will be used. (default: “cpu”)
Note: refer to release documentation for an up-to-date list of train arguments and their current descriptions
[ ]:
# Examine the model's layers and decide which to use for feature extraction
model.list_layers(verbose=False)
layer = 'layer3'
[ ]:
pca_components, trained_model = model.train(dataset, output_dir, epochs=2, layer_name=layer,
seed=None, pooling='avg', kernel_size=2, pca_threshold=0.99)
[ ]:
threshold, auroc = model.evaluate(dataset, pca_components, use_test_set=True)
7. Predict¶
Using the same batch of test samples from above, get and view the model’s predictions.
[ ]:
predictions = model.predict(images, pca_components, return_type='class', threshold=threshold)
[ ]:
plot_images(images, labels, 'Predictions', predictions=predictions)
print("Correct predictions are shown in green")
print("Incorrect predictions are shown in red")
accuracy = sum([1 if p==labels[i] else 0 for i, p in enumerate(predictions)])/len(predictions)
print("Accuracy: {}".format(accuracy))
8. Export¶
[ ]:
saved_model_dir = model.export(os.path.join(output_dir, 'anomaly'))
9. Post-training quantization¶
In this section, the tlt
API uses Intel® Neural Compressor (INC) to benchmark and quantize the feature extraction model to get optimal inference performance.
Please note that Benchmark and Quantization is only compatible with CPU models at this time, due to the IPEX backend
We use the Intel Neural Compressor to benchmark the full precision model to see how it performs, as our baseline.
Note that there is a known issue when running Intel Neural Compressor from a notebook that you may sometimes see the error
zmq.error.ZMQError: Address already in use
. If you see this error, rerun the cell again.
[ ]:
results = model.benchmark(dataset=dataset)
Next we use Intel Neural Compressor to automatically search for the optimal quantization recipe for low-precision model inference. Running post-training quantization may take several minutes, depending on your hardware.
[ ]:
inc_output_dir = os.path.join(output_dir, 'quantized_models', model.model_name,
os.path.basename(saved_model_dir))
model.quantize(inc_output_dir, dataset=dataset)
Let’s benchmark using the quantized model, so that we can compare the performance to the full precision model that was originally benchmarked.
[ ]:
quantized_results = model.benchmark(dataset=dataset, saved_model_dir=inc_output_dir)
Dataset Citations¶
Paul Bergmann, Kilian Batzner, Michael Fauser, David Sattlegger, Carsten Steger: The MVTec Anomaly Detection Dataset: A Comprehensive Real-World Dataset for Unsupervised Anomaly Detection; in: International Journal of Computer Vision 129(4):1038-1059, 2021, DOI: 10.1007/s11263-020-01400-4.
Paul Bergmann, Michael Fauser, David Sattlegger, Carsten Steger: MVTec AD — A Comprehensive Real-World Dataset for Unsupervised Anomaly Detection; in: IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), 9584-9592, 2019, DOI: 10.1109/CVPR.2019.00982.