"""Clinical/SNV/CNV shared-BERT encoding, masked gated fusion, OS/PFS anchors.""" import math import random import torch from torch import nn from torch.nn import functional as F def _value(x): return x.item() if isinstance(x, torch.Tensor) and x.numel() == 1 else x def _missing(x): x = _value(x) return (x is None or isinstance(x, str) and x.strip().lower() in {'', '-1', 'unknown', 'nan', 'none'} or isinstance(x, (int, float)) and (x == -1 or not math.isfinite(x))) def build_texts(cancer_type, clinical, priors, drop_fields=(), probabilities=None): """Return three text batches and six-clinical/two-genomic availability flags.""" aliases = {'mutation': 'snv', 'gender': 'sex', 'diagnosis age': 'age', 'tumor stage': 'stage'} if isinstance(drop_fields, str): drop_fields = [drop_fields] dropped = {aliases.get(k.lower(), k.lower()) for k in drop_fields} if not dropped <= {'age', 'sex', 'stage', 'grade', 'subtype', 'snv', 'cnv'}: raise ValueError('drop_fields must use age, sex, stage, grade, subtype, snv, cnv; cancer type is protected.') if not len(cancer_type) == len(clinical) == len(priors) or not len(cancer_type): raise ValueError('Input batches must have the same nonzero length.') texts = [[], [], []] availability = [] for cancer, c, p in zip(cancer_type, clinical, priors): fields = [('cancer type', cancer), ('age', c.get('diagnosis age', c.get('age', -1))), ('sex', c.get('gender', c.get('sex', -1))), ('stage', c.get('tumor stage', c.get('stage', -1))), ('grade', p.get('grade', -1)), ('subtype', p.get('subtype', -1)), ('snv', p.get('mutation', -1)), ('cnv', p.get('cnv', -1))] parts, flags = [], [] for name, raw in fields: value = _value(raw) hidden = name in dropped or (name != 'cancer type' and probabilities is not None and random.random() < probabilities.get(name, probabilities['other'])) available = not hidden and not _missing(value) flags.append(available) if name in {'snv', 'cnv'}: label = 'Driver mutation' if name == 'snv' else 'Driver CNV' if not available: text = f'{label} information: unknown.' elif not isinstance(value, list) or any(not isinstance(g, str) or not g.strip() for g in value): raise ValueError(f'{name} must be a gene list or a missing value.') elif value: text = f"{label} genes: {', '.join(sorted(set(g.strip() for g in value)))}." else: text = ('No qualifying driver mutations identified.' if name == 'snv' else 'No qualifying driver CNVs identified.') texts[1 if name == 'snv' else 2].append(text) else: parts.append(f"{name}: {value if available else 'unknown'}") texts[0].append(' | '.join(parts)) availability.append(flags) return texts, availability class AnchoredRiskHead(nn.Module): def __init__(self, feat_dim: int, num_prototypes: int = 8, temperature: float = 0.1, normalize: bool = True, learnable_temperature: bool = True, init_risk_gap: float = 0.5, min_gap: float = 1e-2, usage_ema_decay: float = 0.99): super().__init__() self.feat_dim = feat_dim self.num_prototypes = num_prototypes self.normalize = normalize self.min_gap = min_gap self.usage_ema_decay = usage_ema_decay # ---- Prototype feature vectors (D, N) ---- self.prototypes = nn.Parameter(torch.randn(feat_dim, num_prototypes) * 0.02) # ---- Anchor risk values: r0 + cumsum(softplus(gaps)) ---- # 保证: 严格有序; 每个相邻间距 >= min_gap; 总跨度 >= (N-1)*min_gap self.r0 = nn.Parameter(torch.zeros(1)) # 用 inverse softplus 让初始 softplus(gaps_logits) ≈ init_risk_gap init_gap_logit = torch.log(torch.expm1(torch.tensor(init_risk_gap - min_gap))) self.gaps_logits = nn.Parameter(torch.full((num_prototypes - 1,), init_gap_logit.item())) # ---- Temperature ---- if learnable_temperature: # 用 log_tau 保证正 self.log_tau = nn.Parameter(torch.tensor(float(torch.log(torch.tensor(temperature))))) else: self.register_buffer('log_tau', torch.tensor(float(torch.log(torch.tensor(temperature))))) # ---- Usage EMA buffer for dead-anchor detection ---- self.register_buffer('usage_ema', torch.full((num_prototypes,), 1.0 / num_prototypes)) # --------------------------- properties --------------------------- @property def temperature(self): return self.log_tau.exp() def get_anchor_risks(self): gaps = F.softplus(self.gaps_logits) + self.min_gap # (N-1,), >0 cum = torch.cumsum(gaps, dim=0) # (N-1,) anchors = torch.cat([self.r0, self.r0 + cum], dim=0) # (N,) return anchors # 严格递增 # --------------------------- forward ------------------------------ def forward(self, z, update_usage: bool = True): """ z: (B, D) returns: risk (B,) soft_w (B, N) soft assignment over anchors extra dict with anchor_risks, etc. """ # 1) similarity to prototypes if self.normalize: z_n = F.normalize(z, dim=-1) p_n = F.normalize(self.prototypes, dim=0) sim = z_n @ p_n # (B, N), cosine in [-1,1] else: sim = z @ self.prototypes # (B, N) # 2) soft assignment (temperature-scaled softmax) soft_w = F.softmax(sim / self.temperature.clamp_min(1e-4), dim=-1) # (B, N) # 3) risk = weighted sum over ordered anchors anchors = self.get_anchor_risks() # (N,) risk = (soft_w * anchors.unsqueeze(0)).sum(dim=-1) # (B,) # 4) update usage EMA (training only, with no_grad) if update_usage and self.training: with torch.no_grad(): batch_usage = soft_w.mean(dim=0) # (N,) self.usage_ema.mul_(self.usage_ema_decay).add_( batch_usage * (1.0 - self.usage_ema_decay) ) extra = { 'anchor_risks': anchors, 'sim' : sim, } return risk, soft_w, extra # --------------------------- regularizers ------------------------- def usage_loss(self, dead_threshold_ratio: float = 0.5): """ 惩罚"死锚点"——usage_ema 远低于均匀使用率 1/N 的那些 anchor. 返回的是非负标量, 没死锚点时 ≈ 0. """ N = self.num_prototypes target = dead_threshold_ratio / N gap = (target - self.usage_ema).clamp_min(0.0) # (N,) 死的越狠越大 return gap.sum() def balance_loss(self, soft_w): """ Batch-level balance: KL( mean_q || uniform ). 只用当前 batch 的 soft_w (B, N), 比 EMA 响应更快. """ q_bar = soft_w.mean(dim=0).clamp_min(1e-8) # (N,) uniform = torch.full_like(q_bar, 1.0 / q_bar.numel()) # KL(q_bar || uniform) = sum q_bar * log(q_bar * N) return (q_bar * (q_bar.log() - uniform.log())).sum() class MOSAICAnchor(nn.Module): def __init__(self, keep_model, keep_tokenizer, feats_dim, trans_num, task_id, randomdrop, device, proj_hidden_dim=64, proj_out_dim=None, num_prototypes_os=8, num_prototypes_pfs=8, proto_temperature=0.1, proto_normalize=True, proto_learnable_tau=True, init_risk_gap=0.5, min_risk_gap=1e-2, max_lengths=(128, 256, 256), p_snv_mask=0.25, p_cnv_mask=0.25, p_other_mask=0.1): super().__init__() self.text_model = getattr(keep_model, 'text', keep_model) self.tokenizer = keep_tokenizer self.device, self.trans_num, self.task_id = device, trans_num, task_id self.feats_dim, self.randomdrop = feats_dim, randomdrop self.proj_out_dim = dim = proj_out_dim or feats_dim self.max_lengths = max_lengths self.mask_probs = {'snv': p_snv_mask, 'cnv': p_cnv_mask, 'other': p_other_mask} if any(not 0 <= p <= 1 for p in self.mask_probs.values()) or len(max_lengths) != 3: raise ValueError('Invalid masking probabilities or max_lengths.') self.branch_proj = nn.ModuleList([ nn.Sequential(nn.Linear(feats_dim, dim), nn.GELU(), nn.LayerNorm(dim)) for _ in range(3)]) self.gate = nn.Sequential(nn.Linear(3 * dim + 8, proj_hidden_dim or 64), nn.GELU(), nn.Linear(proj_hidden_dim or 64, 3)) self.fusion_norm = nn.LayerNorm(dim) args = dict(feat_dim=dim, temperature=proto_temperature, normalize=proto_normalize, learnable_temperature=proto_learnable_tau, init_risk_gap=init_risk_gap, min_gap=min_risk_gap) self.risk_head_os = AnchoredRiskHead(num_prototypes=num_prototypes_os, **args) self.risk_head_pfs = AnchoredRiskHead(num_prototypes=num_prototypes_pfs, **args) def encode_patient(self, cancer_type, clinical, priors, drop_fields=(), probabilities=None): texts, flags = build_texts(cancer_type, clinical, priors, drop_fields, probabilities) device = next(self.parameters()).device fields = torch.tensor(flags, device=device, dtype=torch.bool) available = torch.stack([torch.ones_like(fields[:, 0]), fields[:, 6], fields[:, 7]], dim=1) embeddings = [] for i, text in enumerate(texts): tokens = self.tokenizer(text, max_length=self.max_lengths[i], padding=True, truncation=True, return_tensors='pt').to(device) z = self.text_model(**tokens).pooler_output embeddings.append(self.branch_proj[i](z)) h = torch.stack(embeddings, dim=1) h = h.masked_fill(~available.unsqueeze(-1), 0) logits = self.gate(torch.cat([h.flatten(1), fields.to(h.dtype)], dim=1)) weights = logits.masked_fill(~available, float('-inf')).softmax(-1) z = self.fusion_norm((weights.unsqueeze(-1) * h).sum(1)) return z, weights, available def forward(self, cancer_type, surv_prior, slide_clinical, project_id=None, gene_des=None, mode='train', drop_fields=()): if mode not in {'train', 'val', 'test'}: raise ValueError('mode must be train, val, or test.') full = self.encode_patient(cancer_type, slide_clinical, surv_prior, drop_fields) augment = self.training and mode == 'train' and self.randomdrop masked = (self.encode_patient(cancer_type, slide_clinical, surv_prior, drop_fields, self.mask_probs) if augment else full) outputs = {} for view, (z, gates, available) in [('full', full), ('masked', masked)]: outputs[f'shared_{view}_feats'] = z outputs[f'{view}_gate_weights'] = gates outputs[f'{view}_modality_available'] = available for endpoint in ['os', 'pfs']: head = getattr(self, f'risk_head_{endpoint}') risk, weights, extra = head(z, update_usage=(self.training and mode == 'train' and view == 'full')) outputs[f'{endpoint}_{view}_feats'] = z outputs[f'{endpoint}_{view}_risk'] = risk outputs[f'{endpoint}_{view}_proto_w'] = weights outputs[f'{endpoint}_anchor_risks'] = extra['anchor_risks'] return outputs