"""2D / 2.5D CNN baselines (timm backbones). - ResNet50Center: single center axial slice (B, 3, H, W). - DenseNet2p5D: 9 axial slices encoded by a shared backbone, mean-pooled (2.5D). Both accept the same (B, T, 3, H, W) slice tensor as the rest of the zoo; T is sliced/agg internally so the training loop is uniform. """ from __future__ import annotations import timm import torch import torch.nn as nn class ResNet50Center(nn.Module): """Single-slice baseline: uses the center slice of the axial stack.""" def __init__(self, n_classes: int = 3, pretrained: bool = True, backbone: str = "resnet50", center_index: int | None = None): super().__init__() self.backbone = timm.create_model(backbone, pretrained=pretrained, num_classes=n_classes, in_chans=3) self.center_index = center_index def forward(self, slices: torch.Tensor, tab: torch.Tensor | None = None) -> torch.Tensor: # slices: (B, T, 3, H, W); pick center of the (first) plane's stack T = slices.shape[1] idx = self.center_index if self.center_index is not None else T // 2 return self.backbone(slices[:, idx]) class DenseNet2p5D(nn.Module): """2.5D baseline: shared DenseNet over N slices, mean-pool logits.""" def __init__(self, n_classes: int = 3, pretrained: bool = True, backbone: str = "densenet121", n_slices: int = 9): super().__init__() self.encoder = timm.create_model(backbone, pretrained=pretrained, num_classes=0, in_chans=3) self.head = nn.Linear(self.encoder.num_features, n_classes) self.n_slices = n_slices def forward(self, slices: torch.Tensor, tab: torch.Tensor | None = None) -> torch.Tensor: # use first n_slices tokens (axial plane) -> mean-pool features x = slices[:, : self.n_slices] # (B, S, 3, H, W) B, S, C, H, W = x.shape feats = self.encoder(x.reshape(B * S, C, H, W)).reshape(B, S, -1) return self.head(feats.mean(dim=1)) class DenseNetLateFusion(nn.Module): """Multimodal baseline B9: DenseNet 2.5D image embedding + metadata MLP, concat.""" def __init__(self, n_classes: int = 3, n_tab_features: int = 7, pretrained: bool = True, backbone: str = "densenet121", n_slices: int = 9, dropout: float = 0.3): super().__init__() self.encoder = timm.create_model(backbone, pretrained=pretrained, num_classes=0, in_chans=3) img_dim = self.encoder.num_features self.n_slices = n_slices self.tab = nn.Sequential( nn.Linear(n_tab_features, 64), nn.GELU(), nn.Dropout(dropout), nn.Linear(64, 128), nn.LayerNorm(128), ) self.head = nn.Sequential( nn.Linear(img_dim + 128, 256), nn.GELU(), nn.Dropout(dropout), nn.Linear(256, n_classes), ) def forward(self, slices: torch.Tensor, tab: torch.Tensor) -> torch.Tensor: x = slices[:, : self.n_slices] B, S, C, H, W = x.shape img = self.encoder(x.reshape(B * S, C, H, W)).reshape(B, S, -1).mean(dim=1) return self.head(torch.cat([img, self.tab(tab)], dim=1))