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
Move preprocessing outside XMag model
Browse files- README.md +12 -3
- config.json +1 -0
- modeling_xmag.py +0 -7
- upload_to_hub.py +5 -2
README.md
CHANGED
|
@@ -24,12 +24,21 @@ XMag is a pathology image encoder distilled from a high-magnification foundation
|
|
| 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 |
-
|
|
|
|
| 33 |
|
| 34 |
with torch.no_grad():
|
| 35 |
outputs = model(pixel_values)
|
|
@@ -38,8 +47,8 @@ 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)`
|
| 42 |
-
The model
|
| 43 |
|
| 44 |
## Model Details
|
| 45 |
|
|
|
|
| 24 |
|
| 25 |
```python
|
| 26 |
import torch
|
| 27 |
+
from PIL import Image
|
| 28 |
+
from torchvision import transforms
|
| 29 |
from transformers import AutoModel
|
| 30 |
|
| 31 |
+
eval_transform = transforms.Compose([
|
| 32 |
+
transforms.Resize((224, 224)),
|
| 33 |
+
transforms.ToTensor(),
|
| 34 |
+
transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
|
| 35 |
+
])
|
| 36 |
+
|
| 37 |
model = AutoModel.from_pretrained("AI4PATH/XMAG", trust_remote_code=True)
|
| 38 |
model.eval()
|
| 39 |
|
| 40 |
+
image = Image.open("patch.png").convert("RGB")
|
| 41 |
+
pixel_values = eval_transform(image).unsqueeze(0)
|
| 42 |
|
| 43 |
with torch.no_grad():
|
| 44 |
outputs = model(pixel_values)
|
|
|
|
| 47 |
patch_embeddings = outputs["patch_embeddings"] # (1, 256, 768)
|
| 48 |
```
|
| 49 |
|
| 50 |
+
`pixel_values` should be normalized RGB tensors with shape `(B, 3, 224, 224)`.
|
| 51 |
+
The model does not apply preprocessing internally. Resize, `ToTensor()`, and ImageNet mean/std normalization should be done before calling the model.
|
| 52 |
|
| 53 |
## Model Details
|
| 54 |
|
config.json
CHANGED
|
@@ -20,6 +20,7 @@
|
|
| 20 |
0.224,
|
| 21 |
0.225
|
| 22 |
],
|
|
|
|
| 23 |
"torch_dtype": "float32",
|
| 24 |
"transformers_version": "4.50.3"
|
| 25 |
}
|
|
|
|
| 20 |
0.224,
|
| 21 |
0.225
|
| 22 |
],
|
| 23 |
+
"expects_normalized_input": true,
|
| 24 |
"torch_dtype": "float32",
|
| 25 |
"transformers_version": "4.50.3"
|
| 26 |
}
|
modeling_xmag.py
CHANGED
|
@@ -1,5 +1,4 @@
|
|
| 1 |
import torch
|
| 2 |
-
import torch.nn as nn
|
| 3 |
from transformers import PreTrainedModel
|
| 4 |
|
| 5 |
from .configuration_xmag import XMagConfig
|
|
@@ -13,11 +12,6 @@ class XMagModel(PreTrainedModel):
|
|
| 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).")
|
|
@@ -28,7 +22,6 @@ class XMagModel(PreTrainedModel):
|
|
| 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 {
|
|
|
|
| 1 |
import torch
|
|
|
|
| 2 |
from transformers import PreTrainedModel
|
| 3 |
|
| 4 |
from .configuration_xmag import XMagConfig
|
|
|
|
| 12 |
super().__init__(config)
|
| 13 |
self.model = torch.hub.load("facebookresearch/dinov2", config.backbone_name)
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
def forward(self, pixel_values):
|
| 16 |
if pixel_values.ndim != 4:
|
| 17 |
raise ValueError("pixel_values must have shape (B, 3, H, W).")
|
|
|
|
| 22 |
if height != self.config.image_size or width != self.config.image_size:
|
| 23 |
raise ValueError(f"pixel_values must be {self.config.image_size}x{self.config.image_size}.")
|
| 24 |
|
|
|
|
| 25 |
outputs = self.model.forward_features(pixel_values)
|
| 26 |
|
| 27 |
return {
|
upload_to_hub.py
CHANGED
|
@@ -11,10 +11,13 @@ def main():
|
|
| 11 |
parser.add_argument("--commit-message", default="Add XMag AutoModel release")
|
| 12 |
args = parser.parse_args()
|
| 13 |
|
| 14 |
-
|
|
|
|
| 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,
|
|
|
|
| 11 |
parser.add_argument("--commit-message", default="Add XMag AutoModel release")
|
| 12 |
args = parser.parse_args()
|
| 13 |
|
| 14 |
+
token = os.environ.get("HF_TOKEN")
|
| 15 |
+
if token is None:
|
| 16 |
print("warning: HF_TOKEN is not set. Falling back to cached Hugging Face credentials.")
|
| 17 |
+
login()
|
| 18 |
+
else:
|
| 19 |
+
login(token=token)
|
| 20 |
|
|
|
|
| 21 |
result = upload_folder(
|
| 22 |
folder_path=args.folder,
|
| 23 |
repo_id=args.repo_id,
|