CoolFace
Modelpublic

taejoon89/openpath

sourceHugging Faceapache-2.0updated 2mo agoView on Hugging Face
1likes17downloads
README.md247 linesDownload Raw Back to root
1---2license: apache-2.03tags:4  - pathology5  - histopathology6  - foundation-model7  - self-supervised8  - dinov29  - vision-transformer10  - digital-pathology11library_name: pytorch12pipeline_tag: image-feature-extraction13---14 15# OpenPath: Public-Data Pathology Foundation Models and Leakage-Free Evaluation16 17*Training, reproduction, and evaluation code.*18 19๐Ÿ”— **[GitHub](https://github.com/taejoon89/openpath)** ยท [Checkpoints](https://huggingface.co/taejoon89/openpath-checkpoints) ยท [Corpus](https://huggingface.co/datasets/taejoon89/openpath-corpus)20 21**OpenPath** is a vision foundation model for computational pathology: a **ViT-g/14** encoder22pre-trained with self-supervision (**DINOv2** + **gram anchoring**) on **public-only** whole-slide23histopathology tiles. This repository contains the **training, reproduction, and evaluation code**24plus the **released weight** (`teacher_checkpoint.pth` = `training_316250`). The corpus and the full25checkpoint set are hosted separately (see below).26 27> **Headline result.** On **AMC-HCC-ST** โ€” a contamination-free in-house Asan Medical Center28> hepatocellular-carcinoma spatial-transcriptomics cohort, the least leakage-prone benchmark since no29> public foundation model was trained on it โ€” OpenPath **ranks #1 among seven foundation models** (mean30> Pearson: OpenPath **0.323** > UNI2-h 0.301 > OpenMidnight 0.300 > Virchow2 0.292 > prov-gigapath 0.286 >31> Phikon-v2 0.274 > UNI 0.257). Released checkpoint: **`training_316250`** (in `openpath-checkpoints`).32> See [Evaluation](#evaluation).33 34- **Encoder:** ViT-g/14 (reg4), 1536-dim CLS embedding35- **Objective:** DINO + iBOT + KDE (DINOv2) with **gram anchoring** (technique from DINOv3, re-implemented)36- **Data:** public pathology WSIs only (TCGA, TCIA, GTEx, CAMELYON, ACROBAT, SurGen, โ€ฆ), re-tiled at native 40ร—37- **Warm start:** Meta DINOv2 ViT-g/14-reg38- **Training:** FSDP (SHARD_GRAD_OP), bf16, flat learning-rate schedule, 40ร— B200 (multi-node)39 40## Repository layout41 42```43OpenPath/                                      # DINOv2 training fork (derived from OpenMidnight)44  dinov2/train/train.py                        # training loop (+ gram-weight schedule)45  dinov2/train/ssl_meta_arch.py                # SSL arch (+ frozen gram-anchor teacher)46  dinov2/loss/gram_loss.py                     # gram anchoring loss (clean-room re-impl, Apache-2.0)47  dinov2/data/openpath_wds.py                  # WebDataset loader for the OpenPath corpus48  dinov2/configs/train/openpath_vitg14.yaml    # training config49scripts/50  launch.sh                  # multi-node launcher (host + workers, 40 GPU)51  autoresume.sh              # crash-tolerant auto-resume52  watch_eval.sh              # online HEST probing per checkpoint53  run_hest_3way.py           # HEST evaluation (Meta DINOv2 / Phikon-v2 / OpenPath)54eval/                                          # downstream benchmark / reference-FM comparison55  openpath_eva_backbone.py   # backbone factories: OpenPath + Phikon / OpenMidnight / UNI / UNI2-h / gigapath / Virchow256  st_bench.py                # AMC-HCC-ST benchmark (LOPO ridge, headline)57  run_patch_eval.sh          # PCam / CRC / BACH patch probing via kaiko-eva58  run_hest_ref.py            # HEST-1K for reference FMs (UNI / UNI2-h / gigapath / Virchow2)59  eva_configs/               # eva YAML configs (crc / bach / patch_camelyon)60requirements.txt61```62 63## Related artifacts64 65| Artifact | Hugging Face repo | Notes |66|---|---|---|67| **Corpus** | `taejoon89/openpath-corpus` | Native 40ร— pathology tiles, 33,991 WebDataset shards / ~17 TB |68| **Checkpoints** | `taejoon89/openpath-checkpoints` | full teacher-checkpoint set (`training_0` โ€ฆ `training_345000`) |69| **Code + weight** | `taejoon89/openpath` | This repository โ€” code + the released `teacher_checkpoint.pth` (= `training_316250`). Code mirror: [GitHub](https://github.com/taejoon89/openpath) |70 71The training config points to the corpus via72`train.sample_list_path: "openpath:glob=<corpus>/*/tiles/shards/w*/*.tar"`. The gram anchor73(`gram.ckpt`) is an earlier OpenPath teacher checkpoint from `openpath-checkpoints`.74 75## Method โ€” gram anchoring76 77Long self-supervised training degrades dense/patch features. Following **DINOv3**, we add a78**gram anchoring** loss: the MSE between the L2-normalized patch-token Gram (similarity) matrices79of the student and a **frozen anchor** model (a strong earlier checkpoint). The loss weight is `40`80and it activates near the dense-feature peak (iteration `57,500`) with a 3k-iter ramp. This81**dampens the post-peak decline** of dense representations while DINO/iBOT keep optimizing the82global representation.83 84## Key hyper-parameters85 86| | |87|---|---|88| Arch | `vit_giant2`, patch 14, 4 register tokens, SwiGLU FFN |89| Batch | 64 / GPU ร— 40 GPU = global 2560 |90| LR | base 2e-4 (effective โ‰ˆ 3.16e-4 @ global 2560), flat (near-constant) |91| Schedule | `epochs: 8000` horizon, `early_stop: 276` โ‰ˆ 345k iters โ‰ˆ 1 native epoch |92| gram | weight 40, `it_first_update 57500`, ramp 3000, normalized, remove-neg |93| Precision | bf16, FSDP SHARD_GRAD_OP, sinkhorn-knopp centering |94 95## Reproducing training96 97```bash98export PYTHONPATH="$PWD/OpenPath"99CFG=OpenPath/dinov2/configs/train/openpath_vitg14.yaml100# edit CFG: train.sample_list_path (corpus glob), gram.ckpt (anchor checkpoint), MODEL.WEIGHTS (DINOv2 warm-start)101# set your cluster (see scripts/launch.sh header): MASTER_NODE, WORKER_NODES, MASTER_ADDR, NCCL_IB_HCA, *_SOCKET_IFNAME102export MASTER_NODE=node1 WORKER_NODES="node2 node3 node4 node5" MASTER_ADDR=<master-ib-ip>103bash scripts/launch.sh openpathrun "$CFG" <output_dir> <log_dir>104# optionally run scripts/autoresume.sh (background) and scripts/watch_eval.sh (online HEST)105```106 107Extract CLS embeddings for downstream use (`teacher_checkpoint.pth` = the released `training_316250`,108included in this repo):109 110```python111import torch, dinov2.models.vision_transformer as vits112ck = torch.load("teacher_checkpoint.pth", map_location="cpu", weights_only=False)113sd = {k[len("backbone."):]: v for k, v in ck["teacher"].items() if k.startswith("backbone.")}114m = vits.vit_giant2(patch_size=14, img_size=224, block_chunks=4, num_register_tokens=4,115                    ffn_layer="swiglufused", init_values=1e-5,116                    interpolate_antialias=True, interpolate_offset=0.0)117m.load_state_dict(sd, strict=True); m.eval()118cls = m.forward_features(x)["x_norm_clstoken"]   # (B, 1536)119```120 121## Evaluation122 123Frozen-encoder linear/ridge probing. The headline benchmark is **AMC-HCC-ST** โ€” a124**contamination-free** in-house Asan Medical Center hepatocellular-carcinoma Visium125spatial-transcriptomics cohort (leave-one-patient-out, mean Pearson over top-50 highly-variable126genes) โ€” **no public FM was trained on it**, so it is the least leakage-prone comparison. The127reported OpenPath checkpoint is `training_316250`.128 129**Comparison** โ€” all 7 models loaded through one backbone factory and probed under an identical130protocol; sorted by the clean AMC-HCC-ST benchmark:131 132| Model | AMC-HCC-ST (clean) โ†“ | HEST-1K (public) | NCT-CRC-HE (9-cls acc) | BACH (4-cls acc) |133|---|---|---|---|---|134| **OpenPath** | **0.323** | 0.372 | 0.954 | 0.761 |135| UNI2-h | 0.301 | 0.414 | 0.966 | 0.908 |136| OpenMidnight | 0.300 | 0.390 | 0.967 | 0.906 |137| Virchow2 | 0.292 | 0.398 | 0.964 | 0.875 |138| prov-gigapath | 0.286 | 0.393 | 0.953 | 0.752 |139| Phikon-v2 | 0.274 | 0.375 | 0.937 | 0.708 |140| UNI | 0.257 | 0.386 | 0.946 | 0.777 |141 142**On the contamination-free AMC-HCC-ST cohort OpenPath ranks #1** among all seven foundation models.143The picture inverts on the **public** benchmarks (HEST-1K, CRC, BACH): there OpenPath is mid-pack to144low, and the large FMs lead. Those benchmarks derive from public repositories (TCGA/GTEx/etc.) that145these FMs were pre-trained on, so their apparent edge is confounded by **train/test leakage** โ€” which146is exactly why the leakage-free AMC-HCC-ST cohort is our headline. (The reported checkpoint147`training_316250` is selected by AMC-HCC-ST; OpenPath's HEST-1K peaks earlier in training at ~0.38.)148PCam / CAMELYON is excluded because it overlaps our own training corpus.149 150### Reproducing the comparison151 152All models are loaded through a single backbone-factory module (`eval/openpath_eva_backbone.py`) and153probed under an identical protocol, so OpenPath and the reference FMs (Phikon-v2, OpenMidnight, UNI,154UNI2-h, gigapath, Virchow2) are directly comparable.155 156```bash157export PYTHONPATH="$PWD/OpenPath:$PWD/eval"158# Headline: AMC-HCC-ST (LOPO ridge; cohort is private, code is provided)159python eval/st_bench.py --backbone openpath --weights <teacher_checkpoint.pth>160python eval/st_bench.py --backbone uni              # reference FM (also: uni2 / gigapath / virchow2 / phikon / openmidnight)161 162# Patch probing (PCam / CRC / BACH) via kaiko-eva163bash eval/run_patch_eval.sh openpath crc <teacher_checkpoint.pth>164bash eval/run_patch_eval.sh uni crc                 # reference FM165```166 167Reference FM weights are pulled from their Hugging Face hubs on first use (UNI / UNI2-h / Virchow2168are gated โ€” request access on HF beforehand).169 170### Evaluate your model on AMC-HCC-ST โ€” we run it for you171 172AMC-HCC-ST is an in-house, **contamination-free** spatial-transcriptomics cohort that we are actively173**curating and expanding** at Asan Medical Center. Because it is patient-derived, the cohort **cannot174be publicly redistributed**. Rather than keep it as an internal-only benchmark, **we offer to run the175evaluation on your behalf** โ€” send us your pathology encoder and we return its AMC-HCC-ST score under176the exact protocol used above (leave-one-patient-out ridge, top-50 HVG, mean Pearson), directly177comparable to the reference models.178 179**What to send**180- **Weights** โ€” a `teacher_checkpoint.pth` / `state_dict`, or a public Hugging Face / `timm` hub id.181- **A loader** โ€” a small `build()` returning an `nn.Module` that maps a normalized `(B, 3, 224, 224)`182  batch to a `(B, d)` tile embedding (CLS or pooled), plus the expected input normalization183  (ImageNet by default). See `eval/openpath_eva_backbone.py` for the exact interface we use.184- **Optional** โ€” a one-line model description and license so we can report your result correctly.185 186Every submission runs through the same single backbone-factory + probing pipeline (`eval/`), so your187numbers are apples-to-apples with the table above. This keeps the benchmark **leakage-controlled and188open to the community** even though the underlying data stays private.189 190**Contact:** open a discussion on the [`taejoon89/openpath`](https://huggingface.co/taejoon89/openpath)191model repo, or email **taejoon@amc.seoul.kr**.192 193## Intended use & limitations194 195**Intended use.** OpenPath is a **frozen feature extractor** for H&E histopathology. It produces a1961536-dim CLS embedding per 224ร—224 tile (native ~40ร— / 0.5 ยตm-per-pixel regime, ImageNet197normalization) for downstream **linear/ridge probing, k-NN, MIL aggregation, and retrieval**. It is a198research artifact, **not a medical device**, and must not be used for diagnosis or clinical199decision-making.200 201**Limitations.**202- **Public-benchmark leakage.** Public benchmarks (HEST-1K, NCT-CRC-HE, BACH) derive from repositories203  (TCGA/GTEx/โ€ฆ) that many foundation models โ€” and partly OpenPath โ€” were pre-trained on. Absolute204  numbers and cross-model rankings on them are confounded; prefer leakage-controlled evaluation.205- **Checkpoint trade-off.** The released `training_316250` is selected by the clean AMC-HCC-ST benchmark;206  earlier checkpoints score higher on HEST-1K (~0.38). Pick a checkpoint to match your downstream task.207- **Domain.** Trained on H&E WSIs at native magnification. Behavior on IHC, cytology, frozen sections,208  non-0.5 ยตm-per-pixel inputs, or non-pathology images is untested.209- **Patch-level encoder.** OpenPath encodes tiles independently; slide-level context requires a210  separate aggregator (future work).211 212## Citation213 214A paper is in preparation. Until then, please cite the repository and the upstream work it builds on:215 216```bibtex217@misc{openpath2026,218  title  = {OpenPath: Public-Data Pathology Foundation Models and Leakage-Free Evaluation},219  author = {Tae Joon Jun},220  year   = {2026},221  note   = {https://huggingface.co/taejoon89/openpath}222}223```224 225OpenPath builds on **DINOv2**, **OpenMidnight / Midnight**, and **gram anchoring (DINOv3)** โ€” see226`OpenPath/README.md` for the full upstream citations, which should also be cited.227 228## Acknowledgements229 230This research was supported by a grant of the Korea Health Technology R&D Project through the Korea231Health Industry Development Institute (KHIDI), funded by the Ministry of Health & Welfare, Republic of232Korea (grant number: HR21C0198); the Advanced GPU Utilization Support Program funded by the Government233of the Republic of Korea, Ministry of Science and ICT; and the National Research Foundation of Korea234(NRF) grant funded by the Korean government (MSIT) (grant number: RS-2026-25522634).235 236## License237 238**Code โ€” Apache-2.0.** This repository is a fork of **DINOv2 / OpenMidnight** (both Apache-2.0); see239`OpenPath/LICENSE`. The gram-anchoring loss (`OpenPath/dinov2/loss/gram_loss.py`) is a **clean-room240re-implementation** of the DINOv3 technique โ€” written from its mathematical description and verified241to be numerically equivalent โ€” so it is Apache-2.0 as well, and the codebase contains **no242non-commercial (DINOv3-licensed) code**.243 244**Weights โ€” Apache-2.0** (warm-started from Meta DINOv2 ViT-g/14-reg, itself Apache-2.0).245 246**Training data:** public pathology datasets under CC-BY / CC0 / NIH-open terms (redistributable).247