Image Feature Extraction
Transformers
PyTorch
xmag
feature-extraction
pathology
histopathology
foundation-model
distillation
dinov2
custom_code
Instructions to use AI4PATH/XMAG with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use AI4PATH/XMAG with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-feature-extraction", model="AI4PATH/XMAG", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("AI4PATH/XMAG", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Add XMag AutoModel release
Browse files- README.md +61 -1
- config.json +25 -0
- configuration_xmag.py +21 -0
- modeling_xmag.py +37 -0
- pytorch_model.bin +3 -0
- requirements.txt +4 -0
- upload_to_hub.py +28 -0
README.md
CHANGED
|
@@ -1,3 +1,63 @@
|
|
| 1 |
---
|
| 2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
library_name: transformers
|
| 3 |
+
pipeline_tag: image-feature-extraction
|
| 4 |
+
tags:
|
| 5 |
+
- pathology
|
| 6 |
+
- histopathology
|
| 7 |
+
- foundation-model
|
| 8 |
+
- distillation
|
| 9 |
+
- dinov2
|
| 10 |
+
- xmag
|
| 11 |
---
|
| 12 |
+
|
| 13 |
+
# XMag
|
| 14 |
+
|
| 15 |
+
XMag is a pathology image encoder distilled from a high-magnification foundation model to a low-magnification student model.
|
| 16 |
+
|
| 17 |
+
- Teacher: frozen UNIv2
|
| 18 |
+
- Student: DINOv2 ViT-B/14
|
| 19 |
+
- Input: RGB pathology patch, `224 x 224`
|
| 20 |
+
- Output: CLS embedding and patch embeddings
|
| 21 |
+
- Training objective: global and local cosine feature distillation from high-magnification teacher features
|
| 22 |
+
|
| 23 |
+
## Usage
|
| 24 |
+
|
| 25 |
+
```python
|
| 26 |
+
import torch
|
| 27 |
+
from transformers import AutoModel
|
| 28 |
+
|
| 29 |
+
model = AutoModel.from_pretrained("AI4PATH/XMAG", trust_remote_code=True)
|
| 30 |
+
model.eval()
|
| 31 |
+
|
| 32 |
+
pixel_values = torch.randn(1, 3, 224, 224)
|
| 33 |
+
|
| 34 |
+
with torch.no_grad():
|
| 35 |
+
outputs = model(pixel_values)
|
| 36 |
+
|
| 37 |
+
cls_embedding = outputs["cls_embedding"] # (1, 768)
|
| 38 |
+
patch_embeddings = outputs["patch_embeddings"] # (1, 256, 768)
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
`pixel_values` should be RGB tensors with shape `(B, 3, 224, 224)`, typically after `torchvision.transforms.ToTensor()`.
|
| 42 |
+
The model applies ImageNet mean/std normalization internally.
|
| 43 |
+
|
| 44 |
+
## Model Details
|
| 45 |
+
|
| 46 |
+
The student sees a low-magnification `224 x 224` view of the tissue region. During training, the frozen UNIv2 teacher sees the corresponding high-magnification `896 x 896` region split into `4 x 4` subpatches. The student is trained to match both:
|
| 47 |
+
|
| 48 |
+
- A global teacher representation, computed by averaging the 16 teacher local features.
|
| 49 |
+
- Local teacher representations, aligned to pooled student patch-token blocks.
|
| 50 |
+
|
| 51 |
+
This release contains the student EMA backbone weights only. Projection heads used during distillation are not included.
|
| 52 |
+
|
| 53 |
+
## Requirements
|
| 54 |
+
|
| 55 |
+
```bash
|
| 56 |
+
pip install torch torchvision transformers huggingface_hub
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
The model code uses `torch.hub` to instantiate the DINOv2 ViT-B/14 backbone. The first load may need internet access to fetch the DINOv2 hub code, unless it is already cached.
|
| 60 |
+
|
| 61 |
+
## Citation
|
| 62 |
+
|
| 63 |
+
If you use this model, please cite the related XMag project and the original teacher/student foundation models where appropriate.
|
config.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_type": "xmag",
|
| 3 |
+
"architectures": [
|
| 4 |
+
"XMagModel"
|
| 5 |
+
],
|
| 6 |
+
"auto_map": {
|
| 7 |
+
"AutoConfig": "configuration_xmag.XMagConfig",
|
| 8 |
+
"AutoModel": "modeling_xmag.XMagModel"
|
| 9 |
+
},
|
| 10 |
+
"backbone_name": "dinov2_vitb14",
|
| 11 |
+
"embed_dim": 768,
|
| 12 |
+
"image_size": 224,
|
| 13 |
+
"image_mean": [
|
| 14 |
+
0.485,
|
| 15 |
+
0.456,
|
| 16 |
+
0.406
|
| 17 |
+
],
|
| 18 |
+
"image_std": [
|
| 19 |
+
0.229,
|
| 20 |
+
0.224,
|
| 21 |
+
0.225
|
| 22 |
+
],
|
| 23 |
+
"torch_dtype": "float32",
|
| 24 |
+
"transformers_version": "4.50.3"
|
| 25 |
+
}
|
configuration_xmag.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class XMagConfig(PretrainedConfig):
|
| 5 |
+
model_type = "xmag"
|
| 6 |
+
|
| 7 |
+
def __init__(
|
| 8 |
+
self,
|
| 9 |
+
backbone_name="dinov2_vitb14",
|
| 10 |
+
embed_dim=768,
|
| 11 |
+
image_size=224,
|
| 12 |
+
image_mean=(0.485, 0.456, 0.406),
|
| 13 |
+
image_std=(0.229, 0.224, 0.225),
|
| 14 |
+
**kwargs,
|
| 15 |
+
):
|
| 16 |
+
super().__init__(**kwargs)
|
| 17 |
+
self.backbone_name = backbone_name
|
| 18 |
+
self.embed_dim = embed_dim
|
| 19 |
+
self.image_size = image_size
|
| 20 |
+
self.image_mean = list(image_mean)
|
| 21 |
+
self.image_std = list(image_std)
|
modeling_xmag.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from transformers import PreTrainedModel
|
| 4 |
+
|
| 5 |
+
from .configuration_xmag import XMagConfig
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class XMagModel(PreTrainedModel):
|
| 9 |
+
config_class = XMagConfig
|
| 10 |
+
base_model_prefix = "model"
|
| 11 |
+
|
| 12 |
+
def __init__(self, config):
|
| 13 |
+
super().__init__(config)
|
| 14 |
+
self.model = torch.hub.load("facebookresearch/dinov2", config.backbone_name)
|
| 15 |
+
|
| 16 |
+
mean = torch.tensor(config.image_mean).view(1, 3, 1, 1)
|
| 17 |
+
std = torch.tensor(config.image_std).view(1, 3, 1, 1)
|
| 18 |
+
self.register_buffer("image_mean", mean, persistent=False)
|
| 19 |
+
self.register_buffer("image_std", std, persistent=False)
|
| 20 |
+
|
| 21 |
+
def forward(self, pixel_values):
|
| 22 |
+
if pixel_values.ndim != 4:
|
| 23 |
+
raise ValueError("pixel_values must have shape (B, 3, H, W).")
|
| 24 |
+
|
| 25 |
+
_, channels, height, width = pixel_values.shape
|
| 26 |
+
if channels != 3:
|
| 27 |
+
raise ValueError("pixel_values must have 3 RGB channels.")
|
| 28 |
+
if height != self.config.image_size or width != self.config.image_size:
|
| 29 |
+
raise ValueError(f"pixel_values must be {self.config.image_size}x{self.config.image_size}.")
|
| 30 |
+
|
| 31 |
+
pixel_values = (pixel_values - self.image_mean) / self.image_std
|
| 32 |
+
outputs = self.model.forward_features(pixel_values)
|
| 33 |
+
|
| 34 |
+
return {
|
| 35 |
+
"cls_embedding": outputs["x_norm_clstoken"],
|
| 36 |
+
"patch_embeddings": outputs["x_norm_patchtokens"],
|
| 37 |
+
}
|
pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:83aad56ce30deaf287b40e484269675df585885ebb17af1e58fa986426c3e3c4
|
| 3 |
+
size 346376070
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
torchvision
|
| 3 |
+
transformers
|
| 4 |
+
huggingface_hub
|
upload_to_hub.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
from huggingface_hub import login, upload_folder
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def main():
|
| 8 |
+
parser = argparse.ArgumentParser(description="Upload the XMag Hugging Face release folder.")
|
| 9 |
+
parser.add_argument("--repo-id", default="AI4PATH/XMAG", help="Target Hugging Face model repo.")
|
| 10 |
+
parser.add_argument("--folder", default=".", help="Release folder to upload.")
|
| 11 |
+
parser.add_argument("--commit-message", default="Add XMag AutoModel release")
|
| 12 |
+
args = parser.parse_args()
|
| 13 |
+
|
| 14 |
+
if os.environ.get("HF_TOKEN") is None:
|
| 15 |
+
print("warning: HF_TOKEN is not set. Falling back to cached Hugging Face credentials.")
|
| 16 |
+
|
| 17 |
+
login()
|
| 18 |
+
result = upload_folder(
|
| 19 |
+
folder_path=args.folder,
|
| 20 |
+
repo_id=args.repo_id,
|
| 21 |
+
repo_type="model",
|
| 22 |
+
commit_message=args.commit_message,
|
| 23 |
+
)
|
| 24 |
+
print(result)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if __name__ == "__main__":
|
| 28 |
+
main()
|