from __future__ import annotations import torch from torch import nn class ConvBlock3d(nn.Module): def __init__(self, in_channels: int, out_channels: int, stride: int = 1) -> None: super().__init__() self.block = nn.Sequential( nn.Conv3d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False), nn.InstanceNorm3d(out_channels, affine=True), nn.SiLU(inplace=True), nn.Conv3d(out_channels, out_channels, kernel_size=3, padding=1, bias=False), nn.InstanceNorm3d(out_channels, affine=True), ) self.skip = ( nn.Identity() if in_channels == out_channels and stride == 1 else nn.Conv3d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False) ) self.act = nn.SiLU(inplace=True) def forward(self, x: torch.Tensor) -> torch.Tensor: return self.act(self.block(x) + self.skip(x)) class VolumeEncoder(nn.Module): def __init__(self, in_channels: int = 1, feature_dim: int = 256, channels: tuple[int, ...] = (32, 64, 128, 256)) -> None: super().__init__() layers = [] prev = in_channels for i, ch in enumerate(channels): layers.append(ConvBlock3d(prev, ch, stride=1 if i == 0 else 2)) prev = ch self.backbone = nn.Sequential(*layers) self.pool = nn.AdaptiveAvgPool3d(1) self.proj = nn.Linear(channels[-1], feature_dim) def forward(self, x: torch.Tensor) -> torch.Tensor: feat = self.backbone(x) pooled = self.pool(feat).flatten(1) return self.proj(pooled) class MLP(nn.Module): def __init__(self, in_dim: int, hidden_dim: int, out_dim: int, dropout: float = 0.1) -> None: super().__init__() if in_dim == 0: self.net = nn.Identity() else: self.net = nn.Sequential( nn.Linear(in_dim, hidden_dim), nn.LayerNorm(hidden_dim), nn.SiLU(inplace=True), nn.Dropout(dropout), nn.Linear(hidden_dim, out_dim), ) def forward(self, x: torch.Tensor) -> torch.Tensor: return self.net(x)