• Stars
    star
    479
  • Rank 91,752 (Top 2 %)
  • Language
    Python
  • License
    Apache License 2.0
  • Created over 2 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Towards Total Recall in Industrial Anomaly Detection

This repository contains the implementation for PatchCore as proposed in Roth et al. (2021), https://arxiv.org/abs/2106.08265.

It also provides various pretrained models that can achieve up to 99.6% image-level anomaly detection AUROC, 98.4% pixel-level anomaly localization AUROC and >95% PRO score (although the later metric is not included for license reasons).

defect_segmentation

For questions & feedback, please reach out to [email protected]!


Quick Guide

First, clone this repository and set the PYTHONPATH environment variable with env PYTHONPATH=src python bin/run_patchcore.py. To train PatchCore on MVTec AD (as described below), run

datapath=/path_to_mvtec_folder/mvtec datasets=('bottle' 'cable' 'capsule' 'carpet' 'grid' 'hazelnut'
'leather' 'metal_nut' 'pill' 'screw' 'tile' 'toothbrush' 'transistor' 'wood' 'zipper')
dataset_flags=($(for dataset in "${datasets[@]}"; do echo '-d '$dataset; done))


python bin/run_patchcore.py --gpu 0 --seed 0 --save_patchcore_model \
--log_group IM224_WR50_L2-3_P01_D1024-1024_PS-3_AN-1_S0 --log_online --log_project MVTecAD_Results results \
patch_core -b wideresnet50 -le layer2 -le layer3 --faiss_on_gpu \
--pretrain_embed_dimension 1024  --target_embed_dimension 1024 --anomaly_scorer_num_nn 1 --patchsize 3 \
sampler -p 0.1 approx_greedy_coreset dataset --resize 256 --imagesize 224 "${dataset_flags[@]}" mvtec $datapath

which runs PatchCore on MVTec images of sizes 224x224 using a WideResNet50-backbone pretrained on ImageNet. For other sample runs with different backbones, larger images or ensembles, see sample_training.sh.

Given a pretrained PatchCore model (or models for all MVTec AD subdatasets), these can be evaluated using

datapath=/path_to_mvtec_folder/mvtec
loadpath=/path_to_pretrained_patchcores_models
modelfolder=IM224_WR50_L2-3_P001_D1024-1024_PS-3_AN-1_S0
savefolder=evaluated_results'/'$modelfolder

datasets=('bottle'  'cable'  'capsule'  'carpet'  'grid'  'hazelnut' 'leather'  'metal_nut'  'pill' 'screw' 'tile' 'toothbrush' 'transistor' 'wood' 'zipper')
dataset_flags=($(for dataset in "${datasets[@]}"; do echo '-d '$dataset; done))
model_flags=($(for dataset in "${datasets[@]}"; do echo '-p '$loadpath'/'$modelfolder'/models/mvtec_'$dataset; done))

python bin/load_and_evaluate_patchcore.py --gpu 0 --seed 0 $savefolder \
patch_core_loader "${model_flags[@]}" --faiss_on_gpu \
dataset --resize 366 --imagesize 320 "${dataset_flags[@]}" mvtec $datapath

A set of pretrained PatchCores are hosted here: add link. To use them (and replicate training), check out sample_evaluation.sh and sample_training.sh.


In-Depth Description

Requirements

Our results were computed using Python 3.8, with packages and respective version noted in requirements.txt. In general, the majority of experiments should not exceed 11GB of GPU memory; however using significantly large input images will incur higher memory cost.

Setting up MVTec AD

To set up the main MVTec AD benchmark, download it from here: https://www.mvtec.com/company/research/datasets/mvtec-ad. Place it in some location datapath. Make sure that it follows the following data tree:

mvtec
|-- bottle
|-----|----- ground_truth
|-----|----- test
|-----|--------|------ good
|-----|--------|------ broken_large
|-----|--------|------ ...
|-----|----- train
|-----|--------|------ good
|-- cable
|-- ...

containing in total 15 subdatasets: bottle, cable, capsule, carpet, grid, hazelnut, leather, metal_nut, pill, screw, tile, toothbrush, transistor, wood, zipper.

"Training" PatchCore

PatchCore extracts a (coreset-subsampled) memory of pretrained, locally aggregated training patch features:

patchcore_architecture

To do so, we have provided bin/run_patchcore.py, which uses click to manage and aggregate input arguments. This looks something like

python bin/run_patchcore.py \
--gpu <gpu_id> --seed <seed> # Set GPU-id & reproducibility seed.
--save_patchcore_model # If set, saves the patchcore model(s).
--log_online # If set, logs results to a Weights & Biases account.
--log_group IM224_WR50_L2-3_P01_D1024-1024_PS-3_AN-1_S0 --log_project MVTecAD_Results results # Logging details: Name of the run & Name of the overall project folder.

patch_core  # We now pass all PatchCore-related parameters.
-b wideresnet50  # Which backbone to use.
-le layer2 -le layer3 # Which layers to extract features from.
--faiss_on_gpu # If similarity-searches should be performed on GPU.
--pretrain_embed_dimension 1024  --target_embed_dimension 1024 # Dimensionality of features extracted from backbone layer(s) and final aggregated PatchCore Dimensionality
--anomaly_scorer_num_nn 1 --patchsize 3 # Num. nearest neighbours to use for anomaly detection & neighbourhoodsize for local aggregation.

sampler # We now pass all the (Coreset-)subsampling parameters.
-p 0.1 approx_greedy_coreset # Subsampling percentage & exact subsampling method.

dataset # We now pass all the Dataset-relevant parameters.
--resize 256 --imagesize 224 "${dataset_flags[@]}" mvtec $datapath # Initial resizing shape and final imagesize (centercropped) as well as the MVTec subdatasets to use.

Note that sample_runs.sh contains exemplary training runs to achieve strong AD performance. Due to repository changes (& hardware differences), results may deviate slightly from those reported in the paper, but should generally be very close or even better. As mentioned previously, for re-use and replicability we have also provided several pretrained PatchCore models hosted at add link - download the folder, extract, and pass the model of your choice to bin/load_and_evaluate_patchcore.py which showcases an exemplary evaluation process.

During (after) training, the following information will be stored:

|PatchCore model (if --save_patchcore_model is set)
|-- models
|-----|----- mvtec_bottle
|-----|-----------|------- nnscorer_search_index.faiss
|-----|-----------|------- patchcore_params.pkl
|-----|----- mvtec_cable
|-----|----- ...
|-- results.csv # Contains performance for each subdataset.

|Sample_segmentations (if --save_segmentation_images is set)

In addition to the main training process, we have also included Weights-&-Biases logging, which allows you to log all training & test performances online to Weights-and-Biases servers (https://wandb.ai). To use that, include the --log_online flag and provide your W&B key in run_patchcore.py > --log_wandb_key.

Finally, due to the effectiveness and efficiency of PatchCore, we also incorporate the option to use an ensemble of backbone networks and network featuremaps. For this, provide the list of backbones to use (as listed in /src/anomaly_detection/backbones.py) with -b <backbone and, given their ordering, denote the layers to extract with -le idx.<layer_name>. An example with three different backbones would look something like

python bin/run_patchcore.py --gpu <gpu_id> --seed <seed> --save_patchcore_model --log_group <log_name> --log_online --log_project <log_project> results \

patch_core -b wideresnet101 -b resnext101 -b densenet201 -le 0.layer2 -le 0.layer3 -le 1.layer2 -le 1.layer3 -le 2.features.denseblock2 -le 2.features.denseblock3 --faiss_on_gpu \

--pretrain_embed_dimension 1024  --target_embed_dimension 384 --anomaly_scorer_num_nn 1 --patchsize 3 sampler -p 0.01 approx_greedy_coreset dataset --resize 256 --imagesize 224 "${dataset_flags[@]}" mvtec $datapath

When using --save_patchcore_model, in the case of ensembles, a respective ensemble of PatchCore parameters is stored.

Evaluating a pretrained PatchCore model

To evaluate a/our pretrained PatchCore model(s), run

python bin/load_and_evaluate_patchcore.py --gpu <gpu_id> --seed <seed> $savefolder \
patch_core_loader "${model_flags[@]}" --faiss_on_gpu \
dataset --resize 366 --imagesize 320 "${dataset_flags[@]}" mvtec $datapath

assuming your pretrained model locations to be contained in model_flags; one for each subdataset in dataset_flags. Results will then be stored in savefolder. Example model & dataset flags:

model_flags=('-p', 'path_to_mvtec_bottle_patchcore_model', '-p', 'path_to_mvtec_cable_patchcore_model', ...)
dataset_flags=('-d', 'bottle', '-d', 'cable', ...)

Expected performance of pretrained models

While there may be minor changes in performance due to software & hardware differences, the provided pretrained models should achieve the performances provided in their respective results.csv-files. The mean performance (particularly for the baseline WR50 as well as the larger Ensemble model) should look something like:

Model Mean AUROC Mean Seg. AUROC Mean PRO
WR50-baseline 99.2% 98.1% 94.4%
Ensemble 99.6% 98.2% 94.9%

Citing

If you use the code in this repository, please cite

@misc{roth2021total,
      title={Towards Total Recall in Industrial Anomaly Detection},
      author={Karsten Roth and Latha Pemula and Joaquin Zepeda and Bernhard SchΓΆlkopf and Thomas Brox and Peter Gehler},
      year={2021},
      eprint={2106.08265},
      archivePrefix={arXiv},
      primaryClass={cs.CV}
}

Security

See CONTRIBUTING for more information.

License

This project is licensed under the Apache-2.0 License.

More Repositories

1

mm-cot

Official implementation for "Multimodal Chain-of-Thought Reasoning in Language Models" (stay tuned and more will be updated)
Python
3,727
star
2

chronos-forecasting

Chronos: Pretrained (Language) Models for Probabilistic Time Series Forecasting
Python
2,202
star
3

auto-cot

Official implementation for "Automatic Chain of Thought Prompting in Large Language Models" (stay tuned & more will be updated)
Jupyter Notebook
1,218
star
4

siam-mot

SiamMOT: Siamese Multi-Object Tracking
Python
458
star
5

alexa-teacher-models

Python
362
star
6

bigdetection

BigDetection: A Large-scale Benchmark for Improved Object Detector Pre-training
Python
352
star
7

earth-forecasting-transformer

Official implementation of Earthformer
Jupyter Notebook
337
star
8

sccl

Pytorch implementation of Supporting Clustering with Contrastive Learning, NAACL 2021
Python
262
star
9

prompt-pretraining

Official implementation for the paper "Prompt Pre-Training with Over Twenty-Thousand Classes for Open-Vocabulary Visual Recognition"
Python
250
star
10

RefChecker

RefChecker provides automatic checking pipeline and benchmark dataset for detecting fine-grained hallucinations generated by Large Language Models.
Python
235
star
11

esci-data

Shopping Queries Dataset: A Large-Scale ESCI Benchmark for Improving Product Search
Python
154
star
12

video-contrastive-learning

Video Contrastive Learning with Global Context, ICCVW 2021
Python
146
star
13

tgl

Python
143
star
14

gan-control

This package provides a pythorch implementation of "GAN-Control: Explicitly Controllable GANs", ICCV 2021.
Jupyter Notebook
122
star
15

polygon-transformer

Python
120
star
16

ReFinED

ReFinED is an efficient and accurate entity linking (EL) system.
Python
116
star
17

tanl

Structured Prediction as Translation between Augmented Natural Languages
Python
113
star
18

unconditional-time-series-diffusion

Official PyTorch implementation of TSDiff models presented in the NeurIPS 2023 paper "Predict, Refine, Synthesize: Self-Guiding Diffusion Models for Probabilistic Time Series Forecasting"
Python
112
star
19

crossnorm-selfnorm

CrossNorm and SelfNorm for Generalization under Distribution Shifts, ICCV 2021
Python
111
star
20

cceval

CrossCodeEval: A Diverse and Multilingual Benchmark for Cross-File Code Completion (NeurIPS 2023)
Python
109
star
21

wqa_tanda

This repo provides code and data used in our TANDA paper.
106
star
22

spot-diff

Project for <SPot-the-Difference Self-Supervised Pre-training for Anomaly Detection and Segmentation> (ECCV 2022)
Python
101
star
23

mintaka

Dataset from the paper "Mintaka: A Complex, Natural, and Multilingual Dataset for End-to-End Question Answering" (COLING 2022)
Python
101
star
24

mix-generation

MixGen: A New Multi-Modal Data Augmentation
Python
100
star
25

long-short-term-transformer

[NeurIPS 2021 Spotlight] Official implementation of Long Short-Term Transformer for Online Action Detection
Python
100
star
26

alexa-arena

Python
99
star
27

fraud-dataset-benchmark

Repository for Fraud Dataset Benchmark
Jupyter Notebook
96
star
28

glass-text-spotting

Official implementation for "GLASS: Global to Local Attention for Scene-Text Spotting" (ECCV'22)
Python
94
star
29

meta-q-learning

Code for the paper "Meta-Q-Learning"( ICLR 2020)
Python
92
star
30

exponential-moving-average-normalization

PyTorch implementation of EMAN for self-supervised and semi-supervised learning: https://arxiv.org/abs/2101.08482
Python
91
star
31

co-with-gnns-example

HTML
88
star
32

datatuner

Code related to "Have Your Text and Use It Too! End-to-End Neural Data-to-Text Generation with Semantic Fidelity" paper
Python
87
star
33

mxeval

Python
84
star
34

sentence-representations

Python
77
star
35

CodeSage

CodeSage: Code Representation Learning At Scale (ICLR 2024)
Python
75
star
36

semimtr-text-recognition

Multimodal Semi-Supervised Learning for Text Recognition (SemiMTR)
Python
75
star
37

fact-check-summarization

Python
72
star
38

instruct-video-to-video

Python
69
star
39

tabsyn

Official Implementations of "Mixed-Type Tabular Data Synthesis with Score-based Diffusion in Latent Space""
Python
68
star
40

object-centric-learning-framework

Python
67
star
41

omni-detr

PyTorch implementation of Omni-DETR for omni-supervised object detection: https://arxiv.org/abs/2203.16089
Python
64
star
42

progressive-coordinate-transforms

Progressive Coordinate Transforms for Monocular 3D Object Detection, NeurIPS 2021
Python
63
star
43

FeatGraph

Python
62
star
44

small-baseline-camera-tracking

A dataset to facilitate the research of Structure-from-Motion (SfM) for movie and TV shows.
61
star
45

tubelet-transformer

This is an official implementation of TubeR: Tubelet Transformer for Video Action Detection
Python
59
star
46

embert

Code for EmBERT, a transformer model for embodied, language-guided visual task completion.
Python
52
star
47

RAGChecker

RAGChecker: A Fine-grained Framework For Diagnosing RAG
Python
52
star
48

probconserv

Datasets and code for results presented in the ProbConserv paper
Python
50
star
49

semi-vit

PyTorch implementation of Semi-supervised Vision Transformers
Python
48
star
50

qa-dataset-converter

Code from the paper "What do Models Learn from Question Answering Datasets?" (EMNLP 2020)
Python
48
star
51

masked-diffusion-lm

Official implementation for the paper "A Cheaper and Better Diffusion Language Model with Soft-Masked Noise"
Python
48
star
52

transformer-gan

Python
47
star
53

transformers-data-augmentation

Code associated with the "Data Augmentation using Pre-trained Transformer Models" paper
Python
46
star
54

gluonmm

A library of transformer models for computer vision and multi-modality research
Python
46
star
55

crossmodal-contrastive-learning

CrossCLR: Cross-modal Contrastive Learning For Multi-modal Video Representations, ICCV 2021
Python
45
star
56

recode

Releasing code for "ReCode: Robustness Evaluation of Code Generation Models"
Python
44
star
57

tracking-dataset

Python
44
star
58

dstc11-track2-intent-induction

DSTC 11 Track 2: Intent Induction from Conversations for Task-Oriented Dialogue
Python
43
star
59

dse

Python
43
star
60

dq-bart

DQ-BART: Efficient Sequence-to-Sequence Model via Joint Distillation and Quantization (ACL 2022)
Python
43
star
61

gnn-tail-generalization

Python
43
star
62

auto-rag-eval

Code repo for the ICML 2024 paper "Automated Evaluation of Retrieval-Augmented Language Models with Task-Specific Exam Generation"
Python
42
star
63

boon

Datasets and code for results presented in the BOON paper
Jupyter Notebook
41
star
64

proteno

This repository contains data used in the NAACL 2021 Paper - Proteno: Text Normalization with Limited Data for Fast Deployment in Text to Speech Systems (https://arxiv.org/abs/2104.07777)
40
star
65

fact-graph

Implementation of the paper "FactGraph: Evaluating Factuality in Summarization with Semantic Graph Representations (NAACL 2022)"
Python
39
star
66

c2f-seg

Official Implementation for ICCV'23 paper Coarse-to-Fine Amodal Segmentation with Shape Prior (C2F-Seg).
Python
38
star
67

amazon-multilingual-counterfactual-dataset

37
star
68

QA-ViT

Python
37
star
69

indoor-scene-generation-eai

Jupyter Notebook
36
star
70

long-tailed-ood-detection

Official implementation for "Partial and Asymmetric Contrastive Learning for Out-of-Distribution Detection in Long-Tailed Recognition" (ICML'22 Long Presentation)
Python
36
star
71

efficient-longdoc-classification

Python
35
star
72

object-centric-multiple-object-tracking

Python
34
star
73

hyperbolic-embeddings

Code for hyperboloid embeddings for knowledge graph entities
Python
33
star
74

domain-knowledge-injection

Python
33
star
75

azcausal

Causal Inference in Python
Python
32
star
76

Repoformer

Repoformer: Selective Retrieval for Repository-Level Code Completion (ICML 2024)
Python
32
star
77

ContraCLM

[ACL 2023] Code for ContraCLM: Contrastive Learning For Causal Language Model
Python
31
star
78

unified-ept

A Unified Efficient Pyramid Transformer for Semantic Segmentation, ICCVW 2021
Python
29
star
79

robust-tableqa

Two approaches for robust TableQA: 1) ITR is a general-purpose retrieval-based approach for handling long tables in TableQA transformer models. 2) LI-RAGE is a robust framework for open-domain TableQA which addresses several limitations. (ACL 2023)
Python
29
star
80

bold

Dataset associated with "BOLD: Dataset and Metrics for Measuring Biases in Open-Ended Language Generation" paper
27
star
81

replay-based-recurrent-rl

Code for "Task-Agnostic Continual RL: In Praise of a Simple Baseline"
Python
26
star
82

controlling-llm-memorization

Python
25
star
83

carbon-assessment-with-ml

CaML: Carbon Footprinting of Household Products with Zero-Shot Semantic Text Similarity
Jupyter Notebook
25
star
84

peft-design-spaces

Official implementation for "Parameter-Efficient Fine-Tuning Design Spaces"
Python
24
star
85

llm-interpret

Code for the ACL 2023 paper: "Rethinking the Role of Scale for In-Context Learning: An Interpretability-based Case Study at 66 Billion Scale"
Python
24
star
86

creating-and-correcting-novel-ml-model-errors

Jupyter Notebook
24
star
87

BartGraphSumm

Implementation of the paper "Efficiently Summarizing Text and Graph Encodings of Multi-Document Clusters (NAACL 2021)"
Python
23
star
88

tofueval

23
star
89

wqa-cascade-transformers

21
star
90

textadain-robust-recognition

TextAdaIN: Paying Attention to Shortcut Learning in Text Recognizers
Python
21
star
91

multiatis

Data and code for the paper "End-to-End Slot Alignment and Recognition for Cross-Lingual NLU" (Accepted to EMNLP 2020)
Python
20
star
92

iwslt-autodub-task

Python
20
star
93

street-reasoning

STREET: a multi-task and multi-step reasoning dataset
Python
19
star
94

contrastive-controlled-mt

Code and data for the IWSLT 2022 shared task on Formality Control for SLT
Ruby
19
star
95

pizza-semantic-parsing-dataset

The PIZZA dataset continues the exploration of task-oriented parsing by introducing a new dataset for parsing pizza and drink orders, whose semantics cannot be captured by flat slots and intents.
Python
19
star
96

redset

Redset is a dataset containing three months worth of user query metadata that ran on a selected sample of instances in the Amazon Redshift fleet. We provide query metadata for 200 provisioned and serverless instances each.
19
star
97

fast-rl-with-slow-updates

Jupyter Notebook
18
star
98

few-shot-baseline

Python
17
star
99

doc-mt-metrics

Python
17
star
100

normalizer-free-robust-training

Official implementation of "Removing Batch Normalization Boosts Adversarial Training" (ICML'22)
Python
17
star