Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .claude/skills/trident/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ For the workflow and decisions, see [SKILL.md](SKILL.md).
- Entry points
- `run_batch_of_slides.py` flags
- `run_single_slide.py` flags
- Patch encoders (33) — embedding dim + required patch_size/mag
- Patch encoders (34) — embedding dim + required patch_size/mag
- Slide encoders — required patch encoder + patch_size/mag
- Segmenters & artifact removal
- WSI readers & formats
Expand Down Expand Up @@ -107,6 +107,7 @@ column is **required** for correct features — copy it verbatim.
|---|---:|---|
| `uni_v1` | 1024 | `--patch_size 256 --mag 20` |
| `uni_v2` | 1536 | `--patch_size 256 --mag 20` |
| `digepath` | 1024 | `--patch_size 256 --mag 20` |
| `conch_v1` | 512 | `--patch_size 512 --mag 20` |
| `conch_v15` (default) | 768 | `--patch_size 512 --mag 20` |
| `virchow` | 2560 | `--patch_size 224 --mag 20` |
Expand Down
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ This project was developed by the [Mahmood Lab](https://faisal.ai/) at Harvard M
<img align="right" src="_readme/trident_crop.jpg" width="250px" />

- **End-to-end pipeline**: tissue segmentation → patch coordinates → patch / slide embeddings, in one command (`--task all`) or stage-by-stage.
- **33 patch encoders**: [UNI](https://www.nature.com/articles/s41591-024-02857-3), [CONCHv1.5](https://huggingface.co/MahmoodLab/conchv1_5), [Virchow](https://www.nature.com/articles/s41591-024-03141-0), [Prov-GigaPath](https://huggingface.co/prov-gigapath/prov-gigapath), [H-Optimus-0](https://github.com/bioptimus/releases/tree/main/models/h-optimus/v0), etc.
- **34 patch encoders**: [UNI](https://www.nature.com/articles/s41591-024-02857-3), [Digepath](https://huggingface.co/xtxx/Digepath), [CONCHv1.5](https://huggingface.co/MahmoodLab/conchv1_5), [Virchow](https://www.nature.com/articles/s41591-024-03141-0), [Prov-GigaPath](https://huggingface.co/prov-gigapath/prov-gigapath), [H-Optimus-0](https://github.com/bioptimus/releases/tree/main/models/h-optimus/v0), etc.
- **Slide encoders**: [Titan](https://arxiv.org/abs/2411.19666), [GigaPath](https://www.nature.com/articles/s41586-024-07441-w), [PRISM](https://huggingface.co/paige-ai/Prism), [CHIEF](https://github.com/hms-dbmi/CHIEF), [Madeleine](https://huggingface.co/MahmoodLab/madeleine), [Feather](https://huggingface.co/MahmoodLab/abmil.base.conch_v15.pc108-24k).
- **Tissue segmentation**: [HEST](https://huggingface.co/MahmoodLab/hest-tissue-seg), [GrandQC](https://github.com/cpath-ukk/grandqc), or **Otsu** for CPU-only runs. Optional `--remove_artifacts` / `--remove_penmarks` clean-up pass.
- **Multiple WSI readers**: OpenSlide, CuCIM, plain images (`.png`, `.jpeg`), SDPC, OME-Zarr (`.zarr`), Zeiss CZI (`.czi`). Or convert to pyramidal TIFF with `trident convert`.
Expand Down Expand Up @@ -125,11 +125,12 @@ If embedded MPP metadata is detected in a slide, Trident compares it to the CSV
- **Outputs**:
- Features are saved as h5 files in `./trident_processed/20x_256px_0px_overlap/features_uni_v1`. (Shape: `(n_patches, feature_dim)`)

Trident supports 33 patch encoders, loaded via a patch [`encoder_factory`](https://github.com/mahmoodlab/trident/blob/main/trident/patch_encoder_models/load.py#L14). Models requiring specific installations will return error messages with additional instructions. Gated models on HuggingFace require access requests.
Trident supports 34 patch encoders, loaded via a patch [`encoder_factory`](https://github.com/mahmoodlab/trident/blob/main/trident/patch_encoder_models/load.py#L14). Models requiring specific installations will return error messages with additional instructions. Gated models on HuggingFace require access requests.

| Patch Encoder | Embedding Dim | Args | Link | License |
|-----------------------|---------------:|------------------------------------------------------------------|------|---------|
| **UNI** | 1024 | `--patch_encoder uni_v1 --patch_size 256 --mag 20` | [MahmoodLab/UNI](https://huggingface.co/MahmoodLab/UNI) | 🔒 [CC-BY-NC-ND-4.0](https://creativecommons.org/licenses/by-nc-nd/4.0/) |
| **Digepath** | 1024 | `--patch_encoder digepath --patch_size 256 --mag 20` | [xtxx/Digepath](https://huggingface.co/xtxx/Digepath) | 🔒 [CC-BY-NC-4.0](https://creativecommons.org/licenses/by-nc/4.0/) |
| **UNI2-h** | 1536 | `--patch_encoder uni_v2 --patch_size 256 --mag 20` | [MahmoodLab/UNI2-h](https://huggingface.co/MahmoodLab/UNI2-h) | 🔒 [CC-BY-NC-ND-4.0](https://creativecommons.org/licenses/by-nc-nd/4.0/) |
| **CONCH** | 512 | `--patch_encoder conch_v1 --patch_size 512 --mag 20` | [MahmoodLab/CONCH](https://huggingface.co/MahmoodLab/CONCH) | 🔒 [CC-BY-NC-ND-4.0](https://creativecommons.org/licenses/by-nc-nd/4.0/) |
| **CONCHv1.5** | 768 | `--patch_encoder conch_v15 --patch_size 512 --mag 20` | [MahmoodLab/conchv1_5](https://huggingface.co/MahmoodLab/conchv1_5) | 🔒 [CC-BY-NC-ND-4.0](https://creativecommons.org/licenses/by-nc-nd/4.0/) |
Expand Down
5 changes: 5 additions & 0 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,11 @@ Factory for loading patch-level encoder models.
- ``--patch_encoder uni_v1 --patch_size 256 --mag 20``
- `MahmoodLab/UNI <https://huggingface.co/MahmoodLab/UNI>`__
- 🔒 `CC-BY-NC-ND-4.0 <https://creativecommons.org/licenses/by-nc-nd/4.0/>`__
* - **Digepath**
- 1024
- ``--patch_encoder digepath --patch_size 256 --mag 20``
- `xtxx/Digepath <https://huggingface.co/xtxx/Digepath>`__
- 🔒 `CC-BY-NC-4.0 <https://creativecommons.org/licenses/by-nc/4.0/>`__
* - **UNI2-h**
- 1536
- ``--patch_encoder uni_v2 --patch_size 256 --mag 20``
Expand Down
3 changes: 2 additions & 1 deletion docs/faq.rst
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,7 @@ Environment and advanced usage
"conch_v1": "./ckpts/conch_patch_encoder/pytorch_model.bin",
"uni_v1": "./ckpts/uni_patch_encoder/pytorch_model.bin",
"uni_v2": "./ckpts/uni2_patch_encoder/pytorch_model.bin",
"digepath": "./ckpts/digepath_patch_encoder/model.safetensors",
"ctranspath": "./ckpts/ctranspath_patch_encoder/CHIEF_CTransPath.pth",
"phikon": "./ckpts/phikon_patch_encoder/pytorch_model.bin",
"resnet50": "./ckpts/resnet_patch_encoder/pytorch_model.bin",
Expand Down Expand Up @@ -366,4 +367,4 @@ Environment and advanced usage
try:
slide_encoder_model_factory(model)
except Exception as e:
print(f"Failed to download weights for {model}: {e}")
print(f"Failed to download weights for {model}: {e}")
2 changes: 1 addition & 1 deletion docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ Highlights

**Models**

- **22+ patch encoders**: UNI / UNI2-h, CONCH / CONCHv1.5, Virchow / Virchow2, Phikon /
- **22+ patch encoders**: UNI / UNI2-h, Digepath, CONCH / CONCHv1.5, Virchow / Virchow2, Phikon /
Phikon-v2, KEEP, Prov-GigaPath, H-Optimus 0/1, H0-mini, MUSK, Midnight-12k,
OpenMidnight, GPFM, GenBio-PathFM, Kaiko (5 variants), Lunit, Hibou-L, CTransPath,
ResNet50.
Expand Down
92 changes: 92 additions & 0 deletions tests/test_digepath_encoder.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import tempfile
import unittest
from pathlib import Path
from unittest.mock import MagicMock, patch

import torch
from PIL import Image

import run_batch_of_slides as batch_mod
from trident.patch_encoder_models import (
DigepathInferenceEncoder,
RESIZE_SUPPORTED_PATCH_ENCODERS,
encoder_factory,
encoder_registry,
)
from trident.patch_encoder_models.load import BasePatchEncoder


class TestDigepathEncoder(unittest.TestCase):
def test_public_registration(self):
self.assertIs(encoder_registry["digepath"], DigepathInferenceEncoder)
self.assertIn("digepath", RESIZE_SUPPORTED_PATCH_ENCODERS)

def test_batch_cli_accepts_digepath(self):
args = batch_mod.build_parser().parse_args([
"--job_dir", "job",
"--wsi_dir", "wsis",
"--patch_encoder", "digepath",
])
self.assertEqual(args.patch_encoder, "digepath")

@patch.object(BasePatchEncoder, "_has_internet", True)
@patch("timm.create_model")
def test_hub_loading_uses_official_model(self, create_model):
model = MagicMock()
create_model.return_value = model

encoder = encoder_factory("digepath")

create_model.assert_called_once_with(
"hf_hub:xtxx/Digepath",
pretrained=True,
init_values=1e-5,
dynamic_img_size=True,
)
self.assertIs(encoder.model, model)
self.assertEqual(encoder.precision, torch.float16)

@patch("safetensors.torch.load_file")
@patch("timm.create_model")
def test_local_safetensors_loads_strictly_on_native_grid(self, create_model, load_file):
model = MagicMock()
state_dict = {"weight": torch.ones(1)}
create_model.return_value = model
load_file.return_value = state_dict

with tempfile.NamedTemporaryFile(suffix=".safetensors") as checkpoint:
encoder = encoder_factory(
"digepath",
weights_path=checkpoint.name,
target_img_size=448,
)

create_model.assert_called_once_with(
"vit_large_patch16_224",
img_size=224,
patch_size=16,
init_values=1e-5,
num_classes=0,
dynamic_img_size=True,
)
load_file.assert_called_once_with(checkpoint.name, device="cpu")
model.load_state_dict.assert_called_once_with(state_dict, strict=True)

transformed = encoder.eval_transforms(Image.new("RGB", (256, 256)))
self.assertEqual(tuple(transformed.shape), (3, 448, 448))
normalize = encoder.eval_transforms.transforms[-1]
self.assertEqual(tuple(normalize.mean), (0.485, 0.456, 0.406))
self.assertEqual(tuple(normalize.std), (0.229, 0.224, 0.225))

def test_rejects_non_multiple_input_size_before_loading(self):
with self.assertRaisesRegex(AssertionError, "multiple.*16"):
encoder_factory("digepath", target_img_size=225)

def test_missing_local_checkpoint_is_clear(self):
missing = Path(tempfile.gettempdir()) / "missing-digepath-model.safetensors"
with self.assertRaisesRegex(FileNotFoundError, "Expected checkpoint file"):
encoder_factory("digepath", weights_path=str(missing))


if __name__ == "__main__":
unittest.main()
8 changes: 7 additions & 1 deletion tests/test_patch_encoders.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@ def test_uni_v1_forward(self):
def test_uni_v2_forward(self):
self._test_encoder_forward('uni_v2')

def test_digepath_forward(self):
self.assertEqual(self._output_dim('digepath'), 1024)

def test_ctranspath_forward(self):
self._test_encoder_forward('ctranspath')

Expand Down Expand Up @@ -207,6 +210,9 @@ def test_uni_v2_resize(self):
# patch_size 14 -> 448 is a multiple.
self._test_encoder_resize('uni_v2', target_img_size=448)

def test_digepath_resize(self):
self._test_encoder_resize('digepath', target_img_size=448)

def test_virchow_resize(self):
self._test_encoder_resize('virchow', target_img_size=448)

Expand Down Expand Up @@ -258,4 +264,4 @@ def test_resize_rejects_unsupported_encoder_path(self):
encoder_factory('conch_v15', target_img_size=448)

if __name__ == '__main__':
unittest.main()
unittest.main()
2 changes: 2 additions & 0 deletions trident/patch_encoder_models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
ResNet50InferenceEncoder,
UNIInferenceEncoder,
UNIv2InferenceEncoder,
DigepathInferenceEncoder,
GigaPathInferenceEncoder,
GigaPathFlashInferenceEncoder,
VirchowInferenceEncoder,
Expand Down Expand Up @@ -51,6 +52,7 @@
"ResNet50InferenceEncoder",
"UNIInferenceEncoder",
"UNIv2InferenceEncoder",
"DigepathInferenceEncoder",
"GigaPathInferenceEncoder",
"GigaPathFlashInferenceEncoder",
"VirchowInferenceEncoder",
Expand Down
69 changes: 68 additions & 1 deletion trident/patch_encoder_models/load.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
# `_resolve_target_img_size` for the validation rules.
RESIZE_SUPPORTED_PATCH_ENCODERS = frozenset({
# Category A: dynamic_img_size already enabled on the timm backbone.
"uni_v1", "uni_v2", "virchow", "virchow2", "virchow2-cls",
"uni_v1", "uni_v2", "digepath", "virchow", "virchow2", "virchow2-cls",
"kaiko-vitb8", "kaiko-vitb16", "kaiko-vits8", "kaiko-vits16", "kaiko-vitl14",
# Category B: dynamic_img_size enabled as part of this feature.
"gigapath", "gigapath-flash", "hoptimus0", "hoptimus1", "gpfm", "lunit-vits8", "h0-mini",
Expand Down Expand Up @@ -69,6 +69,7 @@ def encoder_factory(model_name: str, **kwargs) -> torch.nn.Module:
- "conch_v15"
- "uni_v1"
- "uni_v2"
- "digepath"
- "ctranspath"
- "phikon"
- "phikon_v2"
Expand Down Expand Up @@ -839,6 +840,71 @@ def _build(

precision = torch.float16
return model, eval_transform, precision


class DigepathInferenceEncoder(BasePatchEncoder):
"""Digepath ViT-L/16 encoder for gastrointestinal pathology images."""

def __init__(self, **build_kwargs):
super().__init__(**build_kwargs)

def _build(self, target_img_size=None):
import timm
from safetensors.torch import load_file
from torchvision import transforms

self.enc_name = "digepath"
img_size = _resolve_target_img_size(self.enc_name, target_img_size, 224, 16)
weights_path = self._get_weights_path()

if weights_path:
try:
# Keep the backbone on its native 224 grid so the released 197-token
# positional embedding loads strictly. ``dynamic_img_size`` performs
# interpolation at forward time for non-native input resolutions.
model = timm.create_model(
"vit_large_patch16_224",
img_size=224,
patch_size=16,
init_values=1e-5,
num_classes=0,
dynamic_img_size=True,
)
model.load_state_dict(load_file(weights_path, device="cpu"), strict=True)
except Exception:
traceback.print_exc()
raise Exception(
f"Failed to create Digepath model from local checkpoint at '{weights_path}'. "
"You can download the required `model.safetensors` from: "
"https://huggingface.co/xtxx/Digepath."
)
else:
self.ensure_has_internet(self.enc_name)
try:
model = timm.create_model(
"hf_hub:xtxx/Digepath",
pretrained=True,
init_values=1e-5,
dynamic_img_size=True,
)
except Exception:
traceback.print_exc()
raise Exception(
"Failed to download Digepath. Accept the gated model terms at "
"https://huggingface.co/xtxx/Digepath and authenticate with a valid "
"Hugging Face token."
)

eval_transform = transforms.Compose([
transforms.Resize(img_size),
transforms.ToTensor(),
transforms.Normalize(
mean=(0.485, 0.456, 0.406),
std=(0.229, 0.224, 0.225),
),
])

return model, eval_transform, torch.float16


class UNIv2InferenceEncoder(BasePatchEncoder):
Expand Down Expand Up @@ -2063,6 +2129,7 @@ def __init__(self, **build_kwargs):
"conch_v15": Conchv15InferenceEncoder,
"uni_v1": UNIInferenceEncoder,
"uni_v2": UNIv2InferenceEncoder,
"digepath": DigepathInferenceEncoder,
"ctranspath": CTransPathInferenceEncoder,
"phikon": PhikonInferenceEncoder,
"phikon_v2": Phikonv2InferenceEncoder,
Expand Down
3 changes: 2 additions & 1 deletion trident/patch_encoder_models/local_ckpts.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"conch_v1": "",
"uni_v1": "",
"uni_v2": "",
"digepath": "",
"ctranspath": "",
"phikon": "",
"resnet50": "",
Expand Down Expand Up @@ -31,4 +32,4 @@
"gemma4-e4b": "",
"gemma4-26b": "",
"custom_encoder": ""
}
}