"""drawer2 (direction2, 2026-11-17): two new DRAW-ONLY drawer architectures for Pipeline B stage 2 (pure nnU-Net ResEnc-L). New file. Imports cascade2_prompt / cascade2_nnunet read-only (never edits them). Exposed to nnU-Net through the shim src/nnUNet/nnunetv2/training/nnUNetTrainer/nnUNetTrainer_D2Cascade2Prompt2.py. Both trainers inherit the nnUNetTrainer_C2PBallOff recipe unchanged: prompt-only (every GT component prompted, unprompted components ignore), placement-offset + candidate-sized ball prompts (PromptTransformOffset), Kervadec non-empty term (w 0.2), full-scale prompt stem, full LR from epoch 0, D331 warm start, Dataset979 fold c2s2x_detA_ii_x, 20 CONTRA fold-0 patients held out, bank heat only used for the unlabelled-pathology ignore. (A) nnUNetTrainer_C2PBallMS MULTI-SCALE PROMPT. Network input is still [T1, prompt] (stem sees both, as BallOff). In addition the prompt is injected at EVERY encoder stage: the prompt is max- and average-pooled to each stage's resolution (the stage strides, ceil mode) and added to that stage's output features via a 1x1x1 conv (2 -> C_stage, weight and bias ZERO-initialised, so at step 0 the network equals the BallOff/D331-initialised network). Implemented by swapping the ResidualEncoder's class for PromptMSResidualEncoder (forward only) and attaching encoder.prompt_inj (ModuleList). Deep supervision, sliding-window inference and nnUNetPredictor work unchanged (build_network_architecture is overridden, so the predictor builds the same network from the shim). (B) nnUNetTrainer_C2PCrop PER-CANDIDATE CROP drawer. Same ResEnc-L (all D331 weights load: shapes do not depend on the patch), plans patched in __init__ to patch 96^3 at 1 mm, batch CROP_BS. Every training crop is centred on a lesion component (P_COMP 1.0, size-weighted alpha 0.5, floor 0.1 mL, from the existing component table). PromptCropTransform: the component nearest the crop centre is THE target and gets the offset/sized ball prompt; every other lesion in the crop -> ignore (dilated 1 voxel, never into the target). Inference (drawer2_infer.py): for each accepted candidate, a 96^3 crop centred on its heat-weighted centroid in nnU-Net preprocessed space with ONLY that candidate's ball, predict, paste back by max, export to the raw grid with nnU-Net's resampling. """ from __future__ import annotations import copy import sys as _sys from pathlib import Path import numpy as np import torch import torch.nn.functional as F from torch import nn _D2 = str(Path(__file__).resolve().parent) if _D2 not in _sys.path: _sys.path.insert(0, _D2) import cascade2_nnunet as N # noqa: E402 from cascade2_nnunet import _label26, _mf, IGNORE # noqa: E402 from cascade2_prompt import nnUNetTrainer_C2PBallOff, PromptTransformOffset # noqa: E402 from dynamic_network_architectures.building_blocks.residual_encoders import ResidualEncoder # noqa: E402 # ============================================================================================ (A) multi-scale prompt class PromptMSResidualEncoder(ResidualEncoder): """ResidualEncoder whose forward also injects the prompt (input channel PROMPT_CH) into every stage output through self.prompt_inj[s] (1x1x1 conv on [maxpool(prompt), avgpool(prompt)] at the stage resolution). Only forward differs.""" PROMPT_CH = 1 def forward(self, x): p = x[:, self.PROMPT_CH:self.PROMPT_CH + 1] pm = pa = p if self.stem is not None: x = self.stem(x) inj = getattr(self, "prompt_inj", None) ret = [] for i, s in enumerate(self.stages): x = s(x) if inj is not None: st = self.strides[i] st = [st] * (x.ndim - 2) if isinstance(st, int) else list(st) if any(k > 1 for k in st): pm = F.max_pool3d(pm, st, st, ceil_mode=True) pa = F.avg_pool3d(pa, st, st, ceil_mode=True, count_include_pad=False) if tuple(pm.shape[2:]) != tuple(x.shape[2:]): # defensive (odd sizes): exact resolution match pm = F.adaptive_max_pool3d(p, x.shape[2:]); pa = F.adaptive_avg_pool3d(p, x.shape[2:]) x = x + inj[i](torch.cat([pm, pa], 1).to(x.dtype)) ret.append(x) return ret if self.return_skips else ret[-1] def add_prompt_injection(net: nn.Module, n_in: int = 2) -> nn.Module: enc = net.encoder assert type(enc) is ResidualEncoder, f"expected a ResidualEncoder, got {type(enc)}" enc.__class__ = PromptMSResidualEncoder convs = [] for i in range(len(enc.stages)): cv = nn.Conv3d(n_in, int(enc.output_channels[i]), 1, bias=True) nn.init.zeros_(cv.weight); nn.init.zeros_(cv.bias) convs.append(cv) enc.prompt_inj = nn.ModuleList(convs) return net class nnUNetTrainer_C2PBallMS(nnUNetTrainer_C2PBallOff): """(A) BallOff recipe + multi-scale prompt injection at every encoder stage (zero-initialised 1x1x1 convs).""" @staticmethod def build_network_architecture(plans_manager, configuration_manager, num_input_channels, num_output_channels, enable_deep_supervision: bool = True): net = nnUNetTrainer_C2PBallOff.build_network_architecture(plans_manager, configuration_manager, num_input_channels, num_output_channels, enable_deep_supervision) assert num_input_channels == 2, num_input_channels return add_prompt_injection(net) def _warm_start(self): """D331 warm start of everything that exists in D331 (parent logic, strict), then the injection convs (absent from D331) stay zero; they are registered as new parameters (full LR group).""" enc = self._module().encoder inj = enc._modules.pop("prompt_inj") try: super()._warm_start() finally: enc._modules["prompt_inj"] = inj names = [n for n, _ in self._module().named_parameters() if ".prompt_inj." in n] self._new_param_names.update(names) assert all(float(p.abs().sum()) == 0 for n, p in self._module().named_parameters() if ".prompt_inj." in n) self.optimizer, self.lr_scheduler = self.configure_optimizers() self.print_to_log_file(f"C2PBallMS: multi-scale prompt injection, {len(names)} zero-initialised tensors (new, full LR): {names}") # ============================================================================================== (B) per-candidate crop class PromptCropTransform(PromptTransformOffset): """the lesion component nearest the patch centre is the ONLY target (offset/sized ball prompt, fade etc. as in PromptTransformOffset with p_prompt 1); every other lesion component in the crop -> ignore (dilated 1, never into the target). Patch centre = the sampled lesion voxel (component-centred loader; SpatialTransform keeps the centre).""" def apply(self, data_dict, **params): seg = data_dict.get("segmentation") if seg is not None: s0 = seg[0].numpy() les = s0 == 1 if les.any(): lab, n = _label26(les) if n > 1: c = np.array(s0.shape) // 2 k = int(lab[tuple(c)]) if k == 0: idx = np.argwhere(lab > 0) k = int(lab[tuple(idx[np.argmin(((idx - c) ** 2).sum(1))])]) tgt = lab == k other = (lab > 0) & ~tgt ign = (_mf(other.astype(np.uint8), 1, "max") > 0) & ~tgt & (s0 != -1) s0 = s0.copy(); s0[ign] = IGNORE data_dict["segmentation"] = torch.from_numpy(s0).to(seg.dtype)[None] return super().apply(data_dict, **params) class nnUNetTrainer_C2PCrop(nnUNetTrainer_C2PBallOff): """(B) per-candidate crop drawer: 96^3 crops at 1 mm centred on lesion components; target = that lesion only.""" CROP_PATCH = (96, 96, 96) CROP_BS = 10 P_COMP = 1.0 def __init__(self, plans, configuration, fold, dataset_json, device=torch.device("cuda")): plans = copy.deepcopy(plans) cfg = plans["configurations"][configuration] cfg["patch_size"] = list(self.CROP_PATCH); cfg["batch_size"] = int(self.CROP_BS) super().__init__(plans, configuration, fold, dataset_json, device) def _prompt_t(self): return PromptCropTransform(**self.PROMPT_KW) def on_train_start(self): r = super().on_train_start() self.print_to_log_file(f"C2PCrop: patch {self.configuration_manager.patch_size}, batch {self.batch_size}, P_COMP {self.P_COMP}") return r # ---------------------------------------------------------------------------------------------------- smoke classes def _smoke(base): def _init(self, plans, configuration, fold, dataset_json, device=torch.device("cuda")): base.__init__(self, plans, configuration, fold, dataset_json, device); self._smoke() return type(base.__name__ + "_Smoke", (N._C2Smoke, base), {"__init__": _init, "__module__": __name__, "BACKBONE_WARMUP_EPOCHS": 0}) nnUNetTrainer_C2PBallMS_Smoke = _smoke(nnUNetTrainer_C2PBallMS) nnUNetTrainer_C2PCrop_Smoke = _smoke(nnUNetTrainer_C2PCrop) TRAINER_NAMES = sorted(n for n in globals() if n.startswith("nnUNetTrainer_C2P") and n not in ("nnUNetTrainer_C2PBallOff",))