| from __future__ import annotations |
|
|
| import torch |
| from torch import nn |
|
|
|
|
| class SelectivePETFusion(nn.Module): |
| """CT-first PET fusion with a learned PET utility gate. |
| |
| The final fused representation is a convex mix between CT+clinical and |
| CT+PET+clinical features. During training, the gate can be supervised by a |
| pseudo-label derived from CT-only versus PET-enabled validation gain. |
| """ |
|
|
| def __init__(self, feature_dim: int = 256, num_heads: int = 4, gate_mode: str = "selective") -> None: |
| super().__init__() |
| if gate_mode not in {"selective", "always", "never"}: |
| raise ValueError(f"Unsupported gate_mode: {gate_mode}") |
| self.gate_mode = gate_mode |
| self.attn = nn.MultiheadAttention(feature_dim, num_heads=num_heads, batch_first=True) |
| self.ct_head = nn.Linear(feature_dim * 2, 1) |
| self.pet_head = nn.Linear(feature_dim * 3, 1) |
| self.utility_head = nn.Sequential( |
| nn.Linear(feature_dim * 3, feature_dim), |
| nn.SiLU(inplace=True), |
| nn.Linear(feature_dim, 1), |
| ) |
|
|
| def forward( |
| self, |
| ct_feat: torch.Tensor, |
| clinical_feat: torch.Tensor, |
| pet_feat: torch.Tensor | None = None, |
| has_pet: torch.Tensor | None = None, |
| ) -> dict[str, torch.Tensor]: |
| ct_context = torch.cat([ct_feat, clinical_feat], dim=-1) |
| ct_logit = self.ct_head(ct_context).squeeze(-1) |
|
|
| if pet_feat is None: |
| zero_pet = torch.zeros_like(ct_feat) |
| pet_feat = zero_pet |
| tokens = torch.stack([ct_feat, pet_feat, clinical_feat], dim=1) |
| attended, _ = self.attn(tokens, tokens, tokens, need_weights=False) |
| fused = attended.reshape(attended.shape[0], -1) |
| pet_logit = self.pet_head(fused).squeeze(-1) |
| utility_logit = self.utility_head(fused).squeeze(-1) |
| utility = torch.sigmoid(utility_logit) |
| if self.gate_mode == "always": |
| utility = torch.ones_like(utility) |
| elif self.gate_mode == "never": |
| utility = torch.zeros_like(utility) |
| if has_pet is not None: |
| utility = utility * has_pet.float().view(-1) |
| fused_logit = ct_logit + utility * (pet_logit - ct_logit) |
| return { |
| "ct_logit": ct_logit, |
| "pet_logit": pet_logit, |
| "pet_utility_logit": utility_logit, |
| "pet_utility": utility, |
| "fused_logit": fused_logit, |
| "fused_features": fused, |
| } |
|
|