Comparison with baseline methods
To evaluate the RareCode framework, multiple representative UAD methods were selected as baselines, spanning reconstruction-based methods (CAE32, VAE12, SAE33, MAE34, PatchSAE35), memory-augmented reconstruction (MemAE36), knowledge distillation (STFPM37), synthetic anomaly generation (DRAEM38), and pretrained feature extraction (PatchCore18). Baseline selection focused on methods that can be trained or applied under comparable computational budgets and data assumptions (access only to unlabeled normal training samples), thereby ensuring that performance differences reflect methodological contributions rather than disparities in pretraining data scale. To ensure fair comparison, all methods were evaluated using the same 5-fold data splits, preprocessing pipeline, evaluation metrics, and computational environment. Models were trained under the same UAD protocol using only normal training samples, with hyperparameters and thresholds selected on the validation set and final performance assessed only on the held-out test set. Table 1 summarizes 5-fold cross-validation results, and Figure 5 provides multi-metric radar chart comparisons.
As shown in Table 1 and Figure 5, RareCode achieves favorable detection performance and statistical stability on the CRC dataset. In terms of AUC, RareCode (96.82 ± 0.23%) outperforms multiple reconstruction-based baseline models, including MemAE (94.97 ± 0.81%). Statistical analysis confirms that RareCode outperforms all reconstruction-based baselines (paired t-tests, p < 0.05), with the improvement over MemAE reaching statistical significance (p < 0.01). RareCode exhibits low performance variance (standard deviation of 0.23%), indicating consistent cross-fold stability. The limited effectiveness of DRAEM, based on synthetic anomalies, likely reflects the fact that simple texture overlay strategies cannot adequately simulate complex pathological atypia.
Regarding specificity, RareCode achieves 58.24 ± 5.99%, outperforming all comparison methods in reducing false positive rates. This represents approximately a 25-percentage-point improvement over the reconstruction-only baseline (NoCAR, 33.76%), demonstrating the CAR mechanism's contribution to reducing false positives. The lower specificity of STFPM and PatchCore, which rely natural-image-pretrained features, may partially reflect the domain gap between natural and histopathological images. Notably, STFPM and DRAEM exhibit high specificity variance (±33.53% and ±7.09%), with per-fold specificity ranging from near-zero to moderate levels, raising concerns about their deployment reliability.
Per-class detection performance
Per-class analysis was conducted by separately comparing cancer and inflammation samples against normal samples (Table 2). RareCode achieved higher performance for cancer detection (AUC = 99.44 ± 0.12%, recall = 98.13 ± 0.29%, specificity = 94.21 ± 2.22%) than for inflammation detection (AUC = 94.30 ± 0.44%, recall = 96.55 ± 0.78%, specificity = 60.44 ± 4.34%). These findings suggest that RareCode may show stronger discrimination for malignant abnormalities than for inflammatory changes, whereas the inflammation-normal boundary appears to contribute substantially to the reduced overall specificity.
Ablation study
To investigate the contributions of key components within the RareCode framework, ablation experiments were conducted to assess the impact of the CAR mechanism and the MHC module on detection performance. Results are detailed in Table 3. As shown in Figure 6A, adding CAR to the reconstruction-only baseline improved AUC from 92.81% to 95.92%, and multi-scale codebook fusion further increased AUC to 96.82%. Figure 6B shows that CAR also improved specificity, increasing it from 33.76% in the NoCAR baseline to 58.24% in the full FourScales model. These results support the complementary value of codebook activation rarity and multi-scale fusion.
Additionally, a decoder-complexity ablation was conducted using the FourScales configuration. As shown in Table 3, the complex-decoder variant with multi-scale depthwise convolution blocks and Convolutional Block Attention Modules (CBAM) showed lower AUC than the basic FourScales model (95.17 ± 0.44% vs. 96.82 ± 0.23%). This result suggests that, within the present VQ-AE-based RareCode setting, increasing decoder capacity did not improve anomaly detection performance and may reduce the effectiveness of the codebook-constrained representation.
Hierarchical spatial response analysis
To examine the spatial responses generated by RareCode, patch-level reconstruction error and codebook rarity maps were aggregated at the image level and compared between normal and anomalous samples. Energy ratio, Cohen's d, and AUC were used to quantify image-level response separation. Detailed results are presented in Table 4 and Figure 7 and Figure 8.
Results show that codebook rarity scores at all scales exhibit response elevation on anomalous samples (energy ratios > 1). Smaller-capacity codebooks (Codebook 64) achieve stronger localization-level discrimination (78.79% AUC), consistent with the expectation that higher compression rates encourage learning of more abstract prototypical patterns that are more sensitive to deviations from normal tissue archetypes. Reconstruction error alone provides substantial anomaly capture capability (93.31% AUC), while CAR scores offer complementary signals from the semantic frequency dimension.
Qualitative examination of Figure 7 showed that elevated responses in cancer samples overlapped with irregular and crowded glands, nuclear enlargement, hyperchromasia, pseudostratification, and loss of epithelial polarity. In inflammatory samples, stronger responses were observed around distorted crypts and dense inflammatory-cell infiltrates. Lower-capacity codebooks tended to capture broader architectural deviations, whereas higher-capacity codebooks produced more localized cellular-level responses. These findings provide qualitative morphological interpretation but not pixel-level validation.
Fusion parameter analysis
The fusion weight α balances the contributions of spatial reconstruction error and the CAR score to the final anomaly score. Optimal α values for each fold were determined via a grid search (step size 0.05) on the validation sets, with the results presented in Table 5 and Figure 9. Optimal α values primarily concentrate in the 0.85-0.95 range, with a mean of 0.90 ± 0.05. Under optimal configurations, the model achieves an average AUC of 96.82 ± 0.23% on test sets. Higher optimal weights (approximately 0.90) suggest that CAR scores contribute more to final detection than reconstruction error, while reconstruction error provides auxiliary local constraints. Compared with the α = 0 setting in the sensitivity analysis (AUC = 93.29%), the validation-selected fusion setting improved AUC by approximately 3.53 percentage points.
To summarize the present work presents the RareCode framework for unsupervised anomaly detection in histopathological images, aiming to mitigate the identity-mapping problem encountered by traditional generative models. The CAR mechanism reduces over-reliance on pixel-level reconstruction errors, while the MHC module provides hierarchical feature representations at multiple granularities, enabling complementary anomaly discrimination at different levels of abstraction. Experiments on the CRC dataset demonstrate that RareCode achieves 96.82% AUC, with per-class analysis showing effective cancer detection (AUC = 99.44%) and stronger discrimination for cancer than inflammation, suggesting that inflammation-normal overlap remains a major challenge. Ablation studies confirm that integrating discrete semantic features from VQ with multi-scale tissue morphological representations improves detection performance. RareCode's high recall (98.40%) and moderate specificity (58.24%) suggest its potential as a pre-screening tool for prioritizing suspicious histopathological images; however, its actual effect on pathologist workload will require prospective workflow evaluation.
Data Availability:
The CRC histopathological image dataset used in this study was obtained from Shenzhen People's Hospital under institutional ethics approval (Approval No. LL-KY-2025300-01). Due to patient privacy and institutional data sharing policies, the dataset is not publicly available. Access may be granted upon reasonable request to the corresponding author, subject to institutional approval and data use agreements. The source code for the RareCode framework is publicly available at https://github.com/XL-alg/RareCode.

Figure 1: Overall architecture and data flow of the RareCode framework. A 512 × 512 H&E-stained histopathological image is divided into non-overlapping 32 × 32 and 64 × 64 patches as fine- and coarse-scale inputs. The two branches encode patches into latent embeddings, apply Multi-scale Hierarchical Codebook (MHC) discretization, and reconstruct patches to compute reconstruction-error scores. In parallel, the Codebook Activation Rarity (CAR) mechanism estimates semantic rarity from codebook activation-frequency profiles learned from normal training samples. Normalized reconstruction and CAR scores are then fused to generate the final image-level anomaly score, while patch-level responses are projected back to the image plane for hierarchical localization. Please click here to view a larger version of this figure.

Figure 2: Multi-scale vector quantization mechanism. (A) Distance computation between encoder output features and codebook embedding vectors. (B) Nearest neighbor selection and weighted fusion across codebooks with capacities of 64, 128, 256, and 512. (C) Reconstruction from quantized features via transposed convolutional decoder. Please click here to view a larger version of this figure.

Figure 3: CAR scoring mechanism. This figure illustrates four stages: Stage 1: activation frequency statistics are computed solely on normal training samples. Stage 2: test samples obtain activation indices and distances through encoder and vector quantization. Stage 3: rarity scores and distance scores are computed based on training-set frequency profiles. Stage 4: scores from each codebook scale are fused through learnable weights to produce the final CAR score. Please click here to view a larger version of this figure.

Figure 4: CRC dataset composition and experimental protocol. (A–C) Representative H&E-stained histopathological images of normal colorectal tissue, colorectal cancer, and colorectal inflammation. (D) 5-fold cross-validation protocol for UAD, in which normal samples were used for training and validation, while held-out normal and anomalous samples were used for testing. Images were digitized at 40x magnification and processed into 32 x 32 and 64 x 64 patches. Green, light green, and orange indicate training, validation, and test sets, respectively. Please click here to view a larger version of this figure.

Figure 5: Multi-metric comparison radar chart of anomaly detection methods. Radar chart comparing RareCode against baseline methods across AUC, average precision (AP), F1-score, precision, recall, and precision at 90% recall (P@R90). All values represent mean performance across 5-fold cross-validation. Please click here to view a larger version of this figure.

Figure 6: Incremental contribution analysis of ablation study components. (A) AUC performance comparison showing the progressive improvement from reconstruction-only baseline (NoCAR) through single-codebook to multi-scale configurations. (B) Specificity performance comparison demonstrating the CAR mechanism's effect on false positive reduction. All error bars represent standard deviation (SD) across 5-fold cross-validation. Please click here to view a larger version of this figure.

Figure 7: Multi-scale codebook hierarchical localization heatmaps. Representative examples are shown for (A) normal, (B) cancer, and (C) inflammation samples. Each row includes the original image, overlay, reconstruction-error map, rarity-score maps from codebooks of different capacities (64, 128, 256, and 512), and the final fused localization map. Smaller-capacity codebooks highlight coarse-grained patterns through stronger compression abstraction, whereas larger-capacity codebooks preserve finer structural details. High-response regions qualitatively correspond to cancer- or inflammation-related histopathological features, but were not validated with pixel-level expert annotations. Please click here to view a larger version of this figure.

Figure 8: Distribution histograms of different score types. Histograms compare score distributions between normal and anomalous samples for (A) reconstruction error, (B) combined CAR score, (C) Codebook 64, (D) Codebook 128, (E) Codebook 256, and (F) Codebook 512. Green and red histograms indicate normal and anomalous samples, respectively. Please click here to view a larger version of this figure.

Figure 9: Alpha parameter sensitivity analysis. (A) Validation-set AUC used for α selection. (B) Test-set AUC under different α values. The validation-selected α values ranged from 0.85 to 0.95, with a mean of 0.90 ± 0.05, consistent with Table 5. AUC variation remained below 0.5% when α varied within the [0.70, 1.00] range, indicating stable performance across a wide parameter range. Please click here to view a larger version of this figure.
| Method | AUC (%) | AP (%) | F1 (%) | Precision (%) | Recall (%) | Specificity (%) | P@R90 (%) |
| CAE | 90.37 ± 0.94 | 98.62 ± 0.18 | 95.34 ± 0.15 | 91.64 ± 0.40 | 99.35 ± 0.22 | 28.14 ± 3.88 | 95.66 ± 0.32 |
| SAE | 90.58 ± 0.94 | 98.66 ± 0.18 | 95.34 ± 0.15 | 91.67 ± 0.40 | 99.32 ± 0.24 | 28.46 ± 3.97 | 95.71 ± 0.30 |
| VAE | 93.60 ± 0.82 | 99.13 ± 0.12 | 95.86 ± 0.19 | 92.81 ± 0.49 | 99.12 ± 0.29 | 39.07 ± 4.70 | 96.94 ± 0.43 |
| MAE | 91.65 ± 2.75 | 98.76 ± 0.50 | 95.61 ± 0.60 | 92.87 ± 1.56 | 98.55 ± 0.55 | 39.74 ± 14.32 | 96.55 ± 0.97 |
| MemAE | 94.97 ± 0.81 | 99.35 ± 0.11 | 95.78 ± 0.33 | 92.82 ± 1.07 | 98.95 ± 0.60 | 39.15 ± 9.99 | 97.57 ± 0.33 |
| PatchSAE | 94.86 ± 0.36 | 99.34 ± 0.05 | 95.39 ± 0.13 | 92.32 ± 0.27 | 98.67 ± 0.12 | 34.91 ± 2.57 | 98.13 ± 0.24 |
| STFPM | 90.23 ± 3.05 | 98.70 ± 0.44 | 94.32 ± 0.21 | 91.90 ± 3.51 | 97.14 ± 3.38 | 29.82 ± 33.53 | 95.93 ± 1.96 |
| DRAEM | 76.34 ± 2.82 | 95.34 ± 0.90 | 94.19 ± 0.07 | 89.39 ± 0.65 | 99.56 ± 0.65 | 6.19 ± 7.09 | 92.69 ± 0.57 |
| PatchCore | 74.64 ± 1.82 | 94.76 ± 0.55 | 94.73 ± 0.05 | 90.52 ± 0.15 | 99.36 ± 0.12 | 17.49 ± 1.54 | 92.54 ± 0.15 |
| RareCode | 96.82 ± 0.23 | 99.59 ± 0.03 | 96.63 ± 0.15 | 94.93 ± 0.67 | 98.40 ± 0.48 | 58.24 ± 5.99 | 98.80 ± 0.10 |
Table 1: Comparison results with baseline methods (5-fold cross-validation). Detection performance of RareCode and nine baseline UAD methods on the CRC dataset. Metrics include AUC, average precision (AP), recall, specificity, F1-score, precision at 90% recall (P@R90), and precision. All values represent mean ± SD across 5-fold cross-validation. Bold values indicate the best performance for each metric.
| Category | AUC (%) | AP (%) | F1 (%) | Recall (%) | Specificity (%) |
| Cancer | 99.44 ± 0.12 | 99.86 ± 0.03 | 98.34 ± 0.17 | 98.13 ± 0.29 | 94.21 ± 2.22 |
| Inflammation | 94.30 ± 0.44 | 98.48 ± 0.12 | 93.44 ± 0.29 | 96.55 ± 0.78 | 60.44 ± 4.34 |
Table 2: Per-class detection performance across anomaly subtypes. Separate evaluation of RareCode's detection performance for cancer and inflammation samples against normal samples. Per-class metrics, including AUC, AP, F1-score, recall, and specificity, were computed using class-specific optimal thresholds.
| Variant | Codebook Config | CAR | AUC (%) | AP (%) | F1 (%) | Specificity (%) | P@R90 (%) |
| NoCAR |  |  | 92.81 ± 0.12 | 99.05 ± 0.02 | 95.30 ± 0.08 | 33.76 ± 3.82 | 96.72 ± 0.12 |
| SingleCodebook | [256] |  | 95.92 ± 0.40 | 99.47 ± 0.05 | 96.25 ± 0.14 | 55.37 ± 6.51 | 98.31 ± 0.43 |
| TwoScales | [128, 512] |  | 96.57 ± 0.27 | 99.56 ± 0.04 | 96.45 ± 0.12 | 57.75 ± 4.14 | 98.75 ± 0.12 |
| ThreeScales | [128, 256, 512] |  | 96.36 ± 0.37 | 99.53 ± 0.05 | 96.52 ± 0.17 | 57.99 ± 4.65 | 98.60 ± 0.23 |
| FourScales | [64, 128, 256, 512] |  | 96.82 ± 0.23 | 99.59 ± 0.03 | 96.63 ± 0.15 | 58.24 ± 5.99 | 98.80 ± 0.10 |
| FourScales + complex decoder | [64, 128, 256, 512] |  | 95.17 ± 0.44 | 99.39 ± 0.06 | 95.32 ± 0.20 | 53.83 ± 21.45 | 98.40 ± 0.37 |
Table 3: Ablation study results. Performance comparison of RareCode configurations with progressive addition of components: reconstruction-only baseline (NoCAR), single-codebook CAR (SingleCodebook), and multi-scale configurations (TwoScales, ThreeScales, FourScales). An additional decoder-complexity ablation using the FourScales configuration is also included. Metrics include AUC, average precision (AP), F1-score, specificity, and precision at 90% recall (P@R90).
| Score Type | Energy Ratio | Cohen's d | AUC (%) |
| Reconstruction Error | 2.623 | 2.006 | 93.31 |
| Combined CAR | 1.078 | 1.002 | 74.85 |
| Codebook 64 | 1.109 | 1.207 | 78.79 |
| Codebook 128 | 1.085 | 1.067 | 76.19 |
| Codebook 256 | 1.065 | 0.916 | 72.80 |
| Codebook 512 | 1.064 | 0.833 | 70.38 |
Table 4: Image-level analysis of localization-derived responses. Image-averaged reconstruction error and codebook rarity responses were compared between normal and anomalous samples using the energy ratio, Cohen's d, and AUC.
| Fold | Optimal α | Val AUC (%) | Test AUC (%) |
| 1 | 0.95 | 96.22 | 96.91 |
| 2 | 0.9 | 96.38 | 96.39 |
| 3 | 0.85 | 96.71 | 96.82 |
| 4 | 0.85 | 96.22 | 96.93 |
| 5 | 0.95 | 96.72 | 97.05 |
| Mean | 0.90 ± 0.05 | 96.45 ± 0.23 | 96.82 ± 0.23 |
Table 5: Optimal alpha values across folds. Optimal fusion weight alpha determined via grid search (step size 0.05) on validation sets for each cross-validation fold, with mean and SD statistics.