Image Feature Extraction
Transformers
PyTorch
manekko_3d
feature-extraction
vision-transformer
3d
medical-imaging
manekko
custom_code
Instructions to use Tenbatsu2424/Manekko_PanCancerCT with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Tenbatsu2424/Manekko_PanCancerCT with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-feature-extraction", model="Tenbatsu2424/Manekko_PanCancerCT", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("Tenbatsu2424/Manekko_PanCancerCT", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Download modeling_manekko.py from Tenbatsu2424/Manekko_PanCancerCT: direct link, hf CLI and curl.
- Browser
- Download file 15.4 kB
-
https://huggingface.co/Tenbatsu2424/Manekko_PanCancerCT/resolve/main/modeling_manekko.py
- Command line
-
hf download hf://Tenbatsu2424/Manekko_PanCancerCT/modeling_manekko.py
-
curl -L -o modeling_manekko.py https://huggingface.co/Tenbatsu2424/Manekko_PanCancerCT/resolve/main/modeling_manekko.py
15.4 kB
| """3D Manekko feature encoder and Hugging Face loading interface.""" | |
| from __future__ import annotations | |
| import math | |
| from pathlib import Path | |
| from typing import Mapping | |
| import torch | |
| from torch import nn | |
| from dynamic_network_architectures.building_blocks.patch_encode_decode import ( | |
| PatchEmbedDeeperControlled, | |
| ) | |
| from huggingface_hub import hf_hub_download | |
| from huggingface_hub.errors import EntryNotFoundError | |
| from safetensors.torch import load_file, save_file | |
| from transformers import PreTrainedModel | |
| from .configuration_manekko import ManekkoConfig | |
| from .eva_manekko import Eva | |
| from .layers_manekko import LayerScale | |
| class WeightsUnavailableError(OSError): | |
| """The architecture exists, but the requested pretrained weights do not.""" | |
| WEIGHT_FILENAMES = ( | |
| "model.safetensors", | |
| "pytorch_model.bin", | |
| "checkpoint_final.pth", | |
| "checkpoint.pth", | |
| "checkpoint.ckpt", | |
| "encoder.ckpt", | |
| ) | |
| def extract_encoder_state_dict(payload: Mapping) -> dict[str, torch.Tensor]: | |
| """Extract encoder tensors, selecting ``model.*`` in Lightning checkpoints.""" | |
| if not isinstance(payload, Mapping): | |
| raise TypeError("Expected a checkpoint mapping containing tensor weights") | |
| state = payload.get("state_dict", payload) | |
| if not isinstance(state, Mapping): | |
| raise TypeError("checkpoint['state_dict'] must be a mapping") | |
| state = dict(state) | |
| for prefix in ("module.", "_orig_mod."): | |
| if state and all(isinstance(k, str) and k.startswith(prefix) for k in state): | |
| state = {k[len(prefix) :]: v for k, v in state.items()} | |
| if any(isinstance(k, str) and k.startswith("model.") for k in state): | |
| state = { | |
| k[len("model.") :]: v | |
| for k, v in state.items() | |
| if isinstance(k, str) and k.startswith("model.") | |
| } | |
| if not state or not all( | |
| isinstance(k, str) and isinstance(v, torch.Tensor) for k, v in state.items() | |
| ): | |
| raise ValueError("No tensor-only encoder state dictionary was found") | |
| return state | |
| def load_encoder_file(path: str | Path) -> dict[str, torch.Tensor]: | |
| path = Path(path) | |
| if path.suffix == ".safetensors": | |
| return extract_encoder_state_dict(load_file(str(path), device="cpu")) | |
| # Never execute objects embedded in pickled model uploads. | |
| try: | |
| payload = torch.load(path, map_location="cpu", weights_only=True) | |
| except Exception as exc: | |
| raise ValueError( | |
| "Could not read this checkpoint with torch.load(weights_only=True). " | |
| "Export a tensor-only encoder state dictionary or model.safetensors " | |
| "from the trusted training environment." | |
| ) from exc | |
| return extract_encoder_state_dict(payload) | |
| def _find_weight_file( | |
| repo_or_path, | |
| config, | |
| *, | |
| revision, | |
| cache_dir, | |
| token, | |
| local_files_only, | |
| force_download, | |
| ): | |
| filenames = ( | |
| (config.weights_filename,) if config.weights_filename else WEIGHT_FILENAMES | |
| ) | |
| for name in filenames: | |
| if ( | |
| not isinstance(name, str) | |
| or Path(name).name != name | |
| or not name.endswith((".safetensors", ".bin", ".pth", ".pt", ".ckpt")) | |
| ): | |
| raise ValueError( | |
| "weights_filename must be a top-level safetensors or PyTorch checkpoint filename" | |
| ) | |
| location = Path(str(repo_or_path)).expanduser() | |
| if location.is_dir(): | |
| for name in filenames: | |
| if (location / name).is_file(): | |
| return location / name | |
| else: | |
| for name in filenames: | |
| try: | |
| return Path( | |
| hf_hub_download( | |
| repo_id=str(repo_or_path), | |
| filename=name, | |
| revision=revision, | |
| cache_dir=cache_dir, | |
| token=token, | |
| local_files_only=local_files_only, | |
| force_download=force_download, | |
| ) | |
| ) | |
| except EntryNotFoundError: | |
| continue | |
| raise WeightsUnavailableError( | |
| f"Weights unavailable for {repo_or_path}. This repository currently provides " | |
| "the Manekko architecture and feature API without pretrained weights. " | |
| "The owner can add model.safetensors using convert_checkpoint.py. " | |
| "No randomly initialized model has been substituted." | |
| ) | |
| class ManekkoModel(PreTrainedModel): | |
| config_class = ManekkoConfig | |
| main_input_name = "pixel_values" | |
| base_model_prefix = "" | |
| _no_split_modules = ["EvaBlock3D"] | |
| def __init__(self, config: ManekkoConfig): | |
| super().__init__(config) | |
| self.volume_size = tuple(config.volume_size) | |
| self.patch_size = tuple(config.patch_size) | |
| self.med_in_channels = config.in_channels | |
| self.embed_dim = config.embed_dim | |
| self.num_features = config.embed_dim | |
| self.depth = config.depth | |
| self.num_heads = config.num_heads | |
| self.num_register_tokens = config.num_register_tokens | |
| self.use_mask = config.use_mask | |
| self.patch_embed = PatchEmbedDeeperControlled( | |
| input_channels=config.in_channels, | |
| embed_dim=config.embed_dim, | |
| depth_per_level=tuple(config.depth_per_level), | |
| ch_per_level=tuple(config.ch_per_level), | |
| add_skips=config.add_skips, | |
| nonlin=nn.LeakyReLU, | |
| ) | |
| self.eva = Eva( | |
| embed_dim=config.embed_dim, | |
| depth=config.depth, | |
| num_heads=config.num_heads, | |
| ref_feat_shape=tuple( | |
| v // p for v, p in zip(config.volume_size, config.patch_size) | |
| ), | |
| num_reg_tokens=config.num_register_tokens, | |
| use_rot_pos_emb=config.use_rot_pos_emb, | |
| use_abs_pos_emb=config.use_abs_pos_embed, | |
| mlp_ratio=config.mlp_ratio, | |
| drop_path_rate=config.drop_path_rate, | |
| proj_drop_rate=config.proj_drop_rate, | |
| attn_drop_rate=config.attn_drop_rate, | |
| rope_kwargs=config.rope_kwargs, | |
| init_values=config.init_values, | |
| ) | |
| if config.use_mask: | |
| # Checkpoint parameter; unused during feature extraction. | |
| self.mask_token = nn.Parameter(torch.zeros(1, config.embed_dim)) | |
| self.register_tokens = ( | |
| nn.Parameter(torch.zeros(1, config.num_register_tokens, config.embed_dim)) | |
| if config.num_register_tokens | |
| else None | |
| ) | |
| self.post_init() | |
| if self.register_tokens is not None: | |
| nn.init.trunc_normal_(self.register_tokens, std=0.02) | |
| if config.use_mask: | |
| nn.init.trunc_normal_(self.mask_token, std=0.02) | |
| def _init_weights(self, module): | |
| if isinstance(module, (nn.Linear, nn.Conv3d)): | |
| nn.init.trunc_normal_(module.weight, std=0.02) | |
| if module.bias is not None: | |
| nn.init.zeros_(module.bias) | |
| elif isinstance(module, nn.LayerNorm): | |
| if module.weight is not None: | |
| nn.init.ones_(module.weight) | |
| if module.bias is not None: | |
| nn.init.zeros_(module.bias) | |
| elif isinstance(module, LayerScale): | |
| module.reset_parameters() | |
| def blocks(self): | |
| """Transformer blocks.""" | |
| return self.eva.blocks | |
| def norm(self): | |
| return self.eva.norm | |
| def forward_features(self, x: torch.Tensor) -> dict: | |
| """Extract features from preprocessed float volumes ``[B,C,D,H,W]``. | |
| Spatial sizes must be divisible by the stride (8 for Small). | |
| Returns ``latent [B,E]``, ``patch_latent [B,E,Dp,Hp,Wp]``, | |
| ``patch_tokens [B,Dp*Hp*Wp,E]``, and ``grid_shape (Dp,Hp,Wp)``. | |
| Patch tokens exclude prefix tokens and flatten the last axis fastest. | |
| """ | |
| if not isinstance(x, torch.Tensor) or x.ndim != 5: | |
| raise ValueError("Manekko expects a 3D volume batch [B,C,D,H,W]") | |
| if x.shape[0] < 1 or x.shape[1] != self.med_in_channels: | |
| raise ValueError( | |
| f"Expected a nonempty batch with {self.med_in_channels} input channel(s)" | |
| ) | |
| if not x.is_floating_point(): | |
| raise ValueError( | |
| "Input must be floating point; normalize/convert it before inference" | |
| ) | |
| spatial = tuple(x.shape[-3:]) | |
| if any(v <= 0 or v % p for v, p in zip(spatial, self.patch_size)): | |
| raise ValueError( | |
| f"Input spatial dimensions {spatial} must be positive multiples of {self.patch_size}" | |
| ) | |
| grid = tuple(v // p for v, p in zip(spatial, self.patch_size)) | |
| if math.prod(grid) < 2: | |
| raise ValueError( | |
| "The convolutional stem needs at least two spatial patches for instance normalization" | |
| ) | |
| features = self.patch_embed(x) | |
| actual_grid = tuple(features.shape[-3:]) | |
| if actual_grid != grid: | |
| raise RuntimeError( | |
| f"Patch stem produced grid {actual_grid}, expected {grid}" | |
| ) | |
| tokens = features.flatten(2).transpose(1, 2) | |
| if self.register_tokens is not None: | |
| tokens = torch.cat( | |
| (self.register_tokens.expand(x.shape[0], -1, -1), tokens), dim=1 | |
| ) | |
| tokens = self.eva(tokens, feat_shape=grid) | |
| latent = tokens[:, 0] | |
| patch_tokens = tokens[:, 1 + self.num_register_tokens :] | |
| patch_latent = patch_tokens.transpose(1, 2).reshape( | |
| x.shape[0], self.embed_dim, *grid | |
| ) | |
| return { | |
| "latent": latent, | |
| "patch_latent": patch_latent, | |
| "patch_tokens": patch_tokens, | |
| "grid_shape": grid, | |
| } | |
| def forward(self, pixel_values: torch.Tensor, return_dict=True): | |
| result = self.forward_features(pixel_values) | |
| return result if return_dict else (result["latent"], result["patch_latent"]) | |
| def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): | |
| """Load complete encoder weights from a Hub repository or local folder. | |
| Accepts unsharded safetensors or tensor-only Torch files. Missing or | |
| incompatible weights raise. Use ``model.to(device)`` after loading. | |
| """ | |
| if model_args: | |
| raise TypeError( | |
| "Manekko.from_pretrained takes no positional model arguments" | |
| ) | |
| config = kwargs.pop("config", None) | |
| hub_keys = ( | |
| "revision", | |
| "cache_dir", | |
| "token", | |
| "local_files_only", | |
| "force_download", | |
| ) | |
| defaults = { | |
| "revision": "main", | |
| "cache_dir": None, | |
| "token": None, | |
| "local_files_only": False, | |
| "force_download": False, | |
| } | |
| hub = {k: kwargs.pop(k, defaults[k]) for k in hub_keys} | |
| dtype = kwargs.pop("dtype", kwargs.pop("torch_dtype", None)) | |
| output_loading_info = kwargs.pop("output_loading_info", False) | |
| if kwargs.pop("ignore_mismatched_sizes", False): | |
| raise ValueError("Manekko requires complete, matching encoder weights") | |
| if kwargs.pop("weights_only", True) is not True: | |
| raise ValueError( | |
| "Only safe weights_only=True checkpoint loading is supported" | |
| ) | |
| for key in ( | |
| "trust_remote_code", | |
| "code_revision", | |
| "_from_auto", | |
| "_from_pipeline", | |
| "_commit_hash", | |
| "adapter_kwargs", | |
| "use_safetensors", | |
| ): | |
| kwargs.pop(key, None) | |
| if kwargs: | |
| raise TypeError( | |
| f"Unsupported loading arguments: {', '.join(sorted(kwargs))}. Move the loaded model with model.to(device)." | |
| ) | |
| if config is None: | |
| config = ManekkoConfig.from_pretrained(pretrained_model_name_or_path, **hub) | |
| elif isinstance(config, (str, Path)): | |
| config = ManekkoConfig.from_pretrained(config, **hub) | |
| path = _find_weight_file(pretrained_model_name_or_path, config, **hub) | |
| state = load_encoder_file(path) | |
| model = cls(config) | |
| try: | |
| model.load_state_dict(state, strict=True) | |
| except RuntimeError as exc: | |
| raise ValueError( | |
| "Checkpoint does not exactly match this Manekko encoder configuration. " | |
| "Export the correct student encoder and verify config.json; partial " | |
| "or random initialization is not permitted." | |
| ) from exc | |
| if dtype == "auto": | |
| dtype = next( | |
| (v.dtype for v in state.values() if v.is_floating_point()), | |
| torch.float32, | |
| ) | |
| if isinstance(dtype, str): | |
| dtype = { | |
| "float32": torch.float32, | |
| "float16": torch.float16, | |
| "bfloat16": torch.bfloat16, | |
| }.get(dtype, dtype) | |
| if dtype is not None: | |
| if dtype not in ( | |
| torch.float32, | |
| torch.float16, | |
| torch.bfloat16, | |
| torch.float64, | |
| ): | |
| raise ValueError(f"Unsupported floating dtype {dtype!r}") | |
| model = model.to(dtype=dtype) | |
| model.eval() | |
| if output_loading_info: | |
| return model, { | |
| "missing_keys": [], | |
| "unexpected_keys": [], | |
| "mismatched_keys": [], | |
| "error_msgs": [], | |
| } | |
| return model | |
| def save_pretrained(self, save_directory, *, safe_serialization=True, **kwargs): | |
| """Save configuration, inference code, and safetensors weights. | |
| Clone parameter aliases to preserve every key required by strict loading. | |
| """ | |
| if not safe_serialization: | |
| raise ValueError("Use safetensors for Manekko Hub exports") | |
| if kwargs: | |
| raise TypeError(f"Unsupported save options: {', '.join(sorted(kwargs))}") | |
| folder = Path(save_directory) | |
| folder.mkdir(parents=True, exist_ok=True) | |
| tensors = { | |
| k: v.detach().cpu().contiguous().clone() | |
| for k, v in self.state_dict().items() | |
| } | |
| save_file(tensors, str(folder / "model.safetensors"), metadata={"format": "pt"}) | |
| self.config.weights_available = True | |
| self.config.weights_filename = "model.safetensors" | |
| self.config.save_pretrained(folder) | |
| source = Path(__file__).parent | |
| for name in ( | |
| "configuration_manekko.py", | |
| "modeling_manekko.py", | |
| "eva_manekko.py", | |
| "layers_manekko.py", | |
| ): | |
| target = folder / name | |
| if (source / name).resolve() != target.resolve(): | |
| target.write_bytes((source / name).read_bytes()) | |
| ManekkoModel.register_for_auto_class("AutoModel") | |