""" OMNI: Scaling Multi-Teacher Distillation for Digital Pathology. This file contains everything needed to run an OMNI vision encoder with Hugging Face `transformers` (`trust_remote_code=True`): - OmniConfig : architecture hyper-parameters (read from `config.json`). - OmniModel : ViT backbone with a Mixture-of-Experts (MoE) tail and one learnable token per teacher. The model takes a batch of 224x224 RGB tiles and returns, by default, a single embedding per tile: the average of its M teacher-specific tokens. Example: >>> from transformers import AutoModel >>> model = AutoModel.from_pretrained("sofieneb/omni-base", trust_remote_code=True).eval() >>> transform = model.get_transform() >>> x = transform(pil_image).unsqueeze(0) # (1, 3, 224, 224) >>> emb = model(x) # (1, D) >>> out = model(x, return_teacher_tokens=True) >>> out["embedding"], out["teacher_tokens"] # (1, D), (1, M, D) """ import torch import torch.nn as nn import torch.nn.functional as F from transformers import PretrainedConfig, PreTrainedModel # ============================================================ # Configuration # ============================================================ class OmniConfig(PretrainedConfig): """ Configuration of an OMNI encoder. Args: embed_dim (int): Token dimension D. depth (int): Total number of transformer blocks. num_heads (int): Number of attention heads. mlp_ratio (float): Hidden size of every feed-forward network / expert, as a multiple of D. num_moe_layers (int): Number of final blocks whose FFN is a Mixture-of-Experts layer. num_experts (int): Number of experts in each MoE layer. moe_top_k (int): Number of experts selected per token. img_size (int): Input resolution (square images). patch_size (int): Patch size of the patch embedding. teachers (list[str]): Teacher names, in the order of the teacher tokens. image_mean (list[float]): Normalization mean used at training time. image_std (list[float]): Normalization std used at training time. """ model_type = "omni" def __init__( self, embed_dim: int = 768, depth: int = 12, num_heads: int = 12, mlp_ratio: float = 3.0, num_moe_layers: int = 3, num_experts: int = 5, moe_top_k: int = 2, img_size: int = 224, patch_size: int = 14, teachers: list = None, image_mean: list = (0.485, 0.456, 0.406), image_std: list = (0.229, 0.224, 0.225), **kwargs, ): self.embed_dim = embed_dim self.depth = depth self.num_heads = num_heads self.mlp_ratio = mlp_ratio self.num_moe_layers = num_moe_layers self.num_experts = num_experts self.moe_top_k = moe_top_k # not `top_k`: that name is reserved for generation in transformers 4.x self.img_size = img_size self.patch_size = patch_size self.teachers = list(teachers) if teachers is not None else [] self.image_mean = list(image_mean) self.image_std = list(image_std) super().__init__(**kwargs) # ============================================================ # Building blocks # ============================================================ class Attention(nn.Module): """ Multi-head self-attention using PyTorch's fused scaled-dot-product attention. Args: dim (int): Token dimension. num_heads (int): Number of attention heads. qkv_bias (bool): Whether the query/key/value projection has a bias. """ def __init__(self, dim: int, num_heads: int, qkv_bias: bool): super().__init__() self.num_heads = num_heads self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.proj = nn.Linear(dim, dim) def forward(self, x: torch.Tensor, attn_mask: torch.Tensor) -> torch.Tensor: """ Args: x (torch.Tensor): Tokens of shape (B, N, D). attn_mask (torch.Tensor): Additive mask of shape (N, N) (0 = attend, -inf = masked). Returns: torch.Tensor: Updated tokens of shape (B, N, D). """ B, N, D = x.shape # (B, N, 3*D) -> (3, B, heads, N, head_dim) qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, D // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv.unbind(0) x = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask) return self.proj(x.transpose(1, 2).reshape(B, N, D)) class Mlp(nn.Module): """ Two-layer feed-forward network (Linear -> GELU -> Linear). Args: dim (int): Input / output dimension. hidden_dim (int): Hidden dimension. """ def __init__(self, dim: int, hidden_dim: int): super().__init__() self.fc1 = nn.Linear(dim, hidden_dim) self.fc2 = nn.Linear(hidden_dim, dim) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x (torch.Tensor): Input of shape (..., dim). Returns: torch.Tensor: Output of shape (..., dim). """ return self.fc2(F.gelu(self.fc1(x))) class MoE(nn.Module): """ Sparse Mixture-of-Experts feed-forward layer with top-k routing. A linear router scores every expert for each token; the top-k experts are applied and their outputs are combined with the (re-normalized) router weights. Args: dim (int): Token dimension. hidden_dim (int): Hidden dimension of each expert. num_experts (int): Number of experts. top_k (int): Number of experts used per token. """ def __init__(self, dim: int, hidden_dim: int, num_experts: int, top_k: int): super().__init__() self.top_k = top_k self.router = nn.Linear(dim, num_experts, bias=False) self.experts = nn.ModuleList([Mlp(dim, hidden_dim) for _ in range(num_experts)]) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x (torch.Tensor): Tokens of shape (B, N, D). Returns: torch.Tensor: Tokens of shape (B, N, D). """ B, N, D = x.shape x = x.reshape(-1, D) # Select the top-k experts per token and re-normalize their weights to sum to 1. probs = F.softmax(self.router(x), dim=-1) weights, selected = torch.topk(probs, self.top_k, dim=-1) weights = weights / weights.sum(dim=-1, keepdim=True) # Run each expert only on the tokens that were routed to it. out = torch.zeros_like(x) for i, expert in enumerate(self.experts): token_idx, slot_idx = torch.where(selected == i) if token_idx.numel() > 0: w = weights[token_idx, slot_idx].unsqueeze(1) # Cast back to the accumulator dtype (expert outputs are half precision under autocast). out.index_add_(0, token_idx, (expert(x[token_idx]) * w).to(out.dtype)) return out.view(B, N, D) class Block(nn.Module): """ Pre-norm transformer block: x + Attn(LN(x)), then x + FFN(LN(x)). Args: dim (int): Token dimension. num_heads (int): Number of attention heads. mlp_ratio (float): FFN hidden size as a multiple of dim. use_moe (bool): If True, the FFN is a MoE layer, otherwise a dense MLP. num_experts (int): Number of experts (MoE blocks only). top_k (int): Experts per token (MoE blocks only). """ def __init__(self, dim: int, num_heads: int, mlp_ratio: float, use_moe: bool, num_experts: int, top_k: int): super().__init__() hidden_dim = int(dim * mlp_ratio) self.norm1 = nn.LayerNorm(dim) # Note: dense blocks were trained with a qkv bias, MoE blocks without. self.attn = Attention(dim, num_heads, qkv_bias=not use_moe) self.norm2 = nn.LayerNorm(dim) self.ffn = MoE(dim, hidden_dim, num_experts, top_k) if use_moe else Mlp(dim, hidden_dim) def forward(self, x: torch.Tensor, attn_mask: torch.Tensor) -> torch.Tensor: """ Args: x (torch.Tensor): Tokens of shape (B, N, D). attn_mask (torch.Tensor): Additive attention mask of shape (N, N). Returns: torch.Tensor: Tokens of shape (B, N, D). """ x = x + self.attn(self.norm1(x), attn_mask) x = x + self.ffn(self.norm2(x)) return x # ============================================================ # OMNI model # ============================================================ class OmniModel(PreTrainedModel): """ OMNI vision encoder. The input sequence is [teacher tokens (M) | patch tokens (Np)]. A structured attention mask lets each teacher token attend only to itself and to the patch tokens, while patch tokens attend only to patch tokens. After the final LayerNorm, each teacher token is a teacher-specific representation of the tile. Args: config (OmniConfig): Model configuration. """ config_class = OmniConfig base_model_prefix = "omni" main_input_name = "pixel_values" def __init__(self, config: OmniConfig): super().__init__(config) D = config.embed_dim num_teachers = len(config.teachers) num_patches = (config.img_size // config.patch_size) ** 2 # Patch embedding + learnable positional embedding of the patch tokens. self.patch_embed = nn.Conv2d(3, D, kernel_size=config.patch_size, stride=config.patch_size) self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, D)) # One learnable token (and positional embedding) per teacher. self.teacher_tokens = nn.Parameter(torch.zeros(1, num_teachers, D)) self.teacher_pos_embed = nn.Parameter(torch.zeros(1, num_teachers, D)) # Dense blocks first, MoE blocks for the last `num_moe_layers` blocks. first_moe = config.depth - config.num_moe_layers self.blocks = nn.ModuleList( [ Block(D, config.num_heads, config.mlp_ratio, i >= first_moe, config.num_experts, config.moe_top_k) for i in range(config.depth) ] ) self.norm = nn.LayerNorm(D) self.post_init() def _init_weights(self, module: nn.Module): """ Weight initialization (only used for weights missing from the checkpoint). Args: module (nn.Module): Module to initialize. """ if isinstance(module, (nn.Linear, nn.Conv2d)): 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): nn.init.ones_(module.weight) nn.init.zeros_(module.bias) @property def teachers(self) -> list: """list[str]: Teacher names, in the order of the teacher tokens.""" return self.config.teachers def get_transform(self): """ Returns the preprocessing used at training time (resize to 224, ImageNet normalization). Returns: torchvision.transforms.Compose: Transform mapping a PIL image to a (3, 224, 224) tensor. """ import torchvision.transforms as T return T.Compose( [ T.Resize((self.config.img_size, self.config.img_size)), T.ToTensor(), T.Normalize(mean=self.config.image_mean, std=self.config.image_std), ] ) def _attention_mask(self, num_teachers: int, num_patches: int, device: torch.device) -> torch.Tensor: """ Builds the structured attention mask (rows = queries, columns = keys). - teacher token -> itself only among teacher tokens (no cross-teacher leakage) - teacher token -> all patch tokens - patch token -> all patch tokens (patch tokens never see teacher tokens) Args: num_teachers (int): Number of teacher tokens M. num_patches (int): Number of patch tokens Np. device (torch.device): Device of the mask. Returns: torch.Tensor: Additive mask of shape (M + Np, M + Np) with 0 (attend) or -inf (masked). """ M, L = num_teachers, num_teachers + num_patches allowed = torch.zeros(L, L, dtype=torch.bool, device=device) allowed[:M, :M] = torch.eye(M, dtype=torch.bool, device=device) allowed[:M, M:] = True allowed[M:, M:] = True mask = torch.full((L, L), float("-inf"), device=device) return mask.masked_fill(allowed, 0.0) def forward( self, pixel_values: torch.Tensor, return_teacher_tokens: bool = False, return_patch_tokens: bool = False, ): """ Encodes a batch of tiles. Args: pixel_values (torch.Tensor): Normalized images of shape (B, 3, 224, 224) (see `get_transform`). return_teacher_tokens (bool): Also return the M teacher-specific tokens. return_patch_tokens (bool): Also return the patch tokens. Returns: torch.Tensor: If no flag is set, the tile embedding of shape (B, D), i.e. the average of the M teacher tokens. dict: If a flag is set, a dict with: - "embedding" (B, D): average of the teacher tokens. - "teacher_tokens" (B, M, D): one token per teacher, ordered as `model.teachers` (only if `return_teacher_tokens`). - "patch_tokens" (B, Np, D): patch tokens, Np = 16 x 16 = 256 (only if `return_patch_tokens`). """ B = pixel_values.shape[0] # Patch tokens: (B, 3, H, W) -> (B, Np, D). patches = self.patch_embed(pixel_values).flatten(2).transpose(1, 2) + self.pos_embed # Prepend the teacher tokens: (B, M + Np, D). teachers = (self.teacher_tokens + self.teacher_pos_embed).expand(B, -1, -1) x = torch.cat([teachers, patches], dim=1) M = teachers.shape[1] attn_mask = self._attention_mask(M, patches.shape[1], x.device).to(x.dtype) for block in self.blocks: x = block(x, attn_mask) x = self.norm(x) teacher_tokens, patch_tokens = x[:, :M], x[:, M:] embedding = teacher_tokens.mean(dim=1) if not (return_teacher_tokens or return_patch_tokens): return embedding out = {"embedding": embedding} if return_teacher_tokens: out["teacher_tokens"] = teacher_tokens if return_patch_tokens: out["patch_tokens"] = patch_tokens return out