From 0120b8bf2b3e8f26af19725091d2137f06abdcb9 Mon Sep 17 00:00:00 2001 From: LanTing-0119 Date: Mon, 7 Sep 2026 04:52:46 +0800 Subject: [PATCH] Add native Digepath patch encoder support --- .claude/skills/trident/reference.md | 3 +- README.md | 5 +- docs/api.rst | 5 + docs/faq.rst | 3 +- docs/index.rst | 2 +- tests/test_digepath_encoder.py | 92 +++++++++++++++++++ tests/test_patch_encoders.py | 8 +- trident/patch_encoder_models/__init__.py | 2 + trident/patch_encoder_models/load.py | 69 +++++++++++++- trident/patch_encoder_models/local_ckpts.json | 3 +- 10 files changed, 184 insertions(+), 8 deletions(-) create mode 100644 tests/test_digepath_encoder.py diff --git a/.claude/skills/trident/reference.md b/.claude/skills/trident/reference.md index 1da68e0c..18ee1c6b 100644 --- a/.claude/skills/trident/reference.md +++ b/.claude/skills/trident/reference.md @@ -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 @@ -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` | diff --git a/README.md b/README.md index 496f04c0..22b83e27 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ This project was developed by the [Mahmood Lab](https://faisal.ai/) at Harvard M - **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`. @@ -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/) | diff --git a/docs/api.rst b/docs/api.rst index 29624878..16922168 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -136,6 +136,11 @@ Factory for loading patch-level encoder models. - ``--patch_encoder uni_v1 --patch_size 256 --mag 20`` - `MahmoodLab/UNI `__ - 🔒 `CC-BY-NC-ND-4.0 `__ + * - **Digepath** + - 1024 + - ``--patch_encoder digepath --patch_size 256 --mag 20`` + - `xtxx/Digepath `__ + - 🔒 `CC-BY-NC-4.0 `__ * - **UNI2-h** - 1536 - ``--patch_encoder uni_v2 --patch_size 256 --mag 20`` diff --git a/docs/faq.rst b/docs/faq.rst index 5d1c9aa7..1deea930 100644 --- a/docs/faq.rst +++ b/docs/faq.rst @@ -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", @@ -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}") \ No newline at end of file + print(f"Failed to download weights for {model}: {e}") diff --git a/docs/index.rst b/docs/index.rst index af1a0105..f6469b46 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -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. diff --git a/tests/test_digepath_encoder.py b/tests/test_digepath_encoder.py new file mode 100644 index 00000000..76d2d49d --- /dev/null +++ b/tests/test_digepath_encoder.py @@ -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() diff --git a/tests/test_patch_encoders.py b/tests/test_patch_encoders.py index 4067c544..764ed2e5 100644 --- a/tests/test_patch_encoders.py +++ b/tests/test_patch_encoders.py @@ -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') @@ -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) @@ -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() \ No newline at end of file + unittest.main() diff --git a/trident/patch_encoder_models/__init__.py b/trident/patch_encoder_models/__init__.py index 58577be2..3141f32d 100644 --- a/trident/patch_encoder_models/__init__.py +++ b/trident/patch_encoder_models/__init__.py @@ -10,6 +10,7 @@ ResNet50InferenceEncoder, UNIInferenceEncoder, UNIv2InferenceEncoder, + DigepathInferenceEncoder, GigaPathInferenceEncoder, GigaPathFlashInferenceEncoder, VirchowInferenceEncoder, @@ -51,6 +52,7 @@ "ResNet50InferenceEncoder", "UNIInferenceEncoder", "UNIv2InferenceEncoder", + "DigepathInferenceEncoder", "GigaPathInferenceEncoder", "GigaPathFlashInferenceEncoder", "VirchowInferenceEncoder", diff --git a/trident/patch_encoder_models/load.py b/trident/patch_encoder_models/load.py index 96f42ff9..9571d8b6 100644 --- a/trident/patch_encoder_models/load.py +++ b/trident/patch_encoder_models/load.py @@ -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", @@ -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" @@ -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): @@ -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, diff --git a/trident/patch_encoder_models/local_ckpts.json b/trident/patch_encoder_models/local_ckpts.json index d0046330..fc9f5b14 100644 --- a/trident/patch_encoder_models/local_ckpts.json +++ b/trident/patch_encoder_models/local_ckpts.json @@ -2,6 +2,7 @@ "conch_v1": "", "uni_v1": "", "uni_v2": "", + "digepath": "", "ctranspath": "", "phikon": "", "resnet50": "", @@ -31,4 +32,4 @@ "gemma4-e4b": "", "gemma4-26b": "", "custom_encoder": "" -} \ No newline at end of file +}