Which Anomalies a Score Can See: Choosing Scoring Metrics from Equational Laws

Most industrial anomaly detectors end by comparing a test image's parts with stored normal parts and turning the mismatch into one number. That number is a distance. Every distance silently decides which changes count as "no change". The standard nearest-neighbour rule scores each test patch by its distance to the closest stored normal patch, then takes the worst patch. This rule is essentially a one-sided Hausdorff distance between sets of patches. A set does not record how many times an element appears, so a second copy of a perfectly normal pushpin is invisible to it.

This proposal makes that observation precise and uses it. Quantitative equational logic is a calculus in which "$t =_\epsilon s$" means "terms $t$ and $s$ are at most $\epsilon$ apart". It has shown that classical distances on collections are exactly the distances forced by algebraic laws. The Hausdorff distance comes from the laws of sets, where adding an element twice is the same as adding it once. Kantorovich (optimal-transport) distances come from the laws of convex mixtures. So the laws one assumes decide which anomalies a score can detect at all. We propose to use this to build one detector for many product categories. For each category it picks, from normal data alone, the algebraic theory whose laws match how normal images actually vary. It then scores test images with the distance that theory induces. Structural defects and logical defects (wrong counts, missing parts, wrong proportions) are handled by a single composed distance rather than by heuristic score fusion.

Core Claim

Logical anomaly detection fails in unified multi-class models for two reasons. Their final scoring rule obeys laws that hide count and composition errors. Their fixes, such as histogram banks or a separate global branch, are glued on with normalization tricks that do not compose. Two things should follow from treating the scoring rule as the free metric of a chosen quantitative theory. First, we should be able to predict in advance which anomaly types each scoring rule is blind to. Second, choosing per category among a small family of theories should let one shared detector close those blind spots without hurting structural detection. The family runs from sets, to convex mixtures, to multisets with an explicit cost for unmatched parts.

The logic is the design and analysis tool. It is not a runtime theorem prover. We do not ask the neural backbone to be non-expansive (distance-non-increasing). That sidesteps the tension in the file's Gap 4, where breaking the identity shortcut requires deliberately disruptive operations such as dropout and noise. Non-expansiveness and the triangle inequality are imposed only at the aggregation layer, where they cost nothing in detection power.

Background and Positioning

The method comes from Quantitative Algebraic Reasoning. That paper introduces deduction rules for $=_\epsilon$ and proves that quantitative semilattices give rise to the Hausdorff metric, barycentric algebras with an interpolation axiom to Kantorovich/Wasserstein metrics, and left-invariant barycentric algebras to total variation. We reuse these correspondences as a menu of scoring rules, each with a known list of laws and therefore a known list of blind spots.

Tensor of Quantitative Equational Theories and Sum and Tensor of Quantitative Effects show how to combine theories. We use them to justify building a scene distance by layering a "collection of parts" theory over a base distance on part features. Compositional Quantitative Reasoning proves that distances to a specification compose under parallel composition, via the bound $d(I\parallel J, F\parallel G)\le\max\{d(I,F),d(J,G)\}$. It works on discrete system models, not perceptual features. We borrow the idea that a composite score should be bounded by its parts' scores, replacing post-hoc normalization.

On the anomaly-detection side, the motivating evidence is that logical defects need component-level reasoning. Few Shot Part Segmentation Reveals Compositional Logic for Industrial Anomaly Detection (PSAD) parses images into parts and keeps three memory banks: count histograms, part compositions and patches. It fuses their nearest-neighbour scores with an adaptive scaling fitted to training statistics. Revisiting Deep Feature Reconstruction for Logical and Structural Industrial Anomaly Detection (ULSAD) pairs a local reconstruction branch with a global branch that compares attention maps, and fuses the two with quantile normalization. Both are trained per category. Neither says why its patch branch misses counts. Both rely on fusion rules that may not transfer across categories.

The unified models are the regime we must not regress on. A Unified Model for Multi-class Anomaly Detection (UniAD) uses neighbour-masked attention and feature jitter. Dinomaly uses a frozen DINOv2 encoder with a dropout bottleneck and linear attention. MambaAD uses state-space decoders. VQ-Flow uses hierarchical codebooks feeding a mixture-of-Gaussians flow. All of them train one model across categories and evaluate patch-level discrepancies. That constrains us: any gain on logical anomalies that costs structural accuracy on MVTec-AD or VisA is a failure.

CSAD, SALAD and SAM-LAD supply unsupervised or zero-shot component parsing, which we treat as an interchangeable front end. LogiCode and LogicQA write discrete rules with language models. We differ by producing a continuous distance with a triangle inequality instead of pass/fail checks.

Research Program

The pipeline has four stages: parse the image into parts, choose a theory for the category, compute that theory's scene distance, and fuse it with the patch distance.

Parsing. A frozen DINOv2 encoder, shared with a Dinomaly-style structural branch, feeds an unsupervised part parser in the style of CSAD. The parser turns each image into a finite collection of parts. Each part carries a feature vector and a normalized position, and a base distance $d_0$ between parts combines feature and position distance. Training images are clustered into discovered categories without labels, following the hierarchical clustering idea of Heo and Kang. The whole system is therefore a single unified model.

Candidate theories. Each discovered category is assigned one of three theories. The set theory scores with the Hausdorff distance. The convex-mixture theory scores with a Kantorovich distance between part distributions normalized to unit mass. The multiset theory scores with a matching distance in which unmatched parts pay a fixed cost. For collections $A=\{a_i\}$ and $B=\{b_j\}$, that distance is

$$d_{\lambda}(A,B)=\min_{\pi}\Big[\sum_{(i,j)\in\pi} d_0(a_i,b_j)+\lambda\,\big(|A|+|B|-2|\pi|\big)\Big].$$

Here $\pi$ ranges over partial one-to-one matchings between $A$ and $B$, $|\pi|$ is the number of matched pairs, and $\lambda>0$ is the cost of a part with no partner.

The file establishes the Hausdorff and Kantorovich correspondences. For the multiset case, the first theoretical deliverable is to prove or refute that $d_\lambda$ is the free metric of a quantitative commutative-monoid theory with a "deletion costs $\lambda$" axiom. If it is not, we will find the theory it does correspond to. We will also write down, for each theory, the anomaly edits that are provably invisible to it. For example, duplicating an existing part is invisible under set laws. Scaling all counts by the same factor is invisible under mixture laws.

Theory selection from normal data. The choice is made by testing which laws normal variation respects. If normal images in a category differ in part counts, as with macaroni scattered in variable numbers, the multiset theory would flag normal images. The mixture or set theory is then appropriate. If counts are fixed but layouts vary, the multiset theory applies. Concretely, we pick the strictest theory whose held-out normal-to-normal distances stay below a quantile of its normal distance spread. This uses only defect-free images.

Composition. The final score is built by layering the chosen collection theory over $d_0$, with the patch-level structural distance entering as part of $d_0$. Matching costs add up and inherit the triangle inequality, so a scene's score is bounded by its parts' contributions. That bound is the property we will test against quantile normalization.

Baselines

The do-nothing reference is the unified Dinomaly structural branch alone, with its standard patch-level score. It is run from the ADer toolbox with the same frozen encoder and image resolution. On standard benchmarks Dinomaly is also the strongest unified model: it reports 99.6% image AUROC on MVTec-AD and 98.7% on VisA (Dinomaly). No reported result was found on Lacuna for Dinomaly, UniAD, MambaAD or VQ-Flow on MVTec LOCO AD in the unified setting, so we will train all four ourselves on the five LOCO categories jointly. Beating this baseline means a clear gain in logical-anomaly AUROC on LOCO while staying within run-to-run noise on MVTec-AD and VisA.

The strongest logical competitor is PSAD, which reports 98.1% logical and 91.6% structural AUROC on MVTec LOCO AD in its per-category, few-shot-labelled setting (PSAD). ULSAD reports 84.1% image AUROC on LOCO (ULSAD). We will re-run both in the unified setting, giving them the same part parser where applicable, the same backbone and the same hyperparameter-search budget. Their published per-category numbers serve as an upper reference, not as a target. Matching PSAD's per-category logical AUROC while running as one unified model with no part labels would count as a win. So would beating unified PSAD by a margin larger than seed variance on count-type anomalies.

Two ablations isolate the key ingredient. The first fixes the theory to sets, mixtures or multisets for every category, which tests whether per-category selection matters. The second keeps our parts but fuses part and patch scores with PSAD's adaptive scaling instead of composed matching, which tests whether composition beats normalization.

Why not just…?

Why not just add a count histogram, as PSAD does? This is the most serious threat. On fixed-count categories a histogram bank may perform as well as the multiset distance. The difference shows up where counts legitimately vary, where a histogram flags normal images. It also shows up where the error is "right count, wrong pairing of part and location", which histograms cannot see but matching can. The fixed-theory ablation and the unified PSAD re-run settle this directly. If unified PSAD matches us on every LOCO and VisA multi-instance category, the honest conclusion is that the theory is only an explanation of why histograms work. We would then publish it as an analysis result, not a method.

Why not just use optimal transport between patch sets? Balanced optimal transport is the convex-mixture theory, one point on our menu. Its laws predict that it ignores uniform rescaling of counts and spreads mass rather than charging for missing parts. The fixed-theory ablation measures exactly this, and the controlled edit study below tests the prediction.

Why not just learn the fusion weights? Learning fusion weights well requires anomalous examples, which the unsupervised setting forbids. Fitting weights on normal statistics alone is what quantile and adaptive scaling already do. Heo and Kang (Multi-class Image Anomaly Detection for Practical Applications) document that score scales diverge across classes in unified models. We will report per-category score calibration to show whether composed distances transfer better.

Why not just prompt a vision-language model or have it write rule code? LogiCode and LogicQA produce discrete verdicts with no graded distance. We will include LogicQA-style prompting on LOCO as a reference if compute allows, and will report throughput against ULSAD's reported 33.42 images per second.

Proposed Experiments

The decisive check is a controlled edit study. On normal MVTec LOCO and VisA multi-instance images (capsules, macaroni), we synthesize four edit types by copy-paste and inpainting: duplicating a part, deleting a part, swapping a part's position, and rescaling all counts. The theory predicts specific near-chance AUROC cells, for instance Hausdorff scoring on duplications and mixture scoring on count rescaling.

Real patch features have receptive fields that see neighbouring context, so a duplicated part is not an exact copy and the predictions may hold only partially. Measuring how far the real scores depart from the prediction is itself a finding about how much context leaks into patch features. If the predicted blind spots do not appear even for raw nearest-neighbour scoring, the central premise fails and we stop.

The main evaluation trains one model jointly on the five LOCO categories. It reports logical and structural image AUROC and localization AUROC against the baselines above. Theory-selection accuracy is reported against a manual labelling of each category's count regime. We then check for regressions on MVTec-AD, VisA and Real-IAD, where Dinomaly reports 89.3% and MambaAD 86.3% AUROC, under identical training. Finally, we test transfer of the selection rule: the theory-selection threshold is calibrated on LOCO alone and applied unchanged to VisA. A fixed rule that picks correctly on unseen categories is the strongest evidence that the laws, not the tuning, are doing the work.