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
File size: 21,519 Bytes
8850d81 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 | 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(()) |