EfficientAD: Accurate Visual Anomaly Detection at Millisecond-Level Latencies
Paper · 2023 · Kilian Batzner, Lars Heckler and Rebecca Konig
Summary
An inspection system may have to flag a defective part before the next part reaches the camera. It may also have to learn from a collection of good parts, since the defects that will appear in production are unknown when the system is built. EfficientAD addresses these problems together. It learns what ordinary inspection images look like, assigns a score to a new image, and produces a map showing where the evidence for an anomaly lies. It is designed to catch both visible damage, such as a stain, and mistakes in how otherwise ordinary components are arranged.
The method starts with a compact network that describes small patches of an image. A fixed copy of this network acts as a teacher. A student learns to predict the teacher’s features on normal images, with training concentrated on the feature values it currently predicts least well. An additional penalty discourages the student from carrying that imitation over to unrelated images. At test time, a patch receives a high score when the student and teacher disagree. The authors measured feature extraction at less than 800 µs for a 256×256 image on an NVIDIA RTX A6000 GPU.
Some defects are apparent only when the image is considered as a whole. An extra cable, for instance, can look ordinary wherever it passes through a small patch. EfficientAD therefore adds an autoencoder, a network that compresses the whole image and reconstructs a grid of features from that compressed representation. The patch-based student also learns to predict the autoencoder’s output on good examples, including its usual reconstruction errors. Disagreement between these predictions and the autoencoder provides a separate signal for unexpected arrangements. Scores from held-out normal images put the two maps on comparable scales before they are combined.
Across 32 industrial inspection scenarios, EfficientAD-S and EfficientAD-M achieved mean image-level AU-ROC scores of 95.4% and 96.0%, respectively, compared with 92.4% for the strongest baseline by that measure. These scores measure how well the methods rank anomalous images above normal ones. The two variants also led on the main aggregate measure of defect localization. On the RTX A6000, EfficientAD-S produced an anomaly map in 2.2 ms per image in the single-image test and processed 614 images per second in the batched test. EfficientAD-M took 4.5 ms per image and gave the stronger aggregate detection and localization results. The authors identify fine dimensional errors, such as a screw that is slightly too long, as a remaining challenge.
Deep dive: EfficientAD: Accurate Visual Anomaly Detection at Millisecond-Level Latencies
EfficientAD detects and locates industrial defects by comparing local and whole-image features, with inference in milliseconds. · about 38 minutes to read
The problem and its context
Learning from acceptable products
Imagine building a system to inspect screws. The training images can show how acceptable screws look under the camera, including the variation in orientation that the inspection station normally sees. Preparing examples of every possible defect is a different task. A mark could occur on a part of the screw that nobody anticipated, and an unusual object could enter the image for the first time after installation. A detector trained from normal examples must learn enough about acceptable variation to give a low score to a good screw and enough about its regularities to give a high score to a departure.
The paper works with individual RGB or grayscale images. The prediction for an image comes from that image alone. This establishes what evidence the inspection method can use. A component can be identified as missing because of what surrounds its expected position in the current view, for instance. Evidence that would require comparing its movement across frames falls outside the task considered here. The authors distinguish this setting from work on surveillance sequences and from applications that use other imaging modalities.
The detector serves two purposes in the paper. The first is to assign an anomaly score to the whole image, which allows images to be ranked for inspection or classified at a chosen threshold. The second is to give a spatial account of the detection. A map can show whether the high score comes from a point on the product, from an unexpected arrangement, or from something unrelated in the background. It also makes it possible to use the size of a flagged region during postprocessing. An image-level decision alone leaves those possibilities open.
The available normal images can teach different kinds of regularities. Some concern appearance within a small area. A stain on a surface or a contaminant on a part can produce a texture or shape rarely seen there. Other regularities concern how ordinary features are combined. An assembly may permit a cable in a range of positions while requiring a particular number of cables. A detector that has learned the appearance of cable segments may accept the segments in a defective assembly individually. Recognizing the defect requires evidence about their joint presence.
The paper uses structural and logical to distinguish these cases. Structural anomalies include visible departures such as stains and scratches. Logical anomalies violate constraints on properties such as position, arrangement, count, or size. The distinction describes the reason a part is defective. How easy a defect is to see depends on the image representation as well. An unusual arrangement can produce a locally unusual patch, and a familiar-looking piece of material can be objectionable because of where it occurs. The architecture gives these sources of evidence separate ways to affect the final score.
Computational cost as part of the task
Industrial inspection imposes a time constraint alongside the requirement to recognize defects. A result that arrives late can leave too little time for the machinery to respond. Stations that process parts at a high rate can also lose capacity if inspection becomes the slow stage. The authors motivate the emphasis on response time with cases where recognizing a hazard only after it has reached a machine is of limited value. The experiments themselves use industrial image datasets to compare detectors.
The authors distinguish latency, the wait for a single result, from throughput, the rate at which many images can be handled. A system may process a batch efficiently while taking longer than an application can afford to return any individual result. Conversely, a fast individual prediction does not by itself establish what sustained rate is possible. The paper measures both because they describe different uses of the same hardware.
The paper describes several ways anomaly detectors had gained accuracy at a computational cost. Some combined separate predictors, some drew their features from large image classifiers, and some increased the input resolution to as much as 768×768 pixels. Each choice has a plausible benefit. Several predictors may contribute different evidence, a deep classifier may offer rich features, and a finer image grid can preserve small defects. Each also changes the amount of work needed during inspection. EfficientAD asks how much of that work can be replaced with choices made during training or with a more economical spatial representation.
Traditional machine-vision procedures already offered processing times suitable for many industrial tasks. In the earlier evaluation discussed by the authors, some such procedures became unreliable when their assumptions were violated, including assumptions about object alignment. Learned features offered a way to handle more variation in normal images. The paper’s approach retains the emphasis on low response time while using normal examples to define what the detector should accept.
What earlier detectors compared
One line of earlier work represented an image as a collection of feature vectors from a pretrained convolutional network. A feature vector is a list of measurements derived from part of an image. If the vector is associated with a spatial location, its degree of abnormality can be turned into a location score. Several methods then asked how unusual the feature was under a distribution fitted to normal images. The paper discusses approaches based on Gaussian distributions, on mixtures of Gaussians, and on normalizing flows.
A related approach keeps examples of normal features and asks how close a new feature is to those examples. PatchCore makes this strategy more practical by retaining a representative subset of the feature vectors collected during training. The reduced collection still has to be searched during inspection. The cost of extracting a query feature and the cost of finding its neighbors both contribute to the time required for a result. FastFlow, another baseline in the study, represents the alternative family that estimates feature density with flows.
Student–teacher detection replaces the feature database with a learned prediction. A fixed teacher extracts features, and a student is trained to reproduce them on acceptable images. A mismatch at test time can indicate a departure from what the student learned. The difficulty is that a student good at prediction may also predict well on some defects. Earlier approaches addressed this with choices such as fusing predictions at several scales or making the teacher and student architecturally different. AST, for instance, uses an invertible teacher as part of its approach to asymmetric student–teacher networks.
Reconstruction methods ask a different question. If a network learns to compress and reconstruct good examples, departures might become visible where its reconstruction of an anomalous image fails. This idea is complicated by the fact that normal images can also be difficult to reconstruct. Blurred texture can yield a conspicuous error in an otherwise acceptable region. GCAD addresses this by reconstructing features of a pretrained network. The paper also describes earlier work on memory in reconstruction, including a memory-augmented autoencoder.
Other methods create examples of unusual features during training. DSR creates synthetic anomalies in the latent space of a pretrained autoencoder, where a latent space is the internal representation used by the network. SimpleNet generates synthetic examples in a pretrained feature space and trains a discriminator to recognize them. These approaches differ in how they create evidence of abnormality when real defects are unavailable for training. EfficientAD instead uses normal-image prediction errors and a separate penalty on unrelated images, alongside reconstruction of normal whole-image features.
The method, step by step
What the detector compares
EfficientAD makes two comparisons for each image. In the first, the teacher and student both operate on small neighborhoods, and their disagreement measures how unfamiliar a patch looks. In the second, the student again works from small neighborhoods, but the other network has compressed the whole image before making its prediction. Their disagreement measures where a prediction informed by the full scene departs from what would ordinarily be expected from the local patch. Both comparisons produce spatial maps, so their results can be aligned and combined.
The networks that make all these predictions acquire their roles at different times. A deep classifier supplies feature targets to train the compact teacher on general images. The teacher is then fixed. For a particular inspection scenario, normal images train the student and the autoencoder. Held-out normal images provide the statistics that scale their discrepancy maps. A test image then passes through the fixed networks and receives scores using those stored statistics. The heavy classifier participates only in preparing the teacher.
EfficientAD from teacher preparation to test scoring
The steps in order.
Compact features with a defined location
The patch description network, or PDN, gives each feature vector a restricted field of view. For EfficientAD-S, the network contains four convolutional layers and a feature vector depends on a 33×33 patch of input pixels. The receptive field is the set of input positions that can affect a particular output. As the receptive field moves across the image, the network produces a grid of feature vectors. Because the network is fully convolutional, it computes the grid in one forward pass, sharing work across the overlapping neighborhoods.
Convolutions apply learned filters at many spatial positions. Their cost depends on how many times the filters are applied as well as how many weights the filters contain. The PDN reduces the spatial dimensions of the intermediate feature maps early. It uses strided average pooling after each of its first two convolutions. Average pooling replaces a local group of values with their mean, and a stride advances the pooling window by more than one position at a time. The layers that follow consequently do their work on smaller grids. This design follows the paper’s discussion of early downsampling in classification architectures such as Deep Residual Learning for Image Recognition.
In the padded EfficientAD-S specification, the teacher produces a grid of 384 channels at 64×64 positions from a 3×256×256 input. The channels are the different feature measurements at each position. The student shares the patch architecture, with 768 output channels in the final convolution. The first 384 describe the teacher features the student predicts. The last 384 carry its predictions for the autoencoder comparison. They share the student’s earlier computations, so making both predictions does not require a separate student pass at inference.
EfficientAD-M uses more kernels in the hidden convolutions. Two 1×1 convolutions are also added, one following the second pooling layer and one at the end. Such a convolution can change how feature channels are combined at a position while using only that spatial position as input. The teacher still supplies 384 channels, and the student still ends with 768. In the medium student, the final spatial convolution and the following 1×1 convolution both have 768 kernels. The two variants use the same whole-image autoencoder architecture.
The limited receptive field has a role beyond speed. If a defect lies outside a patch, it cannot change the PDN vector for that patch. This keeps a local comparison tied to the part of the image it describes. The paper contrasts this behavior with features taken directly from deeper networks. To visualize the difference, the authors examine the gradient of a central output feature vector with respect to the input pixels. The gradient reveals which pixels can influence that feature. They also average the first feature channel over 1000 randomly chosen ImageNet images. The examined DenseNet and WideResNet representations show spatial artifacts in those averages. The PDN deliberately limits the architectural routes through which distant pixels can influence an output.
Preparing the teacher by distillation
The teacher needs features that respond to meaningful differences in image content. The authors obtain them through distillation, training the smaller network on the outputs of a larger one. The main experiments take their targets from the WideResNet-101 feature extractor used by PatchCore. The target includes PatchCore’s feature processing. It pools features from two layers and projects the result to 384 dimensions per spatial location. The PDN learns from the features that PatchCore would pass to its procedure for choosing representative vectors. The training images come from ImageNet.
For the chosen extractor, an image resized to 512×512 gives an output grid of shape 384×64×64. The corresponding PDN input is resized to 256×256 to obtain a grid of that same shape. Matching the grids makes it possible to compare corresponding channels and locations. The teacher learns to approximate the values of the deep extractor, subject to the fact that it can see only a small patch for each prediction. A deep feature may draw upon distant image content that the PDN has no way to recover. Distillation transfers what can be predicted by the compact network under this restriction.
The appendix describes a preliminary pass for estimating the target statistics. The authors draw images in 10,000 iterations and occasionally convert an image to grayscale, with probability 0.1. They compute the mean and standard deviation of the extracted values in each channel across images and positions. These statistics standardize the target sent to the teacher.
Ŷᵠ꜀ = (Yᵠ꜀ − μᵠ꜀) / σᵠ꜀
Here the superscript ᵠ denotes the deep feature extractor, called Ψ in the paper. The subscript ꜀ identifies channel c. Yᵠ꜀ is its spatial output for that channel, μᵠ꜀ is the estimated channel mean, and σᵠ꜀ is the estimated channel standard deviation. Ŷᵠ꜀ is the standardized channel. The same mean is subtracted from every position in the channel, and each centered value is divided by the same standard deviation.
Dᵈⁱˢᵗ(c,w,h) = (Ŷᵠ(c,w,h) − Y′(c,w,h))²
Dᵈⁱˢᵗ is the array of distillation errors. The indices c, w, and h identify the channel, horizontal position, and vertical position. Ŷᵠ is the standardized deep feature, and Y′ is the PDN feature at the matching index. The square makes differences in either direction contribute a positive error and gives larger differences more influence.
Lᵈⁱˢᵗ = mean(Dᵈⁱˢᵗ)
Lᵈⁱˢᵗ is the distillation loss for an image. The mean averages Dᵈⁱˢᵗ over its channels and spatial positions, yielding a scalar that can be used to update the teacher. The algorithm groups images for the update and averages their losses.
Lᵇᵃᵗᶜʰ = 16⁻¹ × Σₖ Lᵈⁱˢᵗ(k)
Lᵇᵃᵗᶜʰ is the loss for the batch. The sum Σₖ adds the individual image losses Lᵈⁱˢᵗ(k), with k indexing the images in the batch. The factor 16⁻¹ divides the sum by the batch size of 16, and × denotes multiplication. The optimizer updates the PDN from the gradient of this batch loss.
The reported distillation schedule uses 60,000 updates, an initial learning rate of 10⁻⁴ and weight decay of 10⁻⁵. The authors use PatchCore’s official implementation to obtain the target features and preserve its feature postprocessing. The paper also explains how to adapt the process to other extractors. A different channel count changes the required size of the PDN output. A different spatial grid can be matched by adjusting the input sizes, since the PDN can produce a feature grid for different image dimensions. The experiments with alternative sources retain the compact teacher at test time.
Teaching the student what a normal patch looks like
Once the teacher is ready, the authors prepare it for a specific inspection scenario. They run its training images through the fixed teacher and estimate a new mean and standard deviation for each teacher channel. These statistics are specific to the normal images in that scenario. They serve a similar mathematical purpose to the statistics used during distillation, but are estimated at a different stage, from a different set of images and for a different network’s output.
Ŷ꜀ = (Y′꜀ − μ꜀) / σ꜀
Y′꜀ is the raw output grid of teacher channel c for the current image. The quantities μ꜀ and σ꜀ are the mean and standard deviation for that channel from the scenario’s normal training images. Ŷ꜀ is the resulting standardized slice of the teacher grid. Both the local student prediction and the autoencoder are trained against features on this scale.
The student is initialized separately from the teacher. For an unaugmented normal image, the student’s local output and the standardized teacher output have matching channels and positions. A direct training objective could average their squared differences everywhere. The problem is that much of a normal image can be easy to predict. A uniform background, for instance, can occupy a large part of a screw image. Equally weighting all feature elements gives that background a large share of the loss even when the remaining errors on the product are more important for distinguishing defects.
There is also a separate risk in making the student too effective at the general task of imitating the teacher. The authors observed that adding normal training images could improve agreement on anomalies as well. That would reduce the very difference that makes the method a detector. Reducing the amount of normal training data could sacrifice acceptable variations. The authors keep the available training images and change where the student gets most of its learning signal.
Dˢᵀ(c,w,h) = (Ŷ(c,w,h) − Yˢᵀ(c,w,h))²
Dˢᵀ denotes the squared local discrepancy. Ŷ is the standardized teacher output for the normal image. Yˢᵀ denotes the student channels assigned to the teacher-prediction task. The indices c, w, and h locate matching elements in the two feature grids. The superscript ˢᵀ labels the student–teacher comparison.
dₕₐᵣ𝒹 = quantile(Dˢᵀ, pₕₐᵣ𝒹)
The function quantile finds the cutoff at the fraction pₕₐᵣ𝒹 of the error distribution, where pₕₐᵣ𝒹 is the mining factor. It is applied to all elements of Dˢᵀ together. The result dₕₐᵣ𝒹 is the cutoff error. A high mining factor places this cutoff near the largest errors for the current image.
Lₕₐᵣ𝒹 = mean{Dˢᵀ(c,w,h) : Dˢᵀ(c,w,h) ≥ dₕₐᵣ𝒹}
Lₕₐᵣ𝒹 is the hard feature loss. The braces select the squared errors at or above the cutoff dₕₐᵣ𝒹, as indicated by ≥. The mean averages the selected elements. The indices c, w, and h range over the full channel and spatial grid, so different channels at the same location can have different selection outcomes.
Setting the mining factor to zero gives the ordinary average over the local feature errors. The method description and the EfficientAD-S training algorithm use 0.999. The selected elements change as training proceeds. Once the student predicts a feature well, its error may fall below the cutoff, and a different error will supply more of the training signal. The authors show this behavior on normal screw images. The selected elements concentrate on the screws at different rotations after the backgrounds are already predicted well. The selection follows the current prediction errors, as in online hard example mining.
The hard loss teaches the student to handle difficult normal values, which can otherwise become isolated high scores on good images. It does not give a direct target for what the student should do away from the inspection distribution. The second training term supplies such a target for a separate stream of images. During each training step, the authors draw an ImageNet image and penalize the magnitude of the local student output on it. These are general images drawn from the source used in pretraining. They are distinct from labeled rejects for the inspection task.
Lˢᵀ = Lₕₐᵣ𝒹 + (C × W × H)⁻¹ × Σ꜀ ‖S(P)꜀‖²ꜰ
Lˢᵀ is the local student training loss, and Lₕₐᵣ𝒹 is the selected-error loss on the normal inspection image. P is the random pretraining image. S(P)꜀ is channel c of the student output for P, using the channels that predict the teacher. The notation ‖ ‖²ꜰ is the squared Frobenius norm, which adds the squares of all the spatial entries of that channel. Σ꜀ adds these contributions across channels. C, W, and H are the channel count, feature-grid width, and feature-grid height. Their product gives the number of entries used for the average. The plus sign joins the normal-image matching objective and the pretraining-image penalty.
For this penalty the authors resize the sampled image to 512×512, convert it to grayscale with probability 0.3, and use the center 256×256 pixels. The student is encouraged to produce small values on the resulting image. The objective does not ask it to match the teacher there. This gives the two training streams different roles. Normal inspection images tell the student when to agree with the teacher. General pretraining images discourage it from using its capacity to imitate the teacher everywhere. Once training is over, the extra image stream and both loss computations are absent from inference.
Giving the whole image a role
The paper illustrates why an additional comparison is needed with the cable assembly in MVTec LOCO. A normal image shows a horizontal cable between two splicing connectors. The height of the cable may vary. A small metal washer near a cable end changes the contents of a patch and can appear in the local discrepancy map. An additional cable presents another problem. If its visible pieces resemble the normal cable in their respective neighborhoods, a patch-based comparison has little basis for treating the whole arrangement as wrong.
The autoencoder examines the arrangement through a bottleneck of 64 latent dimensions. Its encoder applies strided convolutions to reduce the image to this compact representation. Its decoder uses bilinear resizing and convolutions to build a spatial feature grid from the compressed code. Bilinear resizing estimates a value from nearby points on the source grid. The decoder’s target is the teacher’s feature grid for the input image, so it is learning to recover the teacher’s account of a normal scene.
Lᴬᴱ = (C × W × H)⁻¹ × Σ꜀ ‖Ŷ꜀ − A(I)꜀‖²ꜰ
Lᴬᴱ is the autoencoder reconstruction loss. A is the autoencoder, I is the normal image used for this part of the training step, and A(I)꜀ is its output for channel c. Ŷ꜀ is the standardized teacher output for the same image and channel. The norm squares and sums their difference at each spatial position. The sum over c combines channels, and C × W × H is the total number of entries, so the factor with exponent ⁻¹ converts the sum to a mean.
When trained on normal scenes, the autoencoder can usually represent regular layouts more readily than unexpected arrangements. Yet reconstructing fine detail from a compact representation is difficult even for a normal image. The background grid in the cable example illustrates the complication. A blurry approximation of a normal grid can differ substantially from the sharp patch features produced by the teacher. Comparing the teacher directly with the reconstruction would then give a high score to a normal part of the scene for a systematic reason.
The extra student output learns the autoencoder’s normal behavior. The student still sees only the patch associated with a position. Its additional channels are asked to predict what the whole-image reconstruction usually looks like at that position, given the local evidence. If a normal background is routinely blurred in the reconstruction, that blur becomes part of the target that the student can learn. The authors use the difference from this learned expectation as the global score.
Lˢᵀᴬᴱ = (C × W × H)⁻¹ × Σ꜀ ‖A(I)꜀ − S′(I)꜀‖²ꜰ
Lˢᵀᴬᴱ is the loss for agreement between the autoencoder and the student’s additional channels. A(I)꜀ is the reconstruction of channel c for image I, and S′(I)꜀ is the corresponding prediction from the extra student channels. The squared Frobenius norm covers the spatial positions for one channel. The sum over c and the division by C × W × H take the average over the full feature grids. The prime on S′ distinguishes this output from the local teacher prediction.
In the extra-cable image, the local student responds to familiar-looking cable patches. The autoencoder has to fit the arrangement with the additional cable into a representation learned from good assemblies. The paper shows disagreement in the global map where the two predictions diverge. The example explains the significance of the word global here. It describes the source of context for one side of the comparison. The resulting score still varies by location across the image, and an ordinary patch can be flagged because of how the surrounding image affects its reconstruction.
Lᵗᵒᵗᵃˡ = Lˢᵀ + Lᴬᴱ + Lˢᵀᴬᴱ
Lᵗᵒᵗᵃˡ is the total training loss for the inspection scenario. Lˢᵀ is the local student loss including the ImageNet penalty, Lᴬᴱ is the autoencoder’s teacher-feature reconstruction loss, and Lˢᵀᴬᴱ is the loss pairing the autoencoder with the extra student output. The terms are added directly. The parameters of the student and autoencoder are updated together. The paper specifies that the autoencoder receives gradients from the agreement term as well as from its reconstruction term.
A training step for an inspection scenario
The scenario training schedule uses a batch size of one and 70,000 iterations. Each step begins by selecting a normal image and evaluating the local student–teacher pair on it. The feature errors for this unaugmented view determine which entries enter the hard feature loss. The separate ImageNet sample supplies the penalty. The autoencoder part of the step uses an augmented view of the same normal inspection image. The training algorithm draws a brightness, contrast, or saturation adjustment and samples its coefficient uniformly from 0.8 to 1.2. The teacher, student, and autoencoder then process this adjusted view for the two losses involving the autoencoder.
The image channels are standardized just before passing the input to a network, after any augmentation. This input convention is separate from the channel normalization of the teacher’s output. The authors use the convolutional initialization and image normalization conventions described in their implementation details. For scenario training, the optimizer starts with a learning rate of 10⁻⁴ and weight decay of 10⁻⁵. The schedule lowers the learning rate to 10⁻⁵ after iteration 66,500. The optimizer is Adam.
The two views of a normal training image give the two tasks distinct conditions without requiring two sets of inspection images. At inference the image is processed without those augmentations. The student can produce both groups of channels in a shared forward pass. This is where the design recovers part of the cost that separate local and global prediction systems would incur.
Turning disagreements into visible scores
At inference the teacher, student, and autoencoder process the same test image. The teacher outputs are standardized using the training statistics, just as in scenario training. The local comparison is formed from the squared differences between the teacher and the student’s local prediction. The second comparison, which yields the global map, uses the squared differences between the autoencoder and the extra student prediction.
Dᴬᴱ(c,w,h) = (A(I)(c,w,h) − S′(I)(c,w,h))²
Here Dᴬᴱ is the discrepancy grid used for the global map at inference. A(I) denotes the autoencoder reconstruction and S′(I) denotes the extra student output for test image I. The indices c, w, and h identify a channel and position. The squared difference is evaluated at each matching entry. The superscript labels the map associated with the autoencoder, while the reconstruction loss used earlier compared the autoencoder with the teacher.
Mʳ(w,h) = C⁻¹ × Σ꜀ Dʳ(c,w,h)
Mʳ is the map for comparison r. The label r is either ˢᵀ for the local comparison or ᴬᴱ for the global comparison. Dʳ supplies the squared discrepancies for that comparison. The sum Σ꜀ ranges over the C channels at fixed spatial coordinates w and h, and the factor C⁻¹ takes their average. Both maps use all their channel errors in this step. Hard selection of errors is a training operation.
To make the maps comparable, the authors estimate how large their ordinary discrepancies can be on held-out normal images. They resize each map to the working image grid by bilinear interpolation and pool the scores from the validation images separately for each comparison. There are two quantiles for each pool. The lower reference quantile uses a = 0.9, and the upper reference uses b = 0.995 in the training algorithm. The quantiles measure where relatively high normal scores occur in each map distribution. They can be estimated from whichever score distribution appears in the scenario without choosing a distributional shape for it.
M̂ʳ = 0.1 × (Mʳ − qᵃʳ) / (qᵇʳ − qᵃʳ)
Mʳ here denotes the resized raw map for comparison r, and M̂ʳ is the normalized map. The quantities qᵃʳ and qᵇʳ are the stored validation quantiles at fractions a and b for that comparison. The subtraction applies separately to each map entry. The denominator is the distance between the two reference scores. The factor 0.1 sets the upper reference value after rescaling. An entry equal to the lower reference maps to 0, and an entry equal to the upper reference maps to 0.1. The equation is linear across the map’s value range.
The scale matters because a high but ordinary score in one comparison can obscure a meaningful signal in the other when the maps are added. Standardizing them this way relates each score to the variation observed on normal validation images. A common positive linear change to the output scale preserves the ranking of scores used by AU-ROC. The choice of which normal quantiles to align matters because it determines the relative scaling of the local and global evidence. The authors choose the shared destination values with visualization in mind.
M = 0.5 × M̂ˢᵀ + 0.5 × M̂ᴬᴱ
M is the combined map. M̂ˢᵀ is the calibrated local map, and M̂ᴬᴱ is the calibrated global map. The coefficient 0.5 gives each an equal weight at every pixel. The plus sign combines the two weighted values at corresponding positions. This lets either branch contribute to a high score at a location.
mⁱᵐᵃᵍᵉ = maxᵢ,ⱼ M(i,j)
The scalar mⁱᵐᵃᵍᵉ is the score for the whole test image. M(i,j) is the combined map value at pixel indices i and j, and max selects the largest value across those indices. Taking the maximum keeps a small, strongly scored region visible at image level. It also means that a single spurious peak on a normal image can raise that image’s score. For the localization evaluation, the map can be resized with bilinear interpolation to the original image size.
Experiments and results
The inspection datasets and the comparison protocol
The authors evaluate 32 scenarios drawn from MVTec AD, VisA, and MVTec LOCO. Each scenario has its own set of normal training images and a test set that includes anomalies. MVTec AD has 15 scenarios. VisA has twelve, and MVTec LOCO has five. Each collection supplies pixel-level defect masks for evaluating localization. The authors use normal validation images for EfficientAD’s calibration, keeping anomaly labels and masks for evaluation.
These collections place different demands on a detector. The paper notes that on MVTec AD, methods already rank many anomalous images correctly, which makes a comparison on that collection sensitive to decisions affecting the remaining difficult images. VisA contains challenging structural defects, including small ones. MVTec LOCO includes both physical defects and violations of assembly constraints. Evaluating the collections separately shows how a method behaves when the anomalies differ in character.
The baselines include AST and the original multiscale S–T approach, GCAD for reconstruction-based comparison, and FastFlow for feature density estimation. Other comparisons use DSR, SimpleNet, and PatchCore, with single and ensemble versions of PatchCore reported separately. The authors use official implementations where available. They describe changes to the evaluation protocol alongside the results because decisions about crops, checkpoint selection, and ensembling can affect both performance and runtime.
For instance, the authors disable test-based early stopping for SimpleNet and FastFlow. They observe that SimpleNet’s original procedure repeatedly evaluates checkpoints on the scenario’s test images and reports the best score. That gives information about the defects to the choice of when to stop. EfficientAD’s comparison instead evaluates the final SimpleNet checkpoint. For FastFlow, the authors use a constant training duration of 200 steps, with a WideResNet-50-2 feature extractor. They report that EfficientAD itself reaches 99.8% image-level AU-ROC on MVTec AD with early stopping enabled. The main comparison uses the evaluation protocol that leaves the test images out of that choice.
The authors also disable PatchCore’s center crop, which kept 76.6% of each image. On MVTec AD, 99.9% of defects lie at least partly within that central area. Using the crop can direct computation towards the subset of the image already known to contain nearly all the benchmark defects. The comparison retains the image periphery, since unseen anomalies in an application can arise there. The single PatchCore configuration uses the authors’ low-latency setting, a coreset ratio of 1% and images of 224×224 pixels. The ensemble uses images of 320×320 pixels and a coreset ratio of 1%, with the configuration selected from the one reported for the strongest MVTec AD detection result in the PatchCore paper.
For GCAD, the authors report the member of its ensemble that uses 33×33 patches. It performs better on average in their experiments than the full ensemble and reduces the reported latency by a factor of two. The choice has a cost for one subset of the results. On MVTec LOCO logical anomalies, the selected configuration achieves 83.9% image-level AU-ROC, compared with the ensemble’s 86.0%. The paper reports the overall MVTec LOCO detection performance as unchanged. This detail matters when evaluating the strongest specialist comparison for logical defects.
The paper records replication differences as well. The AST authors report 99.2% image-level AU-ROC on MVTec AD across five runs. EfficientAD’s authors obtain 98.9% on that collection across five runs using the official implementation and default configuration. For DSR they report 98.1% on MVTec AD, close to the earlier reported 98.2%. On VisA they use 50 epochs for DSR to keep the number of updates in a similar range despite larger training sets. The reported scores therefore describe the implementations and settings used for this comparison.
What the metrics measure
For whole-image detection, the paper uses area under the receiver operating characteristic curve, abbreviated AU-ROC. Scores are interpreted at a range of thresholds. As a threshold changes, a method flags a different share of the anomalous images and a different share of the normal images. The area summarizes this tradeoff over thresholds. It tells a reader how well the scores rank the two groups. It gives no specific false alarm rate for an operating threshold selected by a production site.
Pixel scores are used for localization, and the main comparison uses AU-PRO, the area under the per-region overlap curve up to a 30% false positive rate. Per-region overlap looks at the fraction of each annotated defect region that has been recovered at a threshold and gives each region equal weight. A pixel-wise AU-ROC, by comparison, weights individual defect pixels equally, so large regions can exert more influence. The limit on the false positive rate focuses the localization measure on thresholds at which a more restricted share of defect-free pixels is mistakenly marked. MVTec LOCO uses AU-sPRO, the collection’s extension of the region-overlap metric for evaluating logical anomalies.
For each collection, the authors first calculate the metric within each scenario and then average across scenarios. The overall score gives equal weight to the collection means. The MVTec LOCO evaluation gives logical and structural anomalies equal weight within a scenario. Across the three collections, the paper describes the overall weighting as roughly one-sixth for logical anomalies and five-sixths for structural ones. The per-scenario results distributed with the paper allow a reader to compare methods under a different weighting.
Image-level detection
Mean image-level detection AU-ROC across MVTec AD, VisA, and MVTec LOCO
Both EfficientAD variants rank anomalous images better than the compared baselines on the collection average.
The numbers
| System or setting | AU-ROC % |
|---|---|
| GCAD | 85.4 |
| SimpleNet | 87.9 |
| S–T | 88.4 |
| FastFlow | 90.0 |
| DSR | 90.8 |
| PatchCore | 91.1 |
| PatchCore Ens | 92.1 |
| AST | 92.4 |
| EfficientAD-S | 95.4 |
| EfficientAD-M (this paper) | 96.0 |
EfficientAD-M leads the aggregate image-level comparison, followed by EfficientAD-S. AST is the closest baseline on this aggregate, with the PatchCore ensemble next. The paper reports the EfficientAD means over five runs. The standard deviations in the aggregate AU-ROC comparison are 0.06 for EfficientAD-S and 0.09 for EfficientAD-M, on the same percent-valued scale. This variation describes repeated runs within the study’s setup.
The ordering changes when the collections are considered individually. On MVTec AD, the PatchCore ensemble reaches 99.3% mean image-level AU-ROC. EfficientAD-M reaches 99.1%, and EfficientAD-S reaches 98.8%. AST scores 98.9%. Several systems perform close to the top of the scale here. On VisA, the PatchCore ensemble scores 97.7%, ahead of EfficientAD-S at 97.5%, while EfficientAD-M scores 98.1%. The wider variant’s overall lead reflects results across all the collections.
MVTec LOCO is where the full approach separates more clearly from the comparison methods. EfficientAD-S reaches 90.0% mean image-level AU-ROC, and EfficientAD-M reaches 90.7%. AST obtains 83.4%, and the reported GCAD configuration obtains 83.3%. A collection-level score here incorporates both kinds of defect. The authors report the separate numbers as well to show where that performance comes from.
On the structural subset of MVTec LOCO, EfficientAD-S achieves 94.1% image-level AU-ROC and EfficientAD-M achieves 94.7%. DSR reaches 90.2% on that subset. On the logical subset, the corresponding EfficientAD scores are 85.8% and 86.8%. AST scores 79.7% on logical defects, while the GCAD configurations illustrate how much the chosen baseline variant can matter for that category. The logical anomaly scores for both EfficientAD variants remain below their structural scores. The overall MVTec LOCO improvement has contributions from both categories.
The image-level area under the precision–recall curve, or AU-PRC, gives a complementary view. Precision measures how many flagged images are actually anomalous, and recall measures how many anomalous images are flagged. The paper reports an overall image-level AU-PRC of 95.4% for EfficientAD-S and 95.7% for EfficientAD-M. The PatchCore ensemble scores 92.8%, and AST scores 92.2%. On MVTec AD alone, the ensemble reaches 99.0%, while EfficientAD-M and AST both reach 98.9%. The additional metric supports the broad aggregate result and again shows that the individual collections can favor different systems.
Locating defects within the image
The main localization comparison gives EfficientAD-S an overall score of 92.5% and EfficientAD-M a score of 93.3%, using the region metric through a 30% false positive rate and its MVTec LOCO counterpart. The original S–T method is the strongest baseline on this aggregate at 89.7%, with GCAD at 88.0%. The baseline rankings differ from the image-level comparison. A detector can have enough evidence to rank the image highly while placing its scores less precisely within the image. Conversely, a sharp response on recognized defects can coexist with false alarms elsewhere that make whole images harder to rank.
MVTec AD favors the PatchCore ensemble on the main localization measure. It scores 95.6%, compared with 93.1% for EfficientAD-S and 93.5% for EfficientAD-M. On VisA, EfficientAD-M scores 94.0%, EfficientAD-S scores 93.1%, and S–T scores 93.0%. On MVTec LOCO, the corresponding collection means for the EfficientAD variants are 91.3% and 92.5%, compared with 89.5% for GCAD. On that collection’s logical subset, EfficientAD-M reaches 91.3% and GCAD reaches 89.4%. The scores describe recovery of annotated regions, which is a different question from the image-level separation of logical defects and acceptable images.
The advantage on aggregate region overlap also appears with a tighter false positive limit. At 5%, EfficientAD-S has an overall region score of 76.5% and EfficientAD-M has 78.0%, while S–T has 70.4%. This comparison is relevant because many practically interesting thresholds allow far fewer false positive pixels than the main metric’s integration limit. It still summarizes a range of thresholds rather than specifying an operating point for a given scenario.
The precise choice of localization measure affects which variant looks best. Overall pixel-wise AU-PRC is 51.1% for EfficientAD-S, 50.5% for EfficientAD-M, and 50.6% for DSR. On VisA, DSR reaches 41.1% on that measure while EfficientAD-M reaches 40.8%. Pixel-wise precision–recall and region overlap emphasize different things. The main aggregate finding is strongest for the region-based measures and does not imply the same ranking under every definition of localization quality.
Latency and throughput
Single-image inference latency on the NVIDIA RTX A6000
EfficientAD-S returns an anomaly map fastest, with EfficientAD-M also ahead of the baselines.
The numbers
| System or setting | ms |
|---|---|
| EfficientAD-S (this paper) | 2.2 |
| EfficientAD-M | 4.5 |
| GCAD | 10.7 |
| SimpleNet | 12.0 |
| FastFlow | 16.5 |
| DSR | 17.2 |
| PatchCore | 32.0 |
| AST | 53.1 |
| S–T | 74.7 |
| PatchCore Ens | 147.6 |
The latency measurements use a batch size of 1. Timing begins with the transfer of a test image from the CPU to the GPU and ends when the anomaly map is available on the CPU. This interval includes more than the feature extractor’s forward pass and reflects the time to obtain a map under the paper’s inference procedure. The authors remove unnecessary inference work such as evaluating training losses. They use float16 for the networks and report that this precision change leaves EfficientAD’s detection results unchanged on the evaluated scenarios.
The timing protocol uses 1000 warm-up passes and then measures 1000 passes. Throughput is measured with a batch size of 16. EfficientAD-S achieves 614 images per second on the RTX A6000 in that test. SimpleNet reaches 194 images per second and AST reaches 41. The latency and throughput results describe distinct scheduling conditions. The batched throughput measures how much work that GPU completes when images can be grouped. The single-image result measures how quickly a single map becomes available.
The paper repeats the latency comparison on several GPUs. For instance, EfficientAD-S and EfficientAD-M take 2.5 ms and 5.3 ms on the RTX A5000. On the RTX 2080 Ti, their times are 4.5 ms and 7.6 ms. The variants remain the fastest methods compared on each tested GPU. The relative positions of FastFlow and DSR switch on the Tesla V100 and RTX 3080, where DSR is slightly faster. These measurements give a hardware-specific range for the same general comparison.
The appendix explains why the authors treat parameter count and floating-point operations as supporting information. A convolution can have few weights but reuse them at many positions on a large spatial grid. The original S–T method illustrates the result. An individual network can have between 1.6 and 2.7 million parameters and still take longer and use more memory than the 31 million-parameter U-Net used in GCAD. Operation counts also omit how well the operations can be executed in parallel. The measured GPU memory, in turn, reflects how the implementation reserves and reuses memory to reach its reported runtime.
What the ablations show
Adding the training and scoring changes
The paper performs a cumulative ablation and then tests individual removals. In the cumulative study, the authors start with a configuration using the PDN and add quantile normalization, hard feature loss, and the pretraining-image penalty in that order. The same evaluation uses the mean of the collection-level image detection AU-ROC scores. This experiment asks whether each addition helps given the changes already made before it.
Cumulative mean image-level AU-ROC across MVTec AD, VisA, and MVTec LOCO
Map calibration and the training changes improve the small configuration as they are added.
The numbers
| System or setting | AU-ROC % |
|---|---|
| PDN starting configuration | 93.2 |
| Add quantile map normalization | 94.0 |
| Also add hard feature loss | 95.0 |
| Also add pretraining penalty, EfficientAD-S (this paper) | 95.4 |
The alternative to quantile calibration in these tests is Gaussian-based normalization. The authors choose the linear transformation using the validation mean and variance, producing scores with mean zero and variance one on the normal validation set. This is a meaningful comparison because the two maps still receive scale adjustments. The test isolates a choice of calibration statistics rather than contrasting two calibrated maps with two raw maps. Its result shows that the quantile anchors produce more effective combined detection scores under the scenarios and configurations tested.
The hard feature loss gives a 1.0% improvement on the aggregate AU-ROC scale at its point in the cumulative study. The measured latency is 2.2 ms at every step through the completed EfficientAD-S configuration. This agrees with how the changes enter the method. The hard feature selection and ImageNet penalty change how the student is trained. The normalization uses stored statistics during scoring. The study finds a gain from these choices without requiring a larger inference network.
The second ablation begins with the complete EfficientAD-S and removes each change separately. Removing quantile normalization gives 94.7% aggregate image-level AU-ROC. Removing the hard feature loss also gives 94.7%, and removing the pretraining penalty gives 95.0%. Each setting continues to take 2.2 ms under the single-image timing protocol. These tests establish that each change contributes within the completed small configuration. The sizes of the effects depend on the other components present, as seen by comparing the cumulative and individual tests.
Changing the PDN to the medium architecture is a different kind of intervention. The cumulative table reports 96.0% aggregate detection AU-ROC for EfficientAD-M at 4.5 ms. This trades extra inference work for greater capacity in the teacher and student. The small architecture’s training and scoring improvements account for its own gains while retaining its measured latency. The medium result shows the further change that comes with a wider architecture and additional channel-mixing layers.
How sensitive the choices are
The authors vary the quantiles and the mining factor for EfficientAD-M. For the lower calibration anchor, the aggregate detection AU-ROC is 95.9% at a = 0.5, 96.0% at a = 0.9, and 95.8% at a = 0.99. For the upper anchor, b = 0.95 gives 95.8%, and both b = 0.99 and b = 0.995 give 96.0%. The narrow spread supports the use of a range of choices near the tested anchors. The comparison is about stability of the detection metric across these settings. It does not measure how score values drift when the appearance of normal products changes after training.
The mining sweep shows clearer sensitivity to how many errors participate in the training update. On the same aggregate detection measure, pₕₐᵣ𝒹 = 0.9 and pₕₐᵣ𝒹 = 0.99 both give 94.9%. The value 0.999 gives 95.7%, 0.9999 gives 96.0%, and 0.99999 gives 95.7%. The explicit training algorithm for EfficientAD-S specifies 0.999, while the medium variant’s reported sweep peaks at 0.9999. The sweep therefore gives evidence for concentrating on high errors in this setup, with the precise best cutoff dependent on the setting being tested.
The screw masks help explain the action of that cutoff. The paper shows the selected error locations on randomly chosen normal training images. The brightness of a position in these masks counts how many feature channels there enter back-propagation. Ordinary background positions are largely already predicted well, and more of the remaining training effort goes into the screw at different rotations. This is evidence about the distribution of training updates. It is distinct from the test-set ablation that measures whether the resulting attention to harder normal features improves ranking.
Distillation backbones and visible failure patterns
The authors also repeat the detection comparison with different backbones for feature extraction and distillation. The main study uses WideResNet-101. The alternatives are ResNeXt-101 and DenseNet-201, the other backbones used in the PatchCore ensemble. For PatchCore, changing the backbone changes the network used at inference. For EfficientAD, it changes the source of the targets used earlier to train the compact teacher. The compact architecture still supplies the features at test time.
On MVTec AD, EfficientAD-M obtains 99.1% image-level AU-ROC with WideResNet-101 targets, 99.0% with ResNeXt-101 targets, and 99.2% with DenseNet-201 targets. On VisA, EfficientAD-M scores 98.1%, 98.0%, and 97.7% with those respective targets. PatchCore scores 94.3%, 95.2%, and 94.8% on VisA with the corresponding extractors. This comparison helps separate achievable performance with a source of features from performance under a particular decision procedure. Sharing a source does not make the methods equivalent, since the PDN approximates those features and EfficientAD uses the separate global comparison.
The backbone choice matters more on MVTec LOCO for some settings. The medium variant falls to 88.3% mean image-level AU-ROC with DenseNet-201 targets, compared with its 90.7% with WideResNet-101 targets. The small variant attains 90.6% with DenseNet-201 and 90.0% with WideResNet-101. Thus the size ordering of the main configurations is contingent on which feature source is distilled. The tested alternatives show that good performance can persist across backbones while leaving meaningful variation on the collection concerned with logical constraints.
The qualitative figures illustrate differences that aggregate scores compress. The VisA figure shows a randomly selected defective image from each of its scenarios, alongside the annotation and the EfficientAD-M map. Other figures compare maps from the baselines, including structural and logical examples from MVTec LOCO. The paper shows that AST can respond to an additional cable yet give little response to a missing pushpin. It also shows that a method capable of a precise outline can produce high background scores on another image. These examples help interpret the metrics, which provide the comparison across test images.
Limitations
Limits identified by the authors
Fine-grained logical anomalies remain a stated limitation. A screw that exceeds the required length by two millimeters is the paper’s example. Its material, surface, and much of its local geometry can look ordinary. The global branch must represent the difference through compression and feature reconstruction. A strong mean score on logical anomalies does not establish that the method can resolve tolerances of this kind. The authors point to conventional metrology for such measurements.
The qualitative results show weaker responses even on some of the logical cases that the global branch was designed to handle. The authors point to two examples in which EfficientAD’s maps could respond more strongly, a breakfast box and a box containing pushpins. A distinction between having a mechanism for a type of defect and reliably detecting each instance is important in this setting. The existence of a global comparison gives the system relevant information about the whole scene. Its training on normal images supplies no direct constraint guaranteeing a large score for every possible violation.
The authors also identify the need for scenario-specific training as a practical cost compared with nearest-neighbor methods. The autoencoder in particular must learn the regularities of the normal scene. The paper reports a training time of twenty minutes in its setup. That cost is separate from preparing the distilled teacher and from the inference time per image. The difference matters in applications that must configure many inspection scenarios even when the eventual runtime of any one scenario is small.
Boundaries of the evaluation
The accuracy evidence concerns the particular collections and configurations compared. The datasets represent a range of industrial inspection conditions, with labeled defects and pixel masks for testing. They do not establish behavior under a new camera setup or a later change in the distribution of acceptable products. The maps are calibrated with held-out images assumed to represent normal conditions. A shift in those conditions could alter the frequency and scale of normal score peaks. The paper’s validation procedure estimates these quantities for the images available at setup.
The benchmark metrics also leave the operating threshold open. AU-ROC can show a good ranking even when the cost of an occasional missed defect or an occasional false alarm demands a more specific comparison. Region overlap up to 30%, or even the additional results up to 5%, summarizes a range of thresholds. The paper does not determine what result a facility would obtain at its chosen thresholds, defect prevalence, or rejection costs. Equal weighting of collection means is appropriate for reading the reported benchmark comparison, while the balance of structural and logical defects at an individual facility may be different.
The working image resolution is another boundary. Inputs are resized to 256×256, and the feature maps are interpolated to provide pixel scores. Interpolation supplies positions on the finer map without adding evidence about fine details lost when the image was resized or converted into a feature grid. Effective detection of small defects in the evaluated images therefore leaves open how accurately the system can resolve a particular physical tolerance in another imaging setup. A displayed map with many pixels should be read in light of the resolution at which the underlying features were computed.
The ablations explain the contribution of quantile normalization and the student’s training terms within EfficientAD. They do not directly isolate the full global branch by reporting a corresponding local-only comparison in the cumulative and individual tables. Its role is illustrated by the cable examples and supported by the full system’s results on MVTec LOCO, including the split by anomaly type. Those comparisons cannot assign a numerical share of the overall gain to the autoencoder alone. The same considerations apply to differences in architecture between EfficientAD and external baselines.
Finally, the speed measurements describe a defined hardware and software setup. The networks run in float16, the timed EfficientAD configuration omits PDN padding, and the transfers between CPU and GPU are included. The authors report that removing padding saves 80 µs in the PDN pass without impairing anomaly detection in their evaluation. The comparison does not measure a complete production cycle from acquiring the image through taking action on a flagged part. Some resource comparisons are also incomplete. Using the official PatchCore implementation’s library, the authors could measure how long the nearest-neighbor search took, but they were unable to count the floating-point operations it performed or measure the GPU memory it used separately.
What came after
There are no documented follow-up studies to describe. The paper ends by proposing that the patch description network could serve as a feature extractor for other anomaly detectors. Its experiments show why the authors make that proposal. The compact extractor approximates features from several larger backbones, and once distilled it can run independently of those backbones. Using it within a different detector would test which of the speed and localization properties carry over when the downstream scoring method changes.
Cite
Cite as Kilian Batzner, Lars Heckler and Rebecca Konig. 2023. EfficientAD: Accurate Visual Anomaly Detection at Millisecond-Level Latencies. arXiv:2303.14535 · Proceedings of the IEEE/CVF Winter Conference on Applications of Computer Vision (WACV), 2024, pp. 128-138.
@misc{batzner2023efficientad,
title = {{EfficientAD: Accurate Visual Anomaly Detection at Millisecond-Level Latencies}},
author = {Kilian Batzner, Lars Heckler and Rebecca Konig},
year = {2023},
doi = {10.48550/arxiv.2303.14535},
eprint = {2303.14535},
archivePrefix = {arXiv},
url = {https://doi.org/10.48550/arxiv.2303.14535}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/batzner-2023-efficientad-accurate-visual-anomaly-detection/