"""Recent CNN-Transformer hybrid baselines, re-implemented compact for OASIS-1. Both are TRAINED ON OUR FOLDS — no published cross-dataset numbers are copied. - HCCTCompact: 3D convolutional stem -> compact conv blocks -> 3D patch tokens -> Transformer encoder -> classification head. After Krishnan et al. 3D HCCT (2024). - VSwinFormerLite: residual depthwise 3D CNN stem + 3D CBAM -> Swin-Tiny 3D stages -> GAP -> head. After the 3D-CNN + Video Swin model (Sci Reports 2025), lite variant. """ from __future__ import annotations import torch import torch.nn as nn # --------------------------- 3D HCCT (compact) --------------------------- class ConvBlock3D(nn.Module): def __init__(self, cin, cout, stride=1): super().__init__() self.net = nn.Sequential( nn.Conv3d(cin, cout, 3, stride=stride, padding=1, bias=False), nn.BatchNorm3d(cout), nn.GELU(), nn.Conv3d(cout, cout, 3, padding=1, bias=False), nn.BatchNorm3d(cout), nn.GELU(), ) def forward(self, x): return self.net(x) class HCCTCompact(nn.Module): def __init__(self, n_classes: int = 3, in_channels: int = 1, embed_dim: int = 256, n_layers: int = 3, n_heads: int = 8, dropout: float = 0.1): super().__init__() self.stem = nn.Sequential( nn.Conv3d(in_channels, 32, 3, stride=2, padding=1, bias=False), nn.BatchNorm3d(32), nn.GELU(), ) self.blocks = nn.Sequential( ConvBlock3D(32, 64, stride=2), ConvBlock3D(64, 128, stride=2), ConvBlock3D(128, embed_dim, stride=2), ) self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) nn.init.trunc_normal_(self.cls_token, std=0.02) self.pos_drop = nn.Dropout(dropout) layer = nn.TransformerEncoderLayer( d_model=embed_dim, nhead=n_heads, dim_feedforward=embed_dim * 4, dropout=dropout, batch_first=True, activation="gelu", norm_first=True, ) self.transformer = nn.TransformerEncoder(layer, num_layers=n_layers) self.norm = nn.LayerNorm(embed_dim) self.head = nn.Linear(embed_dim, n_classes) def forward(self, vol: torch.Tensor, tab: torch.Tensor | None = None) -> torch.Tensor: x = self.blocks(self.stem(vol)) # (B, C, d, h, w) B, C = x.shape[:2] tokens = x.flatten(2).transpose(1, 2) # (B, N, C) cls = self.cls_token.expand(B, -1, -1) seq = self.pos_drop(torch.cat([cls, tokens], dim=1)) seq = self.transformer(seq) return self.head(self.norm(seq[:, 0])) # --------------------- 3D-CNN-VSwinFormer (lite) --------------------- class CBAM3D(nn.Module): """3D convolutional block attention (channel + spatial).""" def __init__(self, channels, reduction=8): super().__init__() self.mlp = nn.Sequential( nn.Linear(channels, channels // reduction), nn.ReLU(inplace=True), nn.Linear(channels // reduction, channels), ) self.spatial = nn.Conv3d(2, 1, 7, padding=3, bias=False) def forward(self, x): b, c = x.shape[:2] avg = self.mlp(x.mean(dim=(2, 3, 4))) mx = self.mlp(x.amax(dim=(2, 3, 4))) ca = torch.sigmoid(avg + mx).view(b, c, 1, 1, 1) x = x * ca sa = torch.cat([x.mean(1, keepdim=True), x.amax(1, keepdim=True)], dim=1) x = x * torch.sigmoid(self.spatial(sa)) return x class ResDepthwise3D(nn.Module): def __init__(self, cin, cout, stride=1): super().__init__() self.dw = nn.Conv3d(cin, cin, 3, stride=stride, padding=1, groups=cin, bias=False) self.pw = nn.Conv3d(cin, cout, 1, bias=False) self.bn = nn.BatchNorm3d(cout) self.act = nn.GELU() self.proj = (nn.Conv3d(cin, cout, 1, stride=stride, bias=False) if (cin != cout or stride != 1) else nn.Identity()) def forward(self, x): out = self.act(self.bn(self.pw(self.dw(x)))) return out + self.proj(x) class VSwinFormerLite(nn.Module): """Residual depthwise CNN stem + CBAM, then a MONAI 3D Swin encoder, GAP + head.""" def __init__(self, n_classes: int = 3, in_channels: int = 1, img_size=(96, 112, 112)): super().__init__() self.stem = nn.Sequential( nn.Conv3d(in_channels, 32, 3, stride=2, padding=1, bias=False), nn.BatchNorm3d(32), nn.GELU(), ResDepthwise3D(32, 48), ResDepthwise3D(48, 48), CBAM3D(48), ) from monai.networks.nets.swin_unetr import SwinTransformer from monai.utils import ensure_tuple_rep self.swin = SwinTransformer( in_chans=48, embed_dim=48, window_size=ensure_tuple_rep(7, 3), patch_size=ensure_tuple_rep(2, 3), depths=(2, 2, 2, 2), num_heads=(3, 6, 12, 24), spatial_dims=3, ) self.norm = nn.LayerNorm(48 * 16) self.head = nn.Linear(48 * 16, n_classes) def forward(self, vol: torch.Tensor, tab: torch.Tensor | None = None) -> torch.Tensor: x = self.stem(vol) feats = self.swin(x)[-1] pooled = feats.flatten(2).mean(-1) return self.head(self.norm(pooled))