Beyond Spatial Smoothing: Aligning Transcriptomic Heterogeneity for Gene Expression Prediction from Histopathology
Benchmark data · UNI2-h · Quick start · Results
FRECKLE predicts expression for 250 genes at each measured spot on an H&E slide. A frozen UNI2-h encoder represents each spot with one global feature and four regional features. During training, FRECKLE aligns relationships between spot embeddings with those between their expression profiles. Whole-slide attention then supplies context for gene prediction.
Use Linux with Python 3.10 and a CUDA-compatible NVIDIA GPU. The reference environment uses PyTorch 2.7.1 / CUDA 11.8 on an A100 80 GB.
git clone https://github.com/MAGIC-AI4Med/FRECKLE.git
cd FRECKLE
python3.10 -m venv .venv
source .venv/bin/activate
python -m pip install --no-deps \
--index-url https://download.pytorch.org/whl/cu118 \
torch==2.7.1+cu118 torchvision==0.22.1+cu118
python -m pip install --index-url https://pypi.org/simple -r requirements.txtRun the remaining commands from the repository root in the same Bash session. Set WORK to a location with room for the data, weights and training outputs.
WORK="$HOME/freckle-work"
DATA="$WORK/data"
WEIGHTS="$WORK/weights/uni2-h/pytorch_model.bin"
FEATURES="$WORK/features"
RUNS="$WORK/runs"
EVAL="$WORK/evaluation"
mkdir -p "$WORK"Download the authors' preprocessed benchmark archive following the MERGE data instructions. Save it as $WORK/data.tar.gz and extract:
tar -xf "$WORK/data.tar.gz" -C "$WORK"$DATA should now contain stnet/, her2st/, and skin/ (SCC). FRECKLE uses the supplied images and counts_spcs_to_8n targets at measured spots. See input and output formats for the expected files.
Access required. Request UNI2-h access with your own Hugging Face account and institutional email. Review the provider’s terms. After approval, sign in locally and download the pinned checkpoint.
huggingface-cli login
huggingface-cli download MahmoodLab/UNI2-h pytorch_model.bin \
--revision d517a8dd47902dd7c308b3c36f63bce47e7b9a43 \
--local-dir "$WORK/weights/uni2-h"The extractor checks the weight file’s SHA-256 before loading it. The expected digest is in Reproducibility details.
for ds in stnet her2st scc; do
python extract_features.py --dataset "$ds" --data-root "$DATA" \
--weights "$WEIGHTS" --out "$FEATURES" --device cuda:0 || exit 1
doneTraining and evaluation read the saved features, spot IDs and coordinates from $FEATURES.
Train a single fold (ST-Net, fold 0):
CUDA_VISIBLE_DEVICES=0 python main.py train --dataset stnet --fold 0 \
--data-root "$DATA" --features "$FEATURES" --out "$RUNS"Or train all 24 folds sequentially on one GPU:
CUDA_VISIBLE_DEVICES=0 bash scripts/run_benchmark.sh train \
"$DATA" "$FEATURES" "$RUNS"Use a fresh $RUNS directory for a cold start. The runner can resume a compatible run from its last completed pass. Resume only checkpoints from your own runs.
Evaluate the selected checkpoint of a single fold:
CUDA_VISIBLE_DEVICES=0 python main.py evaluate --dataset stnet --fold 0 \
--data-root "$DATA" --features "$FEATURES" \
--checkpoint "$RUNS/stnet/fold_0/selected.pt" --out "$EVAL"Or evaluate and summarize the complete benchmark:
CUDA_VISIBLE_DEVICES=0 bash scripts/run_benchmark.sh evaluate \
"$DATA" "$FEATURES" "$RUNS" "$EVAL"To aggregate existing evaluation records again:
python main.py summarize --runs "$EVAL"Each dataset score is the mean of eight slide-level folds. Within each fold, the held-out slides determine the checkpoint (lowest MSE, earliest pass on a tie) and supply the reported scores.
| Dataset | MSE ↓ | MAE ↓ | GenePCC ↑ |
|---|---|---|---|
| ST-Net | 0.1120 | 0.2573 | 0.7305 |
| HER2ST | 0.5669 | 0.5763 | 0.5677 |
| SCC | 0.4410 | 0.5140 | 0.5954 |
On the reference A100 setup, cold-start training reproduced all 24 selected passes and all 72 unrounded fold scores. The saved held-out predictions matched the reference runs element for element.
Show the repository tree
FRECKLE/
├── configs/ # Initialization and checkpoint compatibility
├── engine/ # Objective, training and evaluation
├── model/ # FRECKLE architecture
├── scripts/ # Benchmark runner
├── utils/ # Data loading and provenance
├── data.py # Benchmark data and feature I/O
├── extract_features.py # Frozen UNI2-h feature extraction
├── main.py # Train, evaluate, summarize
├── requirements.txt
├── README.md
└── LICENSE
Reference environment and external assets
-
Linux x86-64, Python 3.10.20, PyTorch 2.7.1+cu118, torchvision 0.22.1+cu118, NVIDIA A100 80 GB; tested driver 580.126.20. Dependencies are pinned in
requirements.txt. PyTorch wheels. -
Verify the installation:
python - <<'PYTHON' import torch import torchvision print(torch.__version__, torchvision.__version__, torch.version.cuda) assert torch.cuda.is_available() PYTHON
-
Benchmark archive:
1,208,597,608bytes; the.tar.gzfile contains XZ-compressed data, which GNU tar detects. Expected SHA256:89e863dee4278407544e6ede74654a064492bf2fe6148451cccca0c1c1b16f79 -
UNI2-h checkpoint expected SHA256:
6e077eda234bebc595868d918d3458d9dd32a050199b0ff04443b2f46a0a3b1eCheck the files with
sha256sum "$WORK/data.tar.gz" "$WEIGHTS". Resolve any digest mismatch before extraction. HTTP 401/403 requires checking your own login and model approval. See the pinned Hub CLI documentation and the UNI2-h model card and access terms. The provider specifies CC BY-NC-ND 4.0 and additional conditions for noncommercial academic research, attribution, redistribution, and derivatives. These terms continue to apply independently of the FRECKLE code license.
Benchmark inputs, feature cache, and run outputs
The benchmark uses the supplied JPEG WSIs and SPCS-smoothed expression rescaled to the eight-neighbor reference. The FP32 targets preserve signed values and the original gene order. The archive uses the directory name skin, while the CLI uses scc.
data/
├── stnet/
│ ├── wsi/ # SLIDE.jpg
│ ├── barcodes/ # SLIDE.csv, ordered measured spots
│ ├── tissue_positions/ # SLIDE.csv, array and pixel coordinates
│ ├── features/ # SLIDE.csv, ordered gene names
│ └── counts_spcs_to_8n/ # SLIDE.npy, N × 250 targets
├── her2st/ # same layout
└── skin/ # same layout (SCC)
| Dataset | Slides | Measured spots |
|---|---|---|
| ST-Net | 68 | 30,627 |
| HER2ST | 36 | 13,620 |
| SCC | 12 | 8,671 |
The sorted stems of barcodes/*.csv define each dataset's slide list. To list the slides:
python - "$DATA" <<'PYTHON'
import sys
from data import DATASETS, slide_names
for dataset in DATASETS:
print(f"{dataset}: " + ", ".join(slide_names(sys.argv[1], dataset)))
PYTHONFeature extraction uses measured-spot barcode order, 256 × 256 RGB windows shifted inward at boundaries, and bilinear resizing to 224 × 224. The frozen UNI2-h runs in FP32 evaluation mode with batch size 32. From the final normalized tokens, the CLS feature is retained and eight register tokens are excluded from the 16 × 16 spatial grid. Four 8 × 8 regions are mean-pooled in top-left, top-right, bottom-left, bottom-right order. No extra L2 normalization is applied.
features/DATASET/SLIDE/
├── cls.npy # FP32, N × 1536
├── regions.npy # FP32, N × 4 × 1536
├── coordinates.npy # FP32, N × 2 array coordinates
├── ids.npy # ordered stable spot IDs
└── manifest.json # input, source and output checksums
The loader verifies feature hashes, coordinates and IDs. Extraction reuses only a complete matching feature directory.
Training writes selected.pt, resume.pt, run.json, pass history, and complete.json under $RUNS/DATASET/fold_N/. The resume state includes model, optimizer, scheduler, RNGs, data-loader state and incumbent selected weights. The completion record stores the full training budget and the selected checkpoint digest.
Evaluation writes metrics.json and predictions.npz under $EVAL/DATASET/fold_N/.
Training and evaluation protocol
- Seed 3927, sorted slide IDs with shuffled eight-fold KFold, 1,500 complete passes per fold, one Adam update per training slide, and 7,280,890 trainable parameters.
- The full model receives MSE gradients. The single row-wise forward KL acts on the pre-context representation of measured training spots, with temperature 0.1 and a linear 50-pass ramp to 0.05. The protected auxiliary update affects only the two projection weight matrices. The cosine scheduler steps after each optimizer update and again at each pass boundary.
- After each complete pass, evaluate all measured spots in the outer held-out slides. Select the first pass attaining the strict minimum held-out plain MSE. This same held-out fold supplies the reported benchmark, consistent with the adopted protocol. Only training slides contribute to gradients and relational supervision.
- Within each fold, MSE and MAE pool all held-out spot–gene entries. GenePCC averages Pearson correlations over the 250 genes across pooled measured spots, assigning zero when the FP32 Pearson denominator is zero. Dataset means equally average the eight unrounded fold scores.
- Training and evaluation records retain input and source identities. The compatibility configuration binds explicitly verified source digests while preserving split, gene, spot and feature checks. The bitwise comparison was performed on the reference A100 setup.
FRECKLE was implemented by Zhuoyan Ge (@ZhuoyanGe).
We thank the authors of MERGE, FEAST, and UNI. Please also cite the original ST-Net, HER2ST, and SCC studies when using their data.
FRECKLE's original source code is released under the MIT License.
The benchmark datasets, UNI2-h weights, and other third-party assets are distributed and licensed by their respective providers. Their terms also govern derivative artifacts where specified. This release does not redistribute or relicense these assets. See the MERGE data instructions and UNI2-h model card.