Reconstruction-based anomaly detectors work by "healing" an image. A model trained only on defect-free parts rewrites a test image into a plausible normal version, and the pixels it had to change are flagged as defects. The weak point is the final comparison. Detectors subtract the input from its reconstruction and treat any large difference as suspicious. They do this even though the reconstructor also makes large, systematic errors on perfectly normal wood grain, carpet weave, or cable strands. We propose a different scoring rule. For each image patch, first ask what kinds of residual the reconstructor produces on normal data. Then score how much more common a given residual is in the current test image than in that normal reference. This is a density ratio, estimated per image and per patch, with no explicit density model.
There is a technical difficulty, and it turns out to point to the right tool. The ordinary ratio "test density over normal density" becomes infinite exactly where the normal reference has no mass, which is exactly where the defects are. The α-relative density ratio, introduced in Relative Density-Ratio Estimation for Robust Distribution Comparison, mixes the numerator into the denominator, so the ratio is capped at a known constant. The defect region therefore saturates at a known ceiling instead of exploding. We expect the result to be a localization map that is stable to estimate and has an absolute scale. It sits on top of any existing reconstructor, diffusion or autoencoder, and can be fitted in closed form per image.
Core Claim
Let $z$ be a residual descriptor at one spatial location. It is the difference between pretrained-CNN features of the input $x$ and of its reconstruction $\hat{x}$, stacked across several diffusion noise levels. Let $p(z)$ be the distribution of these descriptors over the patches of the current test image, and $p'(z)$ their distribution over patches of held-out normal images passed through the same reconstructor. We score each patch by
$$r_\alpha(z) = \frac{p(z)}{\alpha\, p(z) + (1-\alpha)\, p'(z)},$$
where $\alpha \in (0,1]$ is a mixing weight. The ratio equals roughly 1 where the test image looks like normal reconstruction behaviour and rises to its ceiling $1/\alpha$ where the normal reference has no support. The intuition is simple. Within one image most patches are normal, so $p$ is a mixture of a large normal part and a small defect part. In the population limit, the ratio separates the two parts with a contrast of $1/\alpha$ to roughly 1, whatever the defect fraction. We fit $r_\alpha$ with RuLSIF, which approximates the ratio as a weighted sum of Gaussian kernels and solves for the weights with one linear system. Kernel width and regularization are chosen by an analytic leave-one-out score.
The claim has three parts, each testable. First, scoring residuals by a ratio against the reconstructor's own normal residuals removes false positives in high-texture regions that raw subtraction cannot handle. Second, the bounded ratio localizes more stably than the unbounded ratio on identical features. Third, and this is the claim most at risk, the ratio beats a one-class density or nearest-neighbour score computed on the same residual features.
Relation to Prior Work
Two lines of work motivate the proposal. The first shows that the gap is real. MVTec AD introduced the standard industrial benchmark. It reports that autoencoders scored by L2 or SSIM (structural-similarity) residuals reach an image AUROC (area under the ROC curve) of 0.86 on the cable category but a per-region overlap of only 0.05. Subtraction finds that something is wrong but not where. Denoising Diffusion Models for Anomaly Localization in Medical Images documents the "noise paradox". If the diffusion model, a generator that learns to turn noise back into images, starts from too little noise, it reproduces the lesion; if it starts from too much, it destroys healthy anatomy. Any single noise level is therefore a compromise. That is why our descriptor $z$ stacks residuals from several noise levels, and the ratio decides which combination is unusual.
The second line supplies the method. RuLSIF from Relative Density-Ratio Estimation for Robust Distribution Comparison gives the bounded ratio, its closed-form fit, and the result that the estimator's variance does not grow with model complexity. The inlier-based outlier detection of Inlier-Based Outlier Detection via Direct Density Ratio Estimation supplies the setting of a clean reference set versus an unlabeled test set. We reuse both, but apply them to reconstruction residuals at the patch level rather than to whole samples in raw input space.
Several papers come close but do something different. Direct Density Ratio Estimation with Convolutional Neural Networks trains a CNN under the unbounded uLSIF loss and outputs one scalar per image, reaching about 0.79 AUC on CIFAR-10 car-vs-cat. It neither localizes nor reconstructs, and it takes about 833 seconds to train on USPS, versus under 0.02 seconds for the kernel solutions. OOD Detection with Class Ratio Estimation estimates in-distribution-to-base ratios with a binary classifier. Its strong variant needs an external 300K-image outlier set, and its data-free "local" base built from crops was weaker. Our reference distribution is instead built from the reconstructor's own behaviour on held-out normals, which needs no outside data and overlaps the test distribution by construction. DRÆM learns a comparison network over the input and its reconstruction, but trains it on synthetic Perlin-noise and texture defects. Our comparison is fitted per image against real normal residuals and makes no assumption about defect appearance. GLAD chooses denoising steps per image by comparing residuals to a fixed threshold. We keep several noise levels and let the ratio weigh them.
One paper partly contradicts us: Is Task-Specific Training Necessary for Anomaly Detection?. It argues that reconstruction faces a fidelity-stability dilemma and should be abandoned for retrieval over DINOv3 features. Our position is narrower. Much of that instability lives in the scoring rule rather than in the reconstruction, and recalibrating the score against normal residual behaviour should recover a large part of the gap. If the experiments show otherwise, that paper's view gains support.
Research Program
The pipeline has four stages. In the first, we take two existing reconstructors without retraining them: GLAD's diffusion model from its released code GLAD, and DRÆM's reconstructive sub-network from ADer. Each training image is reconstructed from K noise levels (for example K=4, spanning the shallow-to-deep range GLAD reports for scratches versus missing parts).
In the second stage, we extract frozen pretrained CNN features of $x$ and each $\hat{x}_k$ on a coarse grid. We form per-location residual descriptors, then reduce them with PCA fitted on normal data so the Gaussian kernels operate in a few dozen dimensions.
In the third stage, we build the reference pool $p'$ from a split of normal training images that the reconstructor never saw. This matters, because residuals on training images understate the reconstructor's real error. The pool is subsampled per category to a few thousand patches.
In the fourth stage, at test time, we fit RuLSIF between the image's own patches and the reference pool. We use about 100 kernel centres drawn from the test patches, so a defect cluster gets basis functions. Leave-one-out cross-validation selects width and regularization. Every patch is then scored, giving a map in $[0, 1/\alpha]$. Image-level scores are the mean of the top 1% of the map. A batch variant pools patches from a production batch to test whether more test data helps rare small defects.
The analysis has two strands. We sweep α from 0.1 to 0.95, measuring the trade-off the file identifies between contrast and variance. We also test whether the known ceiling supports one threshold per category, or even a single global threshold set halfway between 1 and $1/\alpha$, without any anomalous validation data. MVTec AD flags exactly this "thresholding trap".
Baselines
The naive reference is raw residual scoring on the same reconstructions. It uses pixel L2 plus SSIM, and also feature-space distance at the single best noise level. Both use the same reconstructor outputs and an identical image-level top-1% aggregation. Any gain we show must exceed this, or the ratio adds nothing.
The strongest reconstruction-based competitors are GLAD and DRÆM, run from released code with their published settings. GLAD reports 99.3% image AUROC and 98.6% pixel AUROC on MVTec AD. DRÆM reports 98.0 image AUROC and 68.4 pixel average precision (AP) on MVTec AD. We reproduce both on our splits and compare against our reproduction as well as the reported figures. Because our method reuses their reconstructions, the fair comparison is "their scoring head versus ours on identical $\hat{x}$". Beating them means a higher pixel AP and AUPRO (area under the per-region-overlap curve) with the same reconstructor. Pixel AP is the metric where false positives on texture hurt most. Matching their image AUROC is acceptable.
The strongest non-reconstruction method is RAD from Is Task-Specific Training Necessary for Anomaly Detection?, with a reported 98.5% pixel AUROC on MVTec AD. We run it with its own encoder. As an extra control, we also run it with the feature extractor we use, to separate encoder quality from scoring. We do not need to beat RAD outright. We do need to close a substantial part of the gap between raw reconstruction residuals and RAD.
Three ablations isolate the key ingredient. The first is a one-class score on identical residual descriptors: a per-location Gaussian with Mahalanobis distance, and k-nearest-neighbour distance to the reference pool. The second is the unbounded uLSIF ratio on identical descriptors. The third replaces the multi-level descriptor with a single noise level, and the held-out reference pool with training-image residuals. All methods share PCA dimension, reference pool, and a tuning budget of the same number of hyperparameter configurations, selected on normal validation data only.
Why not just…?
Why not just score the residuals with a one-class density or nearest-neighbour distance? This is the real threat, and we treat it as the central ablation rather than a strawman. A Mahalanobis or k-nearest-neighbour score on our residual descriptors already uses the reference pool and the multi-level features. Prior evidence favouring the ratio is indirect. RuLSIF outperformed one-class SVMs on USPS and 20 Newsgroups in Relative Density-Ratio Estimation for Robust Distribution Comparison, and inlier-based detection was proposed precisely because fitting the difference is easier than fitting a density. But that evidence comes from whole samples, not image patches. If pixel AP and AUPRO for the ratio do not exceed both one-class scores on MVTec AD and VisA, the ranking claim fails. What would remain is only the calibration claim, which must then beat a split-conformal threshold on the one-class score.
Why not just train a better learned comparator, as DRÆM does? A learned comparator is only as good as its synthetic defects. DRÆM's discriminator never sees real normal residual statistics; it sees Perlin blobs filled with texture. Our per-image fit adapts to whatever unusual residual appears. The decisive test is on MPDD and on VisA's multi-instance categories, where defects look least like Perlin texture and GLAD reports large gains over prior reconstruction methods on MPDD.
Why not just abandon reconstruction for retrieval, as RAD does? Retrieval may simply be better at ranking, and we say so. Reconstruction keeps a healed counterfactual, which DeScarGAN and the medical diffusion work treat as clinically useful. It also replaces a memory bank of all training patches with a small reference pool. The experiment reports accuracy against reference-pool size alongside RAD's memory footprint.
Why not just use the ordinary ratio, which is simpler? The ordinary ratio diverges where the normal reference is empty, which is the defect region itself. Its spikes depend on kernel placement rather than on the defect. The uLSIF ablation measures this through map variance across random kernel-centre draws and through pixel AP.
Proposed Experiments
We evaluate on MVTec AD (15 categories), VisA (12), and MPDD. Metrics are image AUROC, pixel AUROC, pixel AP, and AUPRO, plus F1 at a fixed threshold to test calibration. MVTec's cable and texture categories are reported separately, because the file's 0.05 cable overlap shows these are where residual scoring breaks.
Four checks decide the outcome. First, with GLAD's reconstructions held fixed, the ratio head must raise pixel AP over GLAD's own scoring. Second, the ratio must beat Mahalanobis and nearest-neighbour scores on identical descriptors; failing this is the main falsifier. Third, the bounded ratio must give lower variance across kernel draws, and higher AP, than uLSIF. Fourth, a single threshold set from the known ceiling must achieve F1 within a few points of the per-category oracle threshold, compared against conformal thresholds on the one-class score.
Secondary analyses cover the α sweep, per-image versus batch fitting for small defects, and wall-clock time. The closed-form fit should add milliseconds over the reconstruction cost; diffusion sampling, not the ratio fit, will dominate latency.
References
- Relative Density-Ratio Estimation for Robust Distribution Comparison
- MVTec AD - A Comprehensive Real-World Dataset for Unsupervised Anomaly Detection
- Denoising Diffusion Models for Anomaly Localization in Medical Images
- Inlier-Based Outlier Detection via Direct Density Ratio Estimation
- Direct Density Ratio Estimation with Convolutional Neural Networks with Application in Outlier Detection
- OOD Detection with Class Ratio Estimation
- DRÆM - A discriminatively trained reconstruction embedding for surface anomaly detection
- GLAD: Towards Better Reconstruction with Global and Local Adaptive Diffusion Models for Unsupervised Anomaly Detection
- Is Task-Specific Training Necessary for Anomaly Detection?
- DeScarGAN: Disease-Specific Anomaly Detection with Weak Supervision