micro_sam.models.vfm
Vision Foundation Model (DINO, UNI, SAM3) encoders for the classification tools.
The classification tools operate directly on dense image-encoder features, so they can use backbones
beyond SAM. This module produces embeddings in the same ImageEmbeddings format that
compute_pixel_features and compute_object_features consume.
Four loading backends are supported:
torch_hub: DINOv2 (fetches model code + weights at runtime, no auth).hf: DINOv3 via thetransformerslibrary (gated, user provides HuggingFace access).timm: the MahmoodLab histopathology models UNI / UNI2-h viatimm(gated, user provides access).sam3: the SAM3 image encoder (the ViT trunk of the SAM3 image model) via thesam3package.
The gated models (DINOv3, UNI, UNI2-h) are never hosted or distributed by us: each user provides their
own HuggingFace access by accepting the license on the model page and authenticating in the terminal
(via huggingface-cli login or the HF_TOKEN environment variable), which the loading library picks
up automatically.
Supports 2D and 3D images, with or without tiling. Each tile / slice is encoded independently and the
embeddings are stored in the same zarr layout that SAM uses, so the classification feature computation
(compute_pixel_features / compute_object_features) consumes them unchanged.
1"""Vision Foundation Model (DINO, UNI, SAM3) encoders for the classification tools. 2 3The classification tools operate directly on dense image-encoder features, so they can use backbones 4beyond SAM. This module produces embeddings in the same `ImageEmbeddings` format that 5`compute_pixel_features` and `compute_object_features` consume. 6 7Four loading backends are supported: 8- `torch_hub`: DINOv2 (fetches model code + weights at runtime, no auth). 9- `hf`: DINOv3 via the `transformers` library (gated, user provides HuggingFace access). 10- `timm`: the MahmoodLab histopathology models UNI / UNI2-h via `timm` (gated, user provides access). 11- `sam3`: the SAM3 image encoder (the ViT trunk of the SAM3 image model) via the `sam3` package. 12 13The gated models (DINOv3, UNI, UNI2-h) are never hosted or distributed by us: each user provides their 14own HuggingFace access by accepting the license on the model page and authenticating in the terminal 15(via `huggingface-cli login` or the `HF_TOKEN` environment variable), which the loading library picks 16up automatically. 17 18Supports 2D and 3D images, with or without tiling. Each tile / slice is encoded independently and the 19embeddings are stored in the same zarr layout that SAM uses, so the classification feature computation 20(`compute_pixel_features` / `compute_object_features`) consumes them unchanged. 21""" 22 23import os 24import sys 25import types 26import importlib.util 27from typing import Dict, Optional, Tuple, Union 28 29import numpy as np 30 31import torch 32import torch.nn.functional as F 33 34from bioimage_cpp.utils import Blocking 35 36from .. import util 37 38# Registry of supported Vision Foundation Model encoders, keyed by the micro-sam `model_type`. 39# 'backend' selects how the model is loaded: 'torch_hub' (DINOv2, auto-download) builds 'repo'/'entrypoint' 40# via torch.hub; 'hf' (DINOv3, gated) loads the HuggingFace 'repo' via transformers.AutoModel; 'timm' 41# (UNI/UNI2-h, gated) loads the HuggingFace 'repo' via timm.create_model; 'sam3' loads the SAM3 image 42# encoder via the sam3 package. 'cache_folder' is the model's folder in the micro-sam model cache. A 43# 'mean'/'std' entry overrides the default ImageNet normalization, and an 'img_size' entry overrides the 44# default longest-side input size (used for SAM3's native 1008 resolution). 45VFM_MODELS: Dict[str, Dict] = { 46 # DINOv2 (patch size 14); weights auto-download via torch.hub, no authentication. 47 "vit_s_dinov2": {"backend": "torch_hub", "cache_folder": "dino/v2", "repo": "facebookresearch/dinov2", "entrypoint": "dinov2_vits14", "patch_size": 14, "embed_dim": 384}, # noqa 48 "vit_b_dinov2": {"backend": "torch_hub", "cache_folder": "dino/v2", "repo": "facebookresearch/dinov2", "entrypoint": "dinov2_vitb14", "patch_size": 14, "embed_dim": 768}, # noqa 49 "vit_l_dinov2": {"backend": "torch_hub", "cache_folder": "dino/v2", "repo": "facebookresearch/dinov2", "entrypoint": "dinov2_vitl14", "patch_size": 14, "embed_dim": 1024}, # noqa 50 "vit_g_dinov2": {"backend": "torch_hub", "cache_folder": "dino/v2", "repo": "facebookresearch/dinov2", "entrypoint": "dinov2_vitg14", "patch_size": 14, "embed_dim": 1536}, # noqa 51 # DINOv3 (patch size 16); loaded from HuggingFace via transformers. Gated: user provides HF access. 52 "vit_s_dinov3": {"backend": "hf", "cache_folder": "dino/v3", "repo": "facebook/dinov3-vits16-pretrain-lvd1689m", "patch_size": 16, "embed_dim": 384}, # noqa 53 "vit_b_dinov3": {"backend": "hf", "cache_folder": "dino/v3", "repo": "facebook/dinov3-vitb16-pretrain-lvd1689m", "patch_size": 16, "embed_dim": 768}, # noqa 54 "vit_l_dinov3": {"backend": "hf", "cache_folder": "dino/v3", "repo": "facebook/dinov3-vitl16-pretrain-lvd1689m", "patch_size": 16, "embed_dim": 1024}, # noqa 55 # UNI / UNI2-h (MahmoodLab histopathology); loaded from HuggingFace via timm. Gated: user provides HF access. 56 "vit_uni": {"backend": "timm", "cache_folder": "uni", "repo": "hf-hub:MahmoodLab/uni", "patch_size": 16, "embed_dim": 1024, "timm_variant": "uni"}, # noqa 57 "vit_univ2": {"backend": "timm", "cache_folder": "uni", "repo": "hf-hub:MahmoodLab/UNI2-h", "patch_size": 14, "embed_dim": 1536, "timm_variant": "uni2_h"}, # noqa 58 # SAM3 image encoder (Perception Encoder ViT trunk, patch size 14); the checkpoint auto-downloads from 59 # HuggingFace (facebook/sam3). Normalized to mean/std 0.5 at its native 1008 resolution. 60 "vit_sam3": {"backend": "sam3", "cache_folder": "sam3", "patch_size": 14, "embed_dim": 1024, "img_size": 1008, "mean": (0.5, 0.5, 0.5), "std": (0.5, 0.5, 0.5)}, # noqa 61} 62 63# Map each model to a human-readable size label for the GUI dropdowns. 64VFM_SIZE_LABELS = { 65 "vit_s_dinov2": "small", "vit_b_dinov2": "base", "vit_l_dinov2": "large", "vit_g_dinov2": "giant", 66 "vit_s_dinov3": "small", "vit_b_dinov3": "base", "vit_l_dinov3": "large", 67 "vit_uni": "large", "vit_univ2": "huge", # UNI is ViT-L, UNI2-h is ViT-H. 68 "vit_sam3": "large", # SAM3 uses a single ViT-L-scale Perception Encoder. 69} 70 71# ImageNet statistics the web-pretrained VFM models expect, applied after mapping the image to [0, 1]. 72# A model can override these via its 'mean'/'std' registry entry (e.g. SAM3 uses 0.5). 73VFM_MEAN = (0.485, 0.456, 0.406) 74VFM_STD = (0.229, 0.224, 0.225) 75 76# Default longest-side input size. The tool snaps it down to a multiple of the patch size per model. 77DEFAULT_VFM_IMG_SIZE = 1024 78 79 80def is_vfm_model(model_type: str) -> bool: 81 """Whether a model_type string refers to a registered VFM encoder (DINO / UNI).""" 82 return isinstance(model_type, str) and model_type in VFM_MODELS 83 84 85def get_vfm_model_names() -> Tuple[str, ...]: 86 """The model_type strings of all supported VFM encoders.""" 87 return tuple(VFM_MODELS.keys()) 88 89 90class VFMEncoder(torch.nn.Module): 91 """Wraps a Vision Foundation Model and produces dense (C, H, W) features for the classification tools. 92 93 Works across the RGB backends: torch.hub (DINOv2), transformers (DINOv3) and timm (UNI / UNI2-h). 94 The image is mapped to RGB (via `util._to_image`, matching what SAM sees), resized so its longest 95 side equals `img_size` and padded to a square multiple of the patch size, then encoded. As with the 96 SAM1 image encoder, the square feature map has its content in the top-left sub-rectangle, which the 97 classification feature computation crops back to the image aspect ratio. All backends return the 98 identical (C, h, w) feature contract, so downstream consumption is backend-agnostic. 99 100 Args: 101 model: The loaded model (a torch.hub, transformers or timm module). 102 spec: The `VFM_MODELS` entry for this model. 103 img_size: The longest-side input size, snapped down to a multiple of the patch size. 104 device: The device to run the encoder on. 105 """ 106 107 def __init__(self, model, spec: Dict, img_size: int, device): 108 super().__init__() 109 self.model = model.to(device).eval() 110 self.device = device 111 self.patch_size = spec["patch_size"] 112 self.embed_dim = spec["embed_dim"] 113 self.backend = spec["backend"] 114 # Normalization stats. ImageNet by default, overridable per model (SAM3 uses 0.5). 115 self.mean = spec.get("mean", VFM_MEAN) 116 self.std = spec.get("std", VFM_STD) 117 # The encoder needs a square input whose side is a multiple of the patch size. 118 self.img_size = (img_size // self.patch_size) * self.patch_size 119 # Set by 'get_vfm_model' so downstream code can read the model identity like a SAM predictor. 120 self.model_type = None 121 self.model_name = None 122 123 @staticmethod 124 def _resize_longest_side(height: int, width: int, long_side: int) -> Tuple[int, int]: 125 scale = long_side / max(height, width) 126 return int(round(height * scale)), int(round(width * scale)) 127 128 def _to_unit_rgb(self, image: np.ndarray) -> torch.Tensor: 129 """Map an image to a (1, 3, H, W) tensor in [0, 1], preserving colour for true RGB. 130 131 A genuine 8-bit RGB image (e.g. H&E) is scaled straight by 1/255 so the stain colour is kept, 132 matching the standard DINO / UNI preprocessing. Grayscale, 2-channel or non-8-bit inputs go 133 through SAM's per-channel min-max mapping (`util._to_image`), which normalizes arbitrary intensity 134 ranges - and is colour-neutral for grayscale, since the replicated channels are scaled identically. 135 """ 136 image = np.asarray(image) 137 if image.ndim == 3 and image.shape[-1] == 3 and image.dtype == np.uint8: 138 rgb = image # true 8-bit RGB: keep the colour, just scale to [0, 1] 139 else: 140 rgb = util._to_image(image) # (H, W, 3) uint8, per-channel min-max normalized 141 tensor = torch.from_numpy(np.ascontiguousarray(rgb)).to(self.device).float().permute(2, 0, 1) 142 return tensor.unsqueeze(0) / 255.0 143 144 def _preprocess(self, image: np.ndarray) -> Tuple[torch.Tensor, Tuple[int, int]]: 145 x = self._to_unit_rgb(image) 146 mean = torch.tensor(self.mean, device=self.device).view(1, 3, 1, 1) 147 std = torch.tensor(self.std, device=self.device).view(1, 3, 1, 1) 148 149 new_h, new_w = self._resize_longest_side(x.shape[-2], x.shape[-1], self.img_size) 150 x = F.interpolate(x, (new_h, new_w), mode="bilinear", align_corners=False, antialias=True) 151 x = (x - mean) / std 152 # Pad bottom/right to a square of side 'img_size' (a multiple of the patch size). 153 x = F.pad(x, (0, self.img_size - new_w, 0, self.img_size - new_h)) 154 return x, (new_h, new_w) 155 156 @torch.no_grad() 157 def encode(self, image: np.ndarray) -> Tuple[np.ndarray, Tuple[int, int]]: 158 """Encode an image into a dense feature map. 159 160 Args: 161 image: The input image, (H, W) or (H, W, C). 162 163 Returns: 164 The feature map of shape (C, H/patch, W/patch). 165 The resized (pre-padding) input size, (h, w). 166 """ 167 x, input_size = self._preprocess(image) 168 param = next(self.model.parameters(), None) 169 if param is not None: 170 x = x.to(dtype=param.dtype) 171 172 h, w = self.img_size // self.patch_size, self.img_size // self.patch_size 173 if self.backend == "torch_hub": # DINOv2 exposes a dense-feature helper directly. 174 features = self.model.get_intermediate_layers(x, n=1, reshape=True)[0] # (1, C, h, w) 175 elif self.backend == "sam3": 176 # SAM3's fused MLP forces bf16. On CPU that bf16 is emulated (slow), so the op is patched to 177 # fp32 (see '_install_sam3_cpu_fp32_mlp') and we run in plain fp32 - no autocast. On CUDA/MPS 178 # bf16 is native, so we keep it and apply the matching bf16 autocast the model's own (CUDA-only) 179 # decorators expect. 'mps' is best-effort (bf16 autocast support is torch/hardware dependent). 180 device_type = torch.device(self.device).type 181 if device_type in ("cuda", "mps"): 182 with torch.autocast(device_type=device_type, dtype=torch.bfloat16): 183 features = self.model(x)[-1] # list of (1, C, h, w) feature maps 184 else: # cpu (and any other device): fp32. 185 features = self.model(x)[-1] 186 else: 187 # 'hf' (transformers DINOv3) and 'timm' (UNI/UNI2-h) both return a token sequence of the 188 # form [prefix tokens..., patch tokens]. The patch tokens are the trailing h*w entries, so 189 # slicing from the end is robust to the (model-dependent) number of cls/register tokens. 190 # Reshape to the (1, C, h, w) grid the torch.hub path returns, keeping the feature contract 191 # identical across all backends. 192 if self.backend == "hf": 193 tokens = self.model(pixel_values=x).last_hidden_state # (1, T, C) 194 else: # timm 195 tokens = self.model.forward_features(x) # (1, T, C) 196 features = tokens[:, -(h * w):, :].reshape(1, h, w, -1).permute(0, 3, 1, 2) 197 return features.float().squeeze(0).cpu().numpy().astype("float32"), input_size 198 199 200def get_vfm_model( 201 model_type: str, 202 device: Optional[Union[str, torch.device]] = None, 203 checkpoint_path: Optional[Union[str, os.PathLike]] = None, 204 img_size: int = DEFAULT_VFM_IMG_SIZE, 205) -> VFMEncoder: 206 """Load a DINO / UNI encoder for the classification tools. 207 208 Args: 209 model_type: One of the keys in `VFM_MODELS`, e.g. 'vit_b_dinov2', 'vit_b_dinov3' or 'vit_sam3'. 210 device: The device to load the model on. By default the best available device. 211 checkpoint_path: For DINOv3 (HuggingFace), an optional local model directory to load instead of 212 the gated HuggingFace repo. For SAM3, an optional local SAM3 checkpoint to load instead of 213 auto-downloading from HuggingFace. Ignored for DINOv2, whose weights download automatically. 214 img_size: The longest-side input size; snapped down to a multiple of the patch size. A model that 215 pins its native size (e.g. SAM3 at 1008) overrides this. 216 217 Returns: 218 The VFM encoder. 219 """ 220 if model_type not in VFM_MODELS: 221 raise ValueError( 222 f"Unknown VFM model '{model_type}'. Available models: {sorted(VFM_MODELS)}." 223 ) 224 spec = VFM_MODELS[model_type] 225 # A model can pin its native input size (e.g. SAM3 at 1008), which overrides the passed default. 226 img_size = spec.get("img_size", img_size) 227 device = util.get_device(device) 228 229 # xFormers' memory-efficient attention is CUDA-only. On CPU some backbones (e.g. the torch.hub DINOv2 230 # code) would try it and crash, so disable it there. The DINOv2-derived code reads this env var at 231 # import, so it must be set before the backbone is loaded. No-op if xFormers is not installed. 232 if str(device) == "cpu": 233 os.environ.setdefault("XFORMERS_DISABLED", "1") 234 235 if spec["backend"] == "torch_hub": # DINOv2: code + weights auto-download, no authentication. 236 model = _load_torch_hub_model(spec) 237 elif spec["backend"] == "hf": # DINOv3: HuggingFace via transformers, user's own HF access. 238 model = _load_hf_model(spec["repo"], spec["cache_folder"], checkpoint_path) 239 elif spec["backend"] == "sam3": # SAM3: the image-model ViT trunk via the sam3 package. 240 model = _load_sam3_model(checkpoint_path) 241 else: # 'timm': UNI / UNI2-h from HuggingFace via timm, user's own HF access. 242 model = _load_timm_model(spec) 243 244 encoder = VFMEncoder(model, spec, img_size=img_size, device=device) 245 encoder.model_type = model_type 246 encoder.model_name = model_type 247 return encoder 248 249 250def _load_torch_hub_model(spec: Dict): 251 """Load a DINOv2 model via torch.hub, with the code and the weights in the micro-sam model cache. 252 253 torch.hub only supports a global download directory, so the function sets it for the load and 254 restores it afterwards. 255 """ 256 hub_dir = torch.hub.get_dir() 257 torch.hub.set_dir(str(util.get_model_cache_directory(spec["cache_folder"]))) 258 try: 259 return torch.hub.load(spec["repo"], spec["entrypoint"]) 260 finally: 261 torch.hub.set_dir(hub_dir) 262 263 264def _download_sam3_checkpoint(): 265 """Download the SAM3 checkpoint from HuggingFace (facebook/sam3) to the micro-sam model cache. 266 267 The 'sam3' download helper always uses the default HuggingFace cache, so the function downloads the 268 checkpoint directly. The ViT trunk only needs the checkpoint, not the HuggingFace config. 269 """ 270 from huggingface_hub import hf_hub_download 271 cache_dir = util.get_model_cache_directory("sam3") 272 return hf_hub_download(repo_id="facebook/sam3", filename="sam3.pt", cache_dir=cache_dir) 273 274 275def _load_timm_model(spec: Dict): 276 """Load a UNI / UNI2-h model from HuggingFace via timm, using the user's own HF access. 277 278 timm resolves the HuggingFace token from the environment (`HF_TOKEN`) or the `huggingface-cli login` 279 cache, so the user manages their own access; we never handle their token. 280 """ 281 try: 282 import timm 283 except ImportError as e: 284 raise ImportError( 285 "Loading UNI / UNI2-h requires the 'timm' package. Install it with 'pip install timm'." 286 ) from e 287 288 # Shared kwargs; 'dynamic_img_size' lets the ViT accept our (square, patch-multiple) inputs. 289 kwargs = {"pretrained": True, "num_classes": 0, "dynamic_img_size": True, "init_values": 1e-5} 290 if spec.get("timm_variant") == "uni2_h": # UNI2-h needs its full custom ViT-H config (see model card). 291 kwargs.update({ 292 "img_size": 224, "patch_size": 14, "depth": 24, "num_heads": 24, "embed_dim": 1536, 293 "mlp_ratio": 2.66667 * 2, "no_embed_class": True, "reg_tokens": 8, 294 "mlp_layer": timm.layers.SwiGLUPacked, "act_layer": torch.nn.SiLU, 295 }) 296 297 try: 298 return timm.create_model(spec["repo"], cache_dir=util.get_model_cache_directory(spec["cache_folder"]), **kwargs) 299 except Exception as e: 300 repo = spec["repo"].split("hf-hub:")[-1] 301 raise RuntimeError( 302 f"Could not load '{spec['repo']}' via timm; see the chained error above for the exact " 303 f"reason. The UNI / UNI2-h weights are gated by MahmoodLab: request access at " 304 f"https://huggingface.co/{repo} (it requires an institutional-email HuggingFace account) " 305 "and authenticate in your terminal via 'huggingface-cli login' or the 'HF_TOKEN' " 306 "environment variable." 307 ) from e 308 309 310def _ensure_sam3_importable(): 311 """Make the 'sam3' package importable on a machine without 'triton'. 312 313 'sam3/__init__' eagerly imports the video-tracker and perf paths, which import 'triton' (a GPU-only 314 JIT) purely for kernels the image encoder never runs (Euclidean distance transform, NMS, ...). When 315 'triton' is absent (e.g. a CPU-only install) that import chain crashes before the image encoder can be 316 built. torch itself handles a missing 'triton' gracefully, so we first let torch finish its own triton 317 probing (while triton is genuinely absent) and then register a minimal 'triton' shim so those sam3 318 modules import; the shimmed kernels are never launched for image encoding. 319 """ 320 if importlib.util.find_spec("triton") is not None: 321 return # real triton present; nothing to do. 322 323 # Let torch/torchvision run their triton probe now, so torch caches 'no triton' and never later 324 # chokes on the shim's partial submodule tree (torch inductor does 'import triton.backends.compiler'). 325 try: 326 import torch._dynamo # noqa 327 except Exception: 328 pass 329 330 class _Stub(types.ModuleType): 331 # Any non-dunder attribute resolves to a universal no-op that works as a decorator ('@triton.jit'), 332 # a decorator factory ('@triton.autotune(...)') or an annotation value ('tl.constexpr'). Dunders 333 # keep normal module semantics so tools like 'inspect' see a well-formed module. 334 def __getattr__(self, name): 335 if name.startswith("__") and name.endswith("__"): 336 raise AttributeError(name) 337 338 def universal(*args, **kwargs): 339 if len(args) == 1 and callable(args[0]) and not kwargs: 340 return args[0] 341 return lambda fn: fn 342 return universal 343 344 triton = _Stub("triton") 345 triton.__file__ = "<triton-shim>" 346 triton.__path__ = [] # mark as a package so 'import triton.language' resolves. 347 language = _Stub("triton.language") 348 language.__file__ = "<triton-shim>" 349 triton.language = language 350 sys.modules["triton"] = triton 351 sys.modules["triton.language"] = language 352 353 354def _install_sam3_cpu_fp32_mlp(): 355 """Run SAM3's fused MLP op in fp32 on CPU. Its hardcoded bf16 is emulated (~4x slower) on CPUs without 356 AVX512-BF16. The replacement is device-aware: CPU inputs take an fp32 linear + activation (features 357 match the bf16 path to ~0.9997 cosine), while CUDA / other devices keep SAM3's native fused bf16 op. 358 """ 359 import sam3.model.vitdet as vitdet 360 if getattr(vitdet, "microsam_addmm_fp32_installed", False): 361 return 362 native_addmm_act = vitdet.addmm_act 363 364 def addmm_act(activation, linear, mat1): 365 if mat1.device.type != "cpu": # keep SAM3's native bf16 fused op off CPU (fast there). 366 return native_addmm_act(activation, linear, mat1) 367 y = F.linear(mat1, linear.weight, linear.bias) 368 if activation in (F.gelu, torch.nn.GELU): 369 return F.gelu(y) 370 if activation in (F.relu, torch.nn.ReLU): 371 return F.relu(y) 372 return native_addmm_act(activation, linear, mat1) # unknown activation: defer to SAM3. 373 374 vitdet.addmm_act = addmm_act 375 vitdet.microsam_addmm_fp32_installed = True 376 377 378def _extract_trunk_state_dict(ckpt: Dict) -> Dict: 379 """Pull the ViT-trunk weights out of a full SAM3 checkpoint (or pass through a trunk-only one).""" 380 prefix = "backbone.vision_backbone.trunk." 381 state_dict = {} 382 for k, v in ckpt.items(): 383 key = k[len("detector."):] if k.startswith("detector.") else k 384 if key.startswith(prefix): 385 state_dict[key[len(prefix):]] = v 386 return state_dict if state_dict else ckpt # fall back: assume the checkpoint is already trunk-only. 387 388 389def _load_sam3_model(checkpoint_path=None): 390 """Load the SAM3 image encoder: the Perception-Encoder ViT trunk of the SAM3 image model. 391 392 Only the vision-transformer trunk is built (via the SAM3 model builder) and its weights are loaded from 393 the SAM3 checkpoint, which auto-downloads from HuggingFace (facebook/sam3) when no `checkpoint_path` is 394 given. Building only the trunk keeps this CPU-safe: the full image model's neck precomputes position 395 encodings on a hardcoded CUDA device, whereas the trunk runs on CPU and GPU alike. That trunk produces 396 the dense patch features the classification tools consume. 397 """ 398 _ensure_sam3_importable() 399 try: 400 from sam3.model_builder import _create_vit_backbone 401 except ImportError as e: 402 raise ImportError( 403 "Loading the SAM3 encoder requires the 'sam3' package. Install segment anything 3 from " 404 "https://github.com/facebookresearch/sam3." 405 ) from e 406 407 _install_sam3_cpu_fp32_mlp() 408 trunk = _create_vit_backbone() 409 try: 410 source = str(checkpoint_path) if checkpoint_path else _download_sam3_checkpoint() 411 except Exception as e: 412 raise RuntimeError( 413 "Could not fetch the SAM3 checkpoint. See the chained error above for the exact reason. The " 414 "weights are gated on HuggingFace (facebook/sam3): accept the license there and authenticate " 415 "via 'huggingface-cli login' or the 'HF_TOKEN' environment variable." 416 ) from e 417 418 ckpt = torch.load(source, map_location="cpu", weights_only=True) 419 if "model" in ckpt and isinstance(ckpt["model"], dict): 420 ckpt = ckpt["model"] 421 missing, unexpected = trunk.load_state_dict(_extract_trunk_state_dict(ckpt), strict=False) 422 if missing: 423 raise RuntimeError(f"The SAM3 checkpoint '{source}' is missing {len(missing)} ViT-trunk weights.") 424 return trunk 425 426 427def _load_hf_model(repo: str, cache_folder: str, checkpoint_path=None): 428 """Load a gated DINOv3 model from HuggingFace via transformers, with the user's own HF access. 429 430 `transformers` resolves the HuggingFace token from the environment (`HF_TOKEN`) or the 431 `huggingface-cli login` cache, so the user manages their own access; we never handle their token. 432 """ 433 try: 434 from transformers import AutoModel 435 except ImportError as e: 436 raise ImportError( 437 "Loading DINOv3 requires the 'transformers' package (>=4.56). Install it with " 438 "'pip install transformers'." 439 ) from e 440 441 source = str(checkpoint_path) if checkpoint_path else repo 442 try: 443 return AutoModel.from_pretrained(source, cache_dir=util.get_model_cache_directory(cache_folder)) 444 except Exception as e: 445 # The chained error (e) carries the exact reason: license not requested, access still pending 446 # the repo authors' review, missing/invalid token, etc. We point the user at it rather than 447 # assuming a single cause. 448 raise RuntimeError( 449 f"Could not load the DINOv3 model '{source}' from HuggingFace; see the chained error above " 450 f"for the exact reason. The weights are gated by Meta: request access at " 451 f"https://huggingface.co/{repo} (approval by the repo authors can still be pending) and " 452 "authenticate in your terminal via 'huggingface-cli login' or the 'HF_TOKEN' environment " 453 "variable." 454 ) from e 455 456 457def _handle_pbar(verbose, pbar_init, pbar_update): 458 """Return (pbar_init, pbar_update, pbar_close): use the given callbacks, else a local tqdm bar.""" 459 if pbar_init is not None and pbar_update is not None: 460 return pbar_init, pbar_update, (lambda: None) 461 462 pbar = None 463 464 def init(total, description): 465 nonlocal pbar 466 pbar = util._progress_bar(total=total, desc=description, disable=not verbose) 467 468 def update(n): 469 if pbar is not None: 470 pbar.update(n) 471 472 def close(): 473 if pbar is not None: 474 pbar.close() 475 476 return init, update, close 477 478 479def _write_signature(f, encoder, input_, mode): 480 """Write the root-level embedding signature read by 'AnnotatorState.initialize_predictor'.""" 481 f.attrs["data_signature"] = util._compute_data_signature(input_) 482 f.attrs["model_type"] = encoder.model_type 483 f.attrs["model_name"] = encoder.model_type 484 f.attrs["patch_size"] = encoder.patch_size 485 f.attrs["embed_dim"] = encoder.embed_dim 486 f.attrs["micro_sam_version"] = util.__version__ 487 f.attrs["vfm_mode"] = mode 488 489 490def _load_cached_embeddings(f, encoder, input_): 491 """Return cached embeddings from an opened zarr group if they match the image and model. Return None otherwise.""" 492 if "features" not in f or f.attrs.get("vfm_mode") is None: 493 return None 494 matches = ( 495 f.attrs.get("data_signature") == util._compute_data_signature(input_) 496 and f.attrs.get("model_name") == encoder.model_type 497 ) 498 if not matches: 499 return None 500 if f.attrs["vfm_mode"] in ("2d", "3d"): # non-tiled: 'features' is an array, sizes in root attrs 501 return { 502 "features": f["features"][:], 503 "input_size": list(f.attrs["input_size"]), 504 "original_size": list(f.attrs["original_size"]), 505 } 506 return {"features": f["features"], "input_size": None, "original_size": None} # tiled: group of tiles 507 508 509def _compute_vfm_2d(encoder, input_, f, save_path, pbar_init, pbar_update): 510 from ..util import _create_dataset_with_data 511 pbar_init(1, "Compute Image Embeddings 2D") 512 features, input_size = encoder.encode(input_) 513 features = features[None] # (1, C, h, w), matching the SAM1 2D layout 514 pbar_update(1) 515 516 image_embeddings = {"features": features, "input_size": list(input_size), "original_size": list(input_.shape[:2])} 517 if save_path is not None: 518 _create_dataset_with_data(f, "features", data=features) 519 f.attrs["input_size"] = list(input_size) 520 f.attrs["original_size"] = list(input_.shape[:2]) 521 _write_signature(f, encoder, input_, "2d") 522 return image_embeddings 523 524 525def _compute_vfm_3d(encoder, input_, f, save_path, pbar_init, pbar_update): 526 from ..util import _create_dataset_with_data 527 n_slices = input_.shape[0] 528 pbar_init(n_slices, "Compute Image Embeddings 3D") 529 planes, input_size = [], None 530 for z in range(n_slices): 531 feats, input_size = encoder.encode(input_[z]) 532 planes.append(feats[None]) # (1, C, h, w) 533 pbar_update(1) 534 features = np.stack(planes) # (Z, 1, C, h, w) 535 536 original_size = list(input_[0].shape[:2]) 537 image_embeddings = {"features": features, "input_size": list(input_size), "original_size": original_size} 538 if save_path is not None: 539 _create_dataset_with_data(f, "features", data=features, chunks=(1, 1) + features.shape[2:]) 540 f.attrs["input_size"] = list(input_size) 541 f.attrs["original_size"] = original_size 542 _write_signature(f, encoder, input_, "3d") 543 return image_embeddings 544 545 546def _compute_vfm_tiled(encoder, input_, tile_shape, halo, f, pbar_init, pbar_update, is_3d): 547 from ..util import _create_dataset_with_data 548 spatial_shape = input_.shape[1:] if is_3d else input_.shape[:2] 549 tiling = Blocking([0, 0], list(spatial_shape), list(tile_shape)) 550 n_tiles = tiling.number_of_blocks 551 n_slices = input_.shape[0] if is_3d else 1 552 553 features = f.require_group("features") 554 features.attrs["shape"] = list(spatial_shape) 555 features.attrs["tile_shape"] = list(tile_shape) 556 features.attrs["halo"] = list(halo) 557 558 pbar_init(n_tiles * n_slices, f"Compute Image Embeddings {'3D' if is_3d else '2D'} tiled") 559 datasets = {} 560 for z in range(n_slices): 561 for tile_id in range(n_tiles): 562 block = tiling.get_block_with_halo(tile_id, list(halo)) 563 bb = tuple(slice(beg, end) for beg, end in zip(block.outer_block.begin, block.outer_block.end)) 564 tile_input = input_[(z,) + bb] if is_3d else input_[bb] 565 feats, input_size = encoder.encode(tile_input) # (C, h, w) 566 567 ds_name = str(tile_id) 568 if is_3d: 569 if ds_name not in datasets: 570 shape = (n_slices, 1) + feats.shape 571 ds = _create_dataset_with_data( 572 features, ds_name, data=np.zeros(shape, dtype="float32"), chunks=(1, 1) + feats.shape 573 ) 574 ds.attrs["original_size"] = list(tile_input.shape[:2]) 575 ds.attrs["input_size"] = list(input_size) 576 datasets[ds_name] = ds 577 datasets[ds_name][z] = feats[None] 578 else: 579 ds = _create_dataset_with_data(features, ds_name, data=feats[None]) # (1, C, h, w) 580 ds.attrs["original_size"] = list(tile_input.shape[:2]) 581 ds.attrs["input_size"] = list(input_size) 582 pbar_update(1) 583 584 _write_signature(f, encoder, input_, "tiled-3d" if is_3d else "tiled-2d") 585 return {"features": features, "input_size": None, "original_size": None} 586 587 588def precompute_vfm_embeddings( 589 predictor: VFMEncoder, 590 input_: np.ndarray, 591 save_path: Optional[Union[str, os.PathLike]] = None, 592 ndim: Optional[int] = None, 593 tile_shape: Optional[Tuple[int, int]] = None, 594 halo: Optional[Tuple[int, int]] = None, 595 verbose: bool = True, 596 lazy_loading: bool = False, 597 pbar_init: Optional[callable] = None, 598 pbar_update: Optional[callable] = None, 599 **kwargs, 600) -> util.ImageEmbeddings: 601 """Compute VFM image embeddings in the `ImageEmbeddings` format used by the classification tools. 602 603 This mirrors the SAM embedding API (same signature and return contract) so that it can be used as a 604 drop-in for VFM (DINO / UNI) encoders. Supports 2D and 3D images, with or without tiling. 605 606 Args: 607 predictor: The VFM encoder (named 'predictor' to match the SAM precompute signature). 608 input_: The input data, 2D (H, W[, C]) or 3D (Z, H, W[, C]). 609 save_path: Optional path to a zarr container to cache the embeddings. 610 ndim: The dimensionality of the data. If not given, deduced from the input. 611 tile_shape: Shape of tiles for tiled embedding computation. By default no tiling. 612 halo: Overlap of the tiles for tiled embedding computation. By default no tiling. 613 verbose: Whether to be verbose. 614 lazy_loading: Unused; accepted for signature compatibility. 615 pbar_init: Callback to initialize an external progress bar (steps, description). 616 pbar_update: Callback to update an external progress bar. 617 618 Returns: 619 The image embeddings. 620 """ 621 ndim = input_.ndim if ndim is None else ndim 622 if ndim not in (2, 3): 623 raise ValueError(f"Invalid dimensionality {ndim}, expect 2 or 3 dimensional data.") 624 625 # Open or create the zarr container and return cached embeddings if they match. Otherwise truncate. 626 if save_path is None: 627 f = util._open_embeddings(None) 628 elif os.path.exists(save_path): 629 f = util._open_embeddings(save_path, mode="a") 630 cached = _load_cached_embeddings(f, predictor, input_) 631 if cached is not None: 632 return cached 633 f = util._open_embeddings(save_path, mode="w") 634 else: 635 f = util._open_embeddings(save_path, mode="a") 636 637 pbar_init, pbar_update, pbar_close = _handle_pbar(verbose, pbar_init, pbar_update) 638 is_3d = ndim == 3 639 if tile_shape is not None: 640 embeddings = _compute_vfm_tiled(predictor, input_, tile_shape, halo, f, pbar_init, pbar_update, is_3d) 641 elif is_3d: 642 embeddings = _compute_vfm_3d(predictor, input_, f, save_path, pbar_init, pbar_update) 643 else: 644 embeddings = _compute_vfm_2d(predictor, input_, f, save_path, pbar_init, pbar_update) 645 pbar_close() 646 return embeddings
81def is_vfm_model(model_type: str) -> bool: 82 """Whether a model_type string refers to a registered VFM encoder (DINO / UNI).""" 83 return isinstance(model_type, str) and model_type in VFM_MODELS
Whether a model_type string refers to a registered VFM encoder (DINO / UNI).
86def get_vfm_model_names() -> Tuple[str, ...]: 87 """The model_type strings of all supported VFM encoders.""" 88 return tuple(VFM_MODELS.keys())
The model_type strings of all supported VFM encoders.
91class VFMEncoder(torch.nn.Module): 92 """Wraps a Vision Foundation Model and produces dense (C, H, W) features for the classification tools. 93 94 Works across the RGB backends: torch.hub (DINOv2), transformers (DINOv3) and timm (UNI / UNI2-h). 95 The image is mapped to RGB (via `util._to_image`, matching what SAM sees), resized so its longest 96 side equals `img_size` and padded to a square multiple of the patch size, then encoded. As with the 97 SAM1 image encoder, the square feature map has its content in the top-left sub-rectangle, which the 98 classification feature computation crops back to the image aspect ratio. All backends return the 99 identical (C, h, w) feature contract, so downstream consumption is backend-agnostic. 100 101 Args: 102 model: The loaded model (a torch.hub, transformers or timm module). 103 spec: The `VFM_MODELS` entry for this model. 104 img_size: The longest-side input size, snapped down to a multiple of the patch size. 105 device: The device to run the encoder on. 106 """ 107 108 def __init__(self, model, spec: Dict, img_size: int, device): 109 super().__init__() 110 self.model = model.to(device).eval() 111 self.device = device 112 self.patch_size = spec["patch_size"] 113 self.embed_dim = spec["embed_dim"] 114 self.backend = spec["backend"] 115 # Normalization stats. ImageNet by default, overridable per model (SAM3 uses 0.5). 116 self.mean = spec.get("mean", VFM_MEAN) 117 self.std = spec.get("std", VFM_STD) 118 # The encoder needs a square input whose side is a multiple of the patch size. 119 self.img_size = (img_size // self.patch_size) * self.patch_size 120 # Set by 'get_vfm_model' so downstream code can read the model identity like a SAM predictor. 121 self.model_type = None 122 self.model_name = None 123 124 @staticmethod 125 def _resize_longest_side(height: int, width: int, long_side: int) -> Tuple[int, int]: 126 scale = long_side / max(height, width) 127 return int(round(height * scale)), int(round(width * scale)) 128 129 def _to_unit_rgb(self, image: np.ndarray) -> torch.Tensor: 130 """Map an image to a (1, 3, H, W) tensor in [0, 1], preserving colour for true RGB. 131 132 A genuine 8-bit RGB image (e.g. H&E) is scaled straight by 1/255 so the stain colour is kept, 133 matching the standard DINO / UNI preprocessing. Grayscale, 2-channel or non-8-bit inputs go 134 through SAM's per-channel min-max mapping (`util._to_image`), which normalizes arbitrary intensity 135 ranges - and is colour-neutral for grayscale, since the replicated channels are scaled identically. 136 """ 137 image = np.asarray(image) 138 if image.ndim == 3 and image.shape[-1] == 3 and image.dtype == np.uint8: 139 rgb = image # true 8-bit RGB: keep the colour, just scale to [0, 1] 140 else: 141 rgb = util._to_image(image) # (H, W, 3) uint8, per-channel min-max normalized 142 tensor = torch.from_numpy(np.ascontiguousarray(rgb)).to(self.device).float().permute(2, 0, 1) 143 return tensor.unsqueeze(0) / 255.0 144 145 def _preprocess(self, image: np.ndarray) -> Tuple[torch.Tensor, Tuple[int, int]]: 146 x = self._to_unit_rgb(image) 147 mean = torch.tensor(self.mean, device=self.device).view(1, 3, 1, 1) 148 std = torch.tensor(self.std, device=self.device).view(1, 3, 1, 1) 149 150 new_h, new_w = self._resize_longest_side(x.shape[-2], x.shape[-1], self.img_size) 151 x = F.interpolate(x, (new_h, new_w), mode="bilinear", align_corners=False, antialias=True) 152 x = (x - mean) / std 153 # Pad bottom/right to a square of side 'img_size' (a multiple of the patch size). 154 x = F.pad(x, (0, self.img_size - new_w, 0, self.img_size - new_h)) 155 return x, (new_h, new_w) 156 157 @torch.no_grad() 158 def encode(self, image: np.ndarray) -> Tuple[np.ndarray, Tuple[int, int]]: 159 """Encode an image into a dense feature map. 160 161 Args: 162 image: The input image, (H, W) or (H, W, C). 163 164 Returns: 165 The feature map of shape (C, H/patch, W/patch). 166 The resized (pre-padding) input size, (h, w). 167 """ 168 x, input_size = self._preprocess(image) 169 param = next(self.model.parameters(), None) 170 if param is not None: 171 x = x.to(dtype=param.dtype) 172 173 h, w = self.img_size // self.patch_size, self.img_size // self.patch_size 174 if self.backend == "torch_hub": # DINOv2 exposes a dense-feature helper directly. 175 features = self.model.get_intermediate_layers(x, n=1, reshape=True)[0] # (1, C, h, w) 176 elif self.backend == "sam3": 177 # SAM3's fused MLP forces bf16. On CPU that bf16 is emulated (slow), so the op is patched to 178 # fp32 (see '_install_sam3_cpu_fp32_mlp') and we run in plain fp32 - no autocast. On CUDA/MPS 179 # bf16 is native, so we keep it and apply the matching bf16 autocast the model's own (CUDA-only) 180 # decorators expect. 'mps' is best-effort (bf16 autocast support is torch/hardware dependent). 181 device_type = torch.device(self.device).type 182 if device_type in ("cuda", "mps"): 183 with torch.autocast(device_type=device_type, dtype=torch.bfloat16): 184 features = self.model(x)[-1] # list of (1, C, h, w) feature maps 185 else: # cpu (and any other device): fp32. 186 features = self.model(x)[-1] 187 else: 188 # 'hf' (transformers DINOv3) and 'timm' (UNI/UNI2-h) both return a token sequence of the 189 # form [prefix tokens..., patch tokens]. The patch tokens are the trailing h*w entries, so 190 # slicing from the end is robust to the (model-dependent) number of cls/register tokens. 191 # Reshape to the (1, C, h, w) grid the torch.hub path returns, keeping the feature contract 192 # identical across all backends. 193 if self.backend == "hf": 194 tokens = self.model(pixel_values=x).last_hidden_state # (1, T, C) 195 else: # timm 196 tokens = self.model.forward_features(x) # (1, T, C) 197 features = tokens[:, -(h * w):, :].reshape(1, h, w, -1).permute(0, 3, 1, 2) 198 return features.float().squeeze(0).cpu().numpy().astype("float32"), input_size
Wraps a Vision Foundation Model and produces dense (C, H, W) features for the classification tools.
Works across the RGB backends: torch.hub (DINOv2), transformers (DINOv3) and timm (UNI / UNI2-h).
The image is mapped to RGB (via util._to_image, matching what SAM sees), resized so its longest
side equals img_size and padded to a square multiple of the patch size, then encoded. As with the
SAM1 image encoder, the square feature map has its content in the top-left sub-rectangle, which the
classification feature computation crops back to the image aspect ratio. All backends return the
identical (C, h, w) feature contract, so downstream consumption is backend-agnostic.
Arguments:
- model: The loaded model (a torch.hub, transformers or timm module).
- spec: The
VFM_MODELSentry for this model. - img_size: The longest-side input size, snapped down to a multiple of the patch size.
- device: The device to run the encoder on.
108 def __init__(self, model, spec: Dict, img_size: int, device): 109 super().__init__() 110 self.model = model.to(device).eval() 111 self.device = device 112 self.patch_size = spec["patch_size"] 113 self.embed_dim = spec["embed_dim"] 114 self.backend = spec["backend"] 115 # Normalization stats. ImageNet by default, overridable per model (SAM3 uses 0.5). 116 self.mean = spec.get("mean", VFM_MEAN) 117 self.std = spec.get("std", VFM_STD) 118 # The encoder needs a square input whose side is a multiple of the patch size. 119 self.img_size = (img_size // self.patch_size) * self.patch_size 120 # Set by 'get_vfm_model' so downstream code can read the model identity like a SAM predictor. 121 self.model_type = None 122 self.model_name = None
Initialize internal Module state, shared by both nn.Module and ScriptModule.
157 @torch.no_grad() 158 def encode(self, image: np.ndarray) -> Tuple[np.ndarray, Tuple[int, int]]: 159 """Encode an image into a dense feature map. 160 161 Args: 162 image: The input image, (H, W) or (H, W, C). 163 164 Returns: 165 The feature map of shape (C, H/patch, W/patch). 166 The resized (pre-padding) input size, (h, w). 167 """ 168 x, input_size = self._preprocess(image) 169 param = next(self.model.parameters(), None) 170 if param is not None: 171 x = x.to(dtype=param.dtype) 172 173 h, w = self.img_size // self.patch_size, self.img_size // self.patch_size 174 if self.backend == "torch_hub": # DINOv2 exposes a dense-feature helper directly. 175 features = self.model.get_intermediate_layers(x, n=1, reshape=True)[0] # (1, C, h, w) 176 elif self.backend == "sam3": 177 # SAM3's fused MLP forces bf16. On CPU that bf16 is emulated (slow), so the op is patched to 178 # fp32 (see '_install_sam3_cpu_fp32_mlp') and we run in plain fp32 - no autocast. On CUDA/MPS 179 # bf16 is native, so we keep it and apply the matching bf16 autocast the model's own (CUDA-only) 180 # decorators expect. 'mps' is best-effort (bf16 autocast support is torch/hardware dependent). 181 device_type = torch.device(self.device).type 182 if device_type in ("cuda", "mps"): 183 with torch.autocast(device_type=device_type, dtype=torch.bfloat16): 184 features = self.model(x)[-1] # list of (1, C, h, w) feature maps 185 else: # cpu (and any other device): fp32. 186 features = self.model(x)[-1] 187 else: 188 # 'hf' (transformers DINOv3) and 'timm' (UNI/UNI2-h) both return a token sequence of the 189 # form [prefix tokens..., patch tokens]. The patch tokens are the trailing h*w entries, so 190 # slicing from the end is robust to the (model-dependent) number of cls/register tokens. 191 # Reshape to the (1, C, h, w) grid the torch.hub path returns, keeping the feature contract 192 # identical across all backends. 193 if self.backend == "hf": 194 tokens = self.model(pixel_values=x).last_hidden_state # (1, T, C) 195 else: # timm 196 tokens = self.model.forward_features(x) # (1, T, C) 197 features = tokens[:, -(h * w):, :].reshape(1, h, w, -1).permute(0, 3, 1, 2) 198 return features.float().squeeze(0).cpu().numpy().astype("float32"), input_size
Encode an image into a dense feature map.
Arguments:
- image: The input image, (H, W) or (H, W, C).
Returns:
The feature map of shape (C, H/patch, W/patch). The resized (pre-padding) input size, (h, w).
201def get_vfm_model( 202 model_type: str, 203 device: Optional[Union[str, torch.device]] = None, 204 checkpoint_path: Optional[Union[str, os.PathLike]] = None, 205 img_size: int = DEFAULT_VFM_IMG_SIZE, 206) -> VFMEncoder: 207 """Load a DINO / UNI encoder for the classification tools. 208 209 Args: 210 model_type: One of the keys in `VFM_MODELS`, e.g. 'vit_b_dinov2', 'vit_b_dinov3' or 'vit_sam3'. 211 device: The device to load the model on. By default the best available device. 212 checkpoint_path: For DINOv3 (HuggingFace), an optional local model directory to load instead of 213 the gated HuggingFace repo. For SAM3, an optional local SAM3 checkpoint to load instead of 214 auto-downloading from HuggingFace. Ignored for DINOv2, whose weights download automatically. 215 img_size: The longest-side input size; snapped down to a multiple of the patch size. A model that 216 pins its native size (e.g. SAM3 at 1008) overrides this. 217 218 Returns: 219 The VFM encoder. 220 """ 221 if model_type not in VFM_MODELS: 222 raise ValueError( 223 f"Unknown VFM model '{model_type}'. Available models: {sorted(VFM_MODELS)}." 224 ) 225 spec = VFM_MODELS[model_type] 226 # A model can pin its native input size (e.g. SAM3 at 1008), which overrides the passed default. 227 img_size = spec.get("img_size", img_size) 228 device = util.get_device(device) 229 230 # xFormers' memory-efficient attention is CUDA-only. On CPU some backbones (e.g. the torch.hub DINOv2 231 # code) would try it and crash, so disable it there. The DINOv2-derived code reads this env var at 232 # import, so it must be set before the backbone is loaded. No-op if xFormers is not installed. 233 if str(device) == "cpu": 234 os.environ.setdefault("XFORMERS_DISABLED", "1") 235 236 if spec["backend"] == "torch_hub": # DINOv2: code + weights auto-download, no authentication. 237 model = _load_torch_hub_model(spec) 238 elif spec["backend"] == "hf": # DINOv3: HuggingFace via transformers, user's own HF access. 239 model = _load_hf_model(spec["repo"], spec["cache_folder"], checkpoint_path) 240 elif spec["backend"] == "sam3": # SAM3: the image-model ViT trunk via the sam3 package. 241 model = _load_sam3_model(checkpoint_path) 242 else: # 'timm': UNI / UNI2-h from HuggingFace via timm, user's own HF access. 243 model = _load_timm_model(spec) 244 245 encoder = VFMEncoder(model, spec, img_size=img_size, device=device) 246 encoder.model_type = model_type 247 encoder.model_name = model_type 248 return encoder
Load a DINO / UNI encoder for the classification tools.
Arguments:
- model_type: One of the keys in
VFM_MODELS, e.g. 'vit_b_dinov2', 'vit_b_dinov3' or 'vit_sam3'. - device: The device to load the model on. By default the best available device.
- checkpoint_path: For DINOv3 (HuggingFace), an optional local model directory to load instead of the gated HuggingFace repo. For SAM3, an optional local SAM3 checkpoint to load instead of auto-downloading from HuggingFace. Ignored for DINOv2, whose weights download automatically.
- img_size: The longest-side input size; snapped down to a multiple of the patch size. A model that pins its native size (e.g. SAM3 at 1008) overrides this.
Returns:
The VFM encoder.
589def precompute_vfm_embeddings( 590 predictor: VFMEncoder, 591 input_: np.ndarray, 592 save_path: Optional[Union[str, os.PathLike]] = None, 593 ndim: Optional[int] = None, 594 tile_shape: Optional[Tuple[int, int]] = None, 595 halo: Optional[Tuple[int, int]] = None, 596 verbose: bool = True, 597 lazy_loading: bool = False, 598 pbar_init: Optional[callable] = None, 599 pbar_update: Optional[callable] = None, 600 **kwargs, 601) -> util.ImageEmbeddings: 602 """Compute VFM image embeddings in the `ImageEmbeddings` format used by the classification tools. 603 604 This mirrors the SAM embedding API (same signature and return contract) so that it can be used as a 605 drop-in for VFM (DINO / UNI) encoders. Supports 2D and 3D images, with or without tiling. 606 607 Args: 608 predictor: The VFM encoder (named 'predictor' to match the SAM precompute signature). 609 input_: The input data, 2D (H, W[, C]) or 3D (Z, H, W[, C]). 610 save_path: Optional path to a zarr container to cache the embeddings. 611 ndim: The dimensionality of the data. If not given, deduced from the input. 612 tile_shape: Shape of tiles for tiled embedding computation. By default no tiling. 613 halo: Overlap of the tiles for tiled embedding computation. By default no tiling. 614 verbose: Whether to be verbose. 615 lazy_loading: Unused; accepted for signature compatibility. 616 pbar_init: Callback to initialize an external progress bar (steps, description). 617 pbar_update: Callback to update an external progress bar. 618 619 Returns: 620 The image embeddings. 621 """ 622 ndim = input_.ndim if ndim is None else ndim 623 if ndim not in (2, 3): 624 raise ValueError(f"Invalid dimensionality {ndim}, expect 2 or 3 dimensional data.") 625 626 # Open or create the zarr container and return cached embeddings if they match. Otherwise truncate. 627 if save_path is None: 628 f = util._open_embeddings(None) 629 elif os.path.exists(save_path): 630 f = util._open_embeddings(save_path, mode="a") 631 cached = _load_cached_embeddings(f, predictor, input_) 632 if cached is not None: 633 return cached 634 f = util._open_embeddings(save_path, mode="w") 635 else: 636 f = util._open_embeddings(save_path, mode="a") 637 638 pbar_init, pbar_update, pbar_close = _handle_pbar(verbose, pbar_init, pbar_update) 639 is_3d = ndim == 3 640 if tile_shape is not None: 641 embeddings = _compute_vfm_tiled(predictor, input_, tile_shape, halo, f, pbar_init, pbar_update, is_3d) 642 elif is_3d: 643 embeddings = _compute_vfm_3d(predictor, input_, f, save_path, pbar_init, pbar_update) 644 else: 645 embeddings = _compute_vfm_2d(predictor, input_, f, save_path, pbar_init, pbar_update) 646 pbar_close() 647 return embeddings
Compute VFM image embeddings in the ImageEmbeddings format used by the classification tools.
This mirrors the SAM embedding API (same signature and return contract) so that it can be used as a drop-in for VFM (DINO / UNI) encoders. Supports 2D and 3D images, with or without tiling.
Arguments:
- predictor: The VFM encoder (named 'predictor' to match the SAM precompute signature).
- input_: The input data, 2D (H, W[, C]) or 3D (Z, H, W[, C]).
- save_path: Optional path to a zarr container to cache the embeddings.
- ndim: The dimensionality of the data. If not given, deduced from the input.
- tile_shape: Shape of tiles for tiled embedding computation. By default no tiling.
- halo: Overlap of the tiles for tiled embedding computation. By default no tiling.
- verbose: Whether to be verbose.
- lazy_loading: Unused; accepted for signature compatibility.
- pbar_init: Callback to initialize an external progress bar (steps, description).
- pbar_update: Callback to update an external progress bar.
Returns:
The image embeddings.