Feature Extraction
Transformers
Safetensors
English
mosaic
computational-pathology
multimodal
survival-analysis
custom_code
Instructions to use Astaxanthin/MOSAIC with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Astaxanthin/MOSAIC with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="Astaxanthin/MOSAIC", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("Astaxanthin/MOSAIC", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Download vision.py from Astaxanthin/MOSAIC: direct link, hf CLI and curl.
- Browser
- Download file 21.5 kB
-
https://huggingface.co/Astaxanthin/MOSAIC/resolve/main/vision.py
- Command line
-
hf download hf://Astaxanthin/MOSAIC/vision.py
-
curl -L -o vision.py https://huggingface.co/Astaxanthin/MOSAIC/resolve/main/vision.py
21.5 kB
| import math | |
| import random | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from nystrom_attention import NystromAttention | |
| class TransLayer(nn.Module): | |
| def __init__( | |
| self, | |
| norm_layer=nn.LayerNorm, | |
| dim=512, | |
| mlp_ratio=2.0, | |
| dropout=0.1, | |
| act_layer=nn.GELU, | |
| ): | |
| super().__init__() | |
| self.norm1 = norm_layer(dim) | |
| self.attn = NystromAttention( | |
| dim=dim, | |
| dim_head=dim // 8, | |
| heads=8, | |
| num_landmarks=dim // 2, | |
| pinv_iterations=6, | |
| residual=True, | |
| dropout=dropout, | |
| ) | |
| self.norm2 = norm_layer(dim) | |
| hidden_dim = int(dim * mlp_ratio) | |
| self.mlp = nn.Sequential( | |
| nn.Linear(dim, hidden_dim), | |
| act_layer(), | |
| nn.Dropout(dropout), | |
| nn.Linear(hidden_dim, dim), | |
| nn.Dropout(dropout), | |
| ) | |
| def forward(self, x, mask=None): | |
| token_mask = None | |
| attn_mask = None | |
| if mask is not None: | |
| attn_mask = mask.bool() | |
| token_mask = attn_mask.unsqueeze(-1).to(dtype=x.dtype) | |
| x = x * token_mask | |
| if not attn_mask.any(dim=1).all(): | |
| raise ValueError("Each sample must have at least one valid token before NystromAttention.") | |
| x = x + self.attn(self.norm1(x), mask=attn_mask) | |
| if token_mask is not None: | |
| x = x * token_mask | |
| x = x + self.mlp(self.norm2(x)) | |
| if token_mask is not None: | |
| x = x * token_mask | |
| return x | |
| class MultiKernelConv2DTransCLS(nn.Module): | |
| """ | |
| 2D version of MultiKernelConv1DTransCLS. | |
| It keeps the original idea: | |
| multi-kernel conv -> residual -> CLS tokens -> TransLayer stack -> cls feats. | |
| New parts: | |
| 1) tile feats are treated as a 2D grid. | |
| 2) 2D coords are encoded by a small MLP and added as position embeddings. | |
| 3) optional avg-pooling can reduce 100x100 -> 50x50 before Transformer. | |
| """ | |
| def __init__( | |
| self, | |
| in_channels=768, | |
| out_channels=768, | |
| head_num=1, | |
| trans_num=4, | |
| assume_ordered_square=False, | |
| recon_mask_ratio=0.0, | |
| eval_pos_norm_grid_size=None, | |
| ): | |
| super().__init__() | |
| self.head_num = head_num | |
| self.assume_ordered_square = assume_ordered_square | |
| self.recon_mask_ratio = recon_mask_ratio | |
| self.eval_pos_norm_grid_size = eval_pos_norm_grid_size | |
| self.input_proj = nn.Identity() if in_channels == out_channels else nn.Linear(in_channels, out_channels) | |
| self.conv1 = nn.Conv2d( | |
| in_channels=out_channels, | |
| out_channels=out_channels, | |
| kernel_size=3, | |
| padding=1, | |
| ) | |
| self.conv2 = nn.Conv2d( | |
| in_channels=out_channels, | |
| out_channels=out_channels, | |
| kernel_size=5, | |
| padding=2, | |
| ) | |
| self.conv3 = nn.Conv2d( | |
| in_channels=out_channels, | |
| out_channels=out_channels, | |
| kernel_size=7, | |
| padding=3, | |
| ) | |
| # self.conv4 = nn.Conv2d( | |
| # in_channels=out_channels, | |
| # out_channels=out_channels, | |
| # kernel_size=3, | |
| # padding=1, | |
| # ) | |
| # self.conv5 = nn.Conv2d( | |
| # in_channels=out_channels, | |
| # out_channels=out_channels, | |
| # kernel_size=5, | |
| # padding=2, | |
| # ) | |
| # self.conv6 = nn.Conv2d( | |
| # in_channels=out_channels, | |
| # out_channels=out_channels, | |
| # kernel_size=7, | |
| # padding=3, | |
| # ) | |
| self.norm = nn.LayerNorm(out_channels) | |
| self.active = nn.ReLU() | |
| self.pos_mlp = nn.Sequential( | |
| nn.Linear(2, out_channels), | |
| nn.ReLU(), | |
| nn.Linear(out_channels, out_channels), | |
| ) | |
| self.cls_token = nn.Parameter(torch.randn(1, self.head_num, out_channels)) | |
| self.mask_token = nn.Parameter(torch.zeros(1, out_channels, 1, 1)) | |
| self.trans_layers = nn.Sequential( | |
| *[TransLayer(dim=out_channels) for _ in range(trans_num)] | |
| ) | |
| def _to_batched(self, x, coords): | |
| if len(x.shape) == 2: | |
| x = x.unsqueeze(0) | |
| if coords is not None and len(coords.shape) == 2: | |
| coords = coords.unsqueeze(0) | |
| if coords is None: | |
| raise ValueError("MultiKernelConv2DTransCLS requires patch coords for 2D position encoding.") | |
| if len(x.shape) != 3 or len(coords.shape) != 3: | |
| raise ValueError("x must be (B, N, C), coords must be (B, N, 2).") | |
| if x.shape[:2] != coords.shape[:2] or coords.shape[-1] != 2: | |
| raise ValueError("x and coords must have matching B/N dimensions, and coords last dim must be 2.") | |
| return x.float(), coords.to(device=x.device, dtype=torch.float32) | |
| def _ordered_square_to_grid(self, x, coords, input_valid=None, patch_size_lv0=None): | |
| B, N, C = x.shape | |
| H = W = int(math.sqrt(N)) | |
| if H * W != N: | |
| raise ValueError(f"Expected square number of tiles, got N={N}.") | |
| if input_valid is None: | |
| input_valid = x.detach().abs().sum(dim=-1).gt(0) | |
| coords_long = coords.long() | |
| patch_sizes = self._infer_patch_sizes(coords_long, valid_tokens=input_valid, patch_size_lv0=patch_size_lv0) | |
| coord_tokens = coords.clone() | |
| rows = torch.arange(H, device=x.device, dtype=coords.dtype) | |
| cols = torch.arange(W, device=x.device, dtype=coords.dtype) | |
| yy, xx = torch.meshgrid(rows, cols, indexing="ij") | |
| grid_offsets = torch.stack([yy.reshape(-1), xx.reshape(-1)], dim=-1) | |
| for b in range(B): | |
| valid_b = input_valid[b] | |
| if valid_b.any(): | |
| offset = coords_long[b, valid_b].min(dim=0).values.to(coords.dtype) | |
| else: | |
| offset = coords_long[b, :1].squeeze(0).to(coords.dtype) | |
| full_coords = offset.unsqueeze(0) + grid_offsets * patch_sizes[b].to(coords.dtype) | |
| coord_tokens[b, ~valid_b] = full_coords[~valid_b] | |
| valid_grid = input_valid.view(B, H, W).unsqueeze(1).contiguous() | |
| x_grid = x.view(B, H, W, C).permute(0, 3, 1, 2).contiguous() | |
| coord_grid = coord_tokens.view(B, H, W, 2).permute(0, 3, 1, 2).contiguous() | |
| return x_grid, coord_grid, valid_grid | |
| def _infer_patch_sizes(self, coords_long, valid_tokens=None, patch_size_lv0=None): | |
| """ | |
| Infer per-slide patch_size_lv0 from coords. | |
| Args: | |
| coords_long: Tensor, shape (B, N, 2) | |
| valid_tokens: optional bool Tensor, shape (B, N), True means real token | |
| patch_size_lv0: optional scalar or Tensor/list with shape (B,) | |
| Returns: | |
| Tensor shape (B,), one patch size per slide | |
| """ | |
| if coords_long.dim() == 2: | |
| coords_long = coords_long.unsqueeze(0) | |
| if valid_tokens is not None and valid_tokens.dim() == 1: | |
| valid_tokens = valid_tokens.unsqueeze(0) | |
| B = coords_long.size(0) | |
| device = coords_long.device | |
| def _as_batch_patch_sizes(value, name): | |
| if value is None: | |
| return None | |
| value = torch.as_tensor(value, device=device, dtype=torch.long).view(-1) | |
| if value.numel() == 1: | |
| return value.expand(B).clamp_min(1) | |
| if value.numel() != B: | |
| raise ValueError(f"{name} must be a scalar or have one value per slide in the batch.") | |
| return value.clamp_min(1) | |
| explicit_patch_sizes = _as_batch_patch_sizes(patch_size_lv0, "patch_size_lv0") | |
| if explicit_patch_sizes is not None: | |
| return explicit_patch_sizes | |
| fallback_patch_sizes = _as_batch_patch_sizes( | |
| getattr(self, "patch_size_lv0", None), | |
| "self.patch_size_lv0", | |
| ) | |
| patch_sizes = [] | |
| for b in range(B): | |
| coords_b = coords_long[b] | |
| if valid_tokens is not None: | |
| valid_b = valid_tokens[b].bool() | |
| coords_b = coords_b[valid_b] | |
| if coords_b.numel() == 0: | |
| if fallback_patch_sizes is not None: | |
| patch_sizes.append(fallback_patch_sizes[b]) | |
| else: | |
| patch_sizes.append(torch.ones((), device=device, dtype=torch.long)) | |
| continue | |
| slide_diffs = [] | |
| for axis in range(2): | |
| vals = torch.unique(coords_b[:, axis]) | |
| vals = torch.sort(vals).values | |
| if vals.numel() <= 1: | |
| continue | |
| diffs = vals[1:] - vals[:-1] | |
| diffs = diffs[diffs > 0] | |
| if diffs.numel() > 0: | |
| slide_diffs.append(diffs) | |
| if len(slide_diffs) > 0: | |
| slide_diffs = torch.cat(slide_diffs) | |
| values, counts = torch.unique(slide_diffs, return_counts=True) | |
| patch_sizes.append(values[counts.argmax()].clamp_min(1)) | |
| elif fallback_patch_sizes is not None: | |
| patch_sizes.append(fallback_patch_sizes[b]) | |
| else: | |
| patch_sizes.append(torch.ones((), device=device, dtype=torch.long)) | |
| return torch.stack(patch_sizes).to(device=device, dtype=torch.long).clamp_min(1) | |
| def _scatter_to_grid(self, x, coords, patch_size_lv0=None, input_valid=None): | |
| B, N, C = x.shape | |
| coords_long = coords.long() | |
| if input_valid is None: | |
| input_valid = x.detach().abs().sum(dim=-1).gt(0) | |
| patch_sizes = self._infer_patch_sizes(coords_long, valid_tokens=input_valid, patch_size_lv0=patch_size_lv0) | |
| per_slide_grid_coords = [] | |
| per_slide_hw = [] | |
| per_slide_offsets = [] | |
| for b in range(B): | |
| valid_b = input_valid[b] | |
| coords_b = coords_long[b, valid_b] | |
| x_b = x[b, valid_b] | |
| if coords_b.numel() == 0: | |
| coords_b = coords_long[b, :1] | |
| x_b = x[b, :1] | |
| offset = coords_b.min(dim=0).values | |
| grid_coords_b = torch.div( | |
| coords_b - offset.unsqueeze(0), | |
| patch_sizes[b], | |
| rounding_mode="floor", | |
| ) | |
| grid_coords_b = grid_coords_b - grid_coords_b.min(dim=0).values.unsqueeze(0) | |
| hw_b = grid_coords_b.amax(dim=0) + 1 | |
| per_slide_grid_coords.append((grid_coords_b, x_b, coords_b.to(coords.dtype))) | |
| per_slide_hw.append(hw_b) | |
| per_slide_offsets.append(offset) | |
| grid_hw = torch.stack(per_slide_hw, dim=0).amax(dim=0) | |
| H, W = int(grid_hw[0].item()), int(grid_hw[1].item()) | |
| x_grid = x.new_zeros(B, H * W, C) | |
| coord_grid = coords.new_zeros(B, H * W, 2) | |
| valid_grid = torch.zeros(B, H * W, device=x.device, dtype=torch.bool) | |
| count_grid = x.new_zeros(B, H * W, 1) | |
| rows = torch.arange(H, device=x.device, dtype=coords.dtype) | |
| cols = torch.arange(W, device=x.device, dtype=coords.dtype) | |
| yy, xx = torch.meshgrid(rows, cols, indexing="ij") | |
| for b, (grid_coords_b, x_b, coords_b) in enumerate(per_slide_grid_coords): | |
| offset = per_slide_offsets[b].to(coords.dtype) | |
| patch_size = patch_sizes[b].to(coords.dtype) | |
| full_coords = torch.stack( | |
| [ | |
| offset[0] + yy.reshape(-1) * patch_size, | |
| offset[1] + xx.reshape(-1) * patch_size, | |
| ], | |
| dim=-1, | |
| ) | |
| coord_grid[b] = full_coords | |
| flat_idx = grid_coords_b[:, 0] * W + grid_coords_b[:, 1] | |
| x_grid[b].scatter_add_(0, flat_idx.unsqueeze(-1).expand(-1, C), x_b) | |
| count_grid[b].scatter_add_(0, flat_idx.unsqueeze(-1), torch.ones_like(x_b[:, :1])) | |
| coord_grid[b].scatter_(0, flat_idx.unsqueeze(-1).expand(-1, 2), coords_b) | |
| valid_grid[b].scatter_(0, flat_idx, torch.ones(flat_idx.numel(), device=x.device, dtype=torch.bool)) | |
| x_grid = x_grid / count_grid.clamp_min(1.0) | |
| x_grid = x_grid.view(B, H, W, C).permute(0, 3, 1, 2).contiguous() | |
| coord_grid = coord_grid.view(B, H, W, 2).permute(0, 3, 1, 2).contiguous() | |
| valid_grid = valid_grid.view(B, H, W).unsqueeze(1).contiguous() | |
| return x_grid, coord_grid, valid_grid | |
| def _coord_pos_embed(self, coord_tokens, valid_tokens=None): | |
| if ( | |
| (not self.training) | |
| and self.eval_pos_norm_grid_size is not None | |
| and valid_tokens is not None | |
| ): | |
| side = int(math.sqrt(coord_tokens.size(1))) | |
| target_side = int(self.eval_pos_norm_grid_size) | |
| if side * side == coord_tokens.size(1) and side < target_side: | |
| norm_coords = torch.zeros_like(coord_tokens) | |
| offset = (target_side - side) // 2 | |
| denom = max(target_side - 1, 1) | |
| for b in range(coord_tokens.size(0)): | |
| valid_b = valid_tokens[b].bool() | |
| if not valid_b.any(): | |
| continue | |
| coords_b = coord_tokens[b, valid_b] | |
| c_min = coords_b.min(dim=0, keepdim=True).values | |
| c_max = coords_b.max(dim=0, keepdim=True).values | |
| grid_pos = (coords_b - c_min) / (c_max - c_min).clamp_min(1.0) | |
| grid_pos = grid_pos * max(side - 1, 1) + offset | |
| norm_coords[b, valid_b] = grid_pos / denom * 2.0 - 1.0 | |
| return self.pos_mlp(norm_coords) | |
| if valid_tokens is None: | |
| c_min = coord_tokens.min(dim=1, keepdim=True).values | |
| c_max = coord_tokens.max(dim=1, keepdim=True).values | |
| coord_tokens = (coord_tokens - c_min) / (c_max - c_min).clamp_min(1.0) | |
| coord_tokens = coord_tokens * 2.0 - 1.0 | |
| else: | |
| norm_coords = torch.zeros_like(coord_tokens) | |
| for b in range(coord_tokens.size(0)): | |
| valid_b = valid_tokens[b].bool() | |
| if not valid_b.any(): | |
| continue | |
| coords_b = coord_tokens[b, valid_b] | |
| c_min = coords_b.min(dim=0, keepdim=True).values | |
| c_max = coords_b.max(dim=0, keepdim=True).values | |
| coords_b = (coords_b - c_min) / (c_max - c_min).clamp_min(1.0) | |
| norm_coords[b, valid_b] = coords_b * 2.0 - 1.0 | |
| coord_tokens = norm_coords | |
| return self.pos_mlp(coord_tokens) | |
| def _conv_norm_active(self, conv, x_grid): | |
| y = conv(x_grid) | |
| y = y.permute(0, 2, 3, 1).contiguous() | |
| y = self.active(self.norm(y)) | |
| y = y.permute(0, 3, 1, 2).contiguous() | |
| return y | |
| def _tokens_to_grid(self, x, coords, patch_size_lv0=None): | |
| x, coords = self._to_batched(x, coords) | |
| input_valid = x.detach().abs().sum(dim=-1).gt(0) | |
| x = self.input_proj(x) | |
| if self.assume_ordered_square: | |
| return self._ordered_square_to_grid(x, coords, input_valid=input_valid, patch_size_lv0=patch_size_lv0) | |
| return self._scatter_to_grid(x, coords, patch_size_lv0=patch_size_lv0, input_valid=input_valid) | |
| def _apply_token_mask(self, x_grid, valid_grid=None, mask_ratio=None): | |
| mask_ratio = self.recon_mask_ratio if mask_ratio is None else mask_ratio | |
| if mask_ratio <= 0: | |
| return x_grid, None | |
| B, C, H, W = x_grid.shape | |
| if valid_grid is None: | |
| valid_tokens = torch.ones(B, H * W, device=x_grid.device, dtype=torch.bool) | |
| else: | |
| valid_tokens = valid_grid.flatten(2).squeeze(1) | |
| mask = (torch.rand(B, H * W, device=x_grid.device) < mask_ratio) & valid_tokens | |
| empty_rows = ~mask.any(dim=1) | |
| if empty_rows.any(): | |
| empty_idx = empty_rows.nonzero(as_tuple=False).flatten() | |
| for b in empty_idx.tolist(): | |
| valid_idx = valid_tokens[b].nonzero(as_tuple=False).flatten() | |
| if valid_idx.numel() > 0: | |
| rand_idx = valid_idx[torch.randint(0, valid_idx.numel(), (1,), device=x_grid.device)] | |
| mask[b, rand_idx] = True | |
| mask_grid = mask.view(B, 1, H, W) | |
| masked_x_grid = torch.where(mask_grid, self.mask_token.to(dtype=x_grid.dtype), x_grid) | |
| return masked_x_grid, mask | |
| def _encode_grid(self, x_grid, coord_grid, valid_grid=None): | |
| if valid_grid is None: | |
| x_grid = x_grid * valid_grid.to(dtype=x_grid.dtype) | |
| output1 = self._conv_norm_active(self.conv1, x_grid) | |
| output2 = self._conv_norm_active(self.conv2, x_grid) | |
| output3 = self._conv_norm_active(self.conv3, x_grid) | |
| output = output1 + output2 + output3 + x_grid | |
| output = output * valid_grid.to(dtype=output.dtype) | |
| output = output.flatten(2).transpose(1, 2).contiguous() | |
| coord_tokens = coord_grid.flatten(2).transpose(1, 2).contiguous() | |
| valid_tokens = valid_grid.flatten(2).squeeze(1) | |
| output = output + self._coord_pos_embed(coord_tokens, valid_tokens=valid_tokens) | |
| output = output * valid_tokens.unsqueeze(-1).to(dtype=output.dtype) | |
| B = output.shape[0] | |
| cls_tokens = self.cls_token.expand(B, -1, -1).to(output.device) | |
| output = torch.cat((cls_tokens, output), dim=1) | |
| cls_valid = torch.ones(B, self.head_num, device=output.device, dtype=torch.bool) | |
| attn_mask = torch.cat((cls_valid, valid_tokens), dim=1) | |
| # output = self.trans_layers(output) | |
| for layer in self.trans_layers: | |
| output = layer(output, mask=attn_mask) | |
| output = output * attn_mask.unsqueeze(-1).to(dtype=output.dtype) | |
| output = self.norm(output) | |
| output_cls = output[:, 0:self.head_num] | |
| output_feats = output[:, self.head_num:] * valid_tokens.unsqueeze(-1).to(dtype=output.dtype) | |
| else: | |
| x_grid = x_grid * valid_grid.to(dtype=x_grid.dtype) | |
| output1 = self._conv_norm_active(self.conv1, x_grid) | |
| output2 = self._conv_norm_active(self.conv2, x_grid) | |
| output3 = self._conv_norm_active(self.conv3, x_grid) | |
| output = output1 + output2 + output3 + x_grid | |
| output = output * valid_grid.to(dtype=output.dtype) | |
| # output4 = self._conv_norm_active(self.conv4, output) | |
| # output5 = self._conv_norm_active(self.conv5, output) | |
| # output6 = self._conv_norm_active(self.conv6, output) | |
| # output = output4 + output5 + output6 + output | |
| # output = output * valid_grid.to(dtype=output.dtype) | |
| # output7 = self._conv_norm_active(self.conv1, output) | |
| # output8 = self._conv_norm_active(self.conv2, output) | |
| # output9 = self._conv_norm_active(self.conv3, output) | |
| # output = output7 + output8 + output9 + output | |
| # output = output * valid_grid.to(dtype=output.dtype) | |
| output = output.flatten(2).transpose(1, 2).contiguous() | |
| coord_tokens = coord_grid.flatten(2).transpose(1, 2).contiguous() | |
| valid_tokens = valid_grid.flatten(2).squeeze(1) | |
| output = output + self._coord_pos_embed(coord_tokens, valid_tokens=valid_tokens) | |
| output = output * valid_tokens.unsqueeze(-1).to(dtype=output.dtype) | |
| B = output.shape[0] | |
| cls_tokens = self.cls_token.expand(B, -1, -1).to(output.device) | |
| output = torch.cat((cls_tokens, output), dim=1) | |
| cls_valid = torch.ones(B, self.head_num, device=output.device, dtype=torch.bool) | |
| attn_mask = torch.cat((cls_valid, valid_tokens), dim=1) | |
| # output = self.trans_layers(output) | |
| for layer in self.trans_layers: | |
| output = layer(output, mask=attn_mask) | |
| output = output * attn_mask.unsqueeze(-1).to(dtype=output.dtype) | |
| output = self.norm(output) | |
| output_cls = output[:, 0:self.head_num] | |
| output_feats = output[:, self.head_num:] * valid_tokens.unsqueeze(-1).to(dtype=output.dtype) | |
| return output_cls, output_feats | |
| def forward( | |
| self, | |
| x, | |
| coords, | |
| patch_size_lv0=None, | |
| mask_ratio=0.0, | |
| return_mask=False, | |
| return_recon_loss=False, | |
| ): | |
| x_grid, coord_grid, valid_grid = self._tokens_to_grid(x, coords, patch_size_lv0=patch_size_lv0) | |
| mask = None | |
| if return_mask or return_recon_loss or mask_ratio > 0: | |
| x_grid, mask = self._apply_token_mask(x_grid, valid_grid=valid_grid, mask_ratio=mask_ratio) | |
| output_cls, output_feats = self._encode_grid(x_grid, coord_grid, valid_grid=valid_grid) | |
| if return_mask: | |
| return output_cls, output_feats, mask | |
| return output_cls, output_feats, output_feats.new_zeros(()) |