File size: 10,288 Bytes
473c56f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""render2 stage-1 trainers: the cascade2 stage-1 detector (_C2DetBase, unchanged) with the confirmation renderer v1
swapped for renderer v2 (cascade2_render2) on the cg family. NEW module (2026-11-16); cascade2_nnunet.py is imported,
never modified. Exposed through the shim nnUNetTrainer_D2Cascade2R2.py (names start with nnUNetTrainer_C2R2).

RENDERER: render2-B (cascade2_render2.Render2B, user re-scope 2026-11-16): v1 engine at >= v1 breadth + CSF/T1 bug fix +
local-contrast label gating + inserted tiny lesions. Labelling of cg samples (stage 1 only; real CONTRA / G1 untouched):
  * code 251: inserted tiny lesion (visible in this render) -> label 1.
  * v1 decoy codes: the registered 35n-addendum rule (cascade2_render.DECOY_IGNORE_RULE) -> IGNORE where seg == 0;
    flow / sulcal / edge stay 0.
  * v2 bright-appearance codes 20 (pv_lining), 21 (wm_diffuse), 22 (cortex_bright): IGNORE (user 2026-11-16: recall-first,
    bright tissue is never label 0).
  * v2 code 250: a lesion component rendered below visibility (post-acquisition contrast < vis_cnr) -> IGNORE even
    though seg == 1 (the detector is never told that invisible tissue is lesion).
Trainers (fold names as cascade2: c2x_<opt>_f<k>; online cg keys cg_<X>):
  nnUNetTrainer_C2R2DetA_iv   renderer v2 only           (vs nnUNetTrainer_C2DetA_iv)
  nnUNetTrainer_C2R2DetA_ii   G1 + renderer v2 + CONTRA  (vs nnUNetTrainer_C2DetA_ii)
  nnUNetTrainer_C2R2DetA_iii  renderer v2 + CONTRA       (vs nnUNetTrainer_C2DetA_iii)
Env C2_R2_KNOBS="k=v,..." overrides R2Knobs (screen variants; the value is printed to the training log).
"""
from __future__ import annotations
import os, sys, time
from pathlib import Path

import numpy as np
import torch

_D2 = str(Path(__file__).resolve().parent)
if _D2 not in sys.path:
    sys.path.insert(0, _D2)

import cascade2_common as C                                   # noqa: E402
import cascade2_nnunet as N                                   # noqa: E402

LES_IGNORE = 250
INSERTED = 251


class C2R2DataLoader(N.C2DataLoader):
    """C2DataLoader + the v2 code 250 (lesion -> ignore). Identical otherwise (generate_train_batch re-implemented only
    to apply the lesion-ignore codes; every other line follows cascade2_nnunet.C2DataLoader.generate_train_batch)."""

    def generate_train_batch(self):
        from acvl_utils.cropping_and_padding.bounding_boxes import crop_and_pad_nd
        from threadpoolctl import threadpool_limits
        data_all = seg_all = None; keys = []
        if getattr(self, "_thr_pid", None) != os.getpid():
            torch.set_num_threads(1); self._thr_pid = os.getpid()
        with torch.no_grad(), threadpool_limits(limits=1, user_api=None):
            for j in range(self.batch_size):
                t_a = time.time()
                k, centre, force_fg = self.draw(); keys.append(k)
                data, seg, _, props = self._data.load_case(k)
                shape = data.shape[1:]
                if centre is not None:
                    lbs, ubs = self._centre_bbox(shape, centre)
                else:
                    lbs, ubs = self.get_bbox(shape, force_fg, props["class_locations"])
                bbox = [[a, b] for a, b in zip(lbs, ubs)]
                dc = torch.from_numpy(crop_and_pad_nd(data, bbox, 0)).float()
                sc = torch.from_numpy(crop_and_pad_nd(seg, bbox, -1, cast_cropped_to=np.int16)).to(torch.int16)
                if os.environ.get("C2_ZERO_OUTSIDE", "0") == "1":
                    dc[:, sc[0] == -1] = 0
                ov = self.load_override(k, bbox, shape)
                if ov is not None:
                    dc[1] = ov
                t_b = time.time()
                if self.render_hook is not None and C.is_online_cg(k):
                    rng = np.random.default_rng(np.random.randint(1 << 31))
                    fl = self.render_hook(dc[0].numpy(), (sc[0] == 1).numpy(), k, bbox, rng)
                    if isinstance(fl, tuple):
                        fl, negmap = fl
                        if negmap is not None:
                            s0 = sc[0]
                            if self.decoy_codes is not None:
                                ign = np.isin(negmap, self.decoy_codes)
                                if ign.any():
                                    if self.decoy_dilate > 0:
                                        ign = N._mf(ign.astype(np.uint8), self.decoy_dilate, "max") > 0
                                    s0[torch.from_numpy(ign) & (s0 == 0)] = N.IGNORE
                            ins = negmap == INSERTED                     # render2-B inserted tiny lesion -> label 1
                            if ins.any():
                                s0[torch.from_numpy(ins) & (s0 == 0)] = 1
                            li = negmap == LES_IGNORE
                            if li.any():                                   # invisible lesion component -> ignore (+1 voxel)
                                li = N._mf(li.astype(np.uint8), 1, "max") > 0
                                s0[torch.from_numpy(li) & (s0 >= 0)] = N.IGNORE
                    dc[1] = torch.as_tensor(fl, dtype=torch.float32)
                    self._tacc["n_render"] += 1
                t_c = time.time()
                if self.transforms is not None:
                    tr = self.transforms(**{"image": dc, "segmentation": sc})
                    ds, ss = tr["image"], tr["segmentation"]
                else:
                    ds, ss = dc, sc
                self._tick(t_b - t_a, t_c - t_b, time.time() - t_c)
                if data_all is None:
                    data_all = torch.empty((self.batch_size, *ds.shape), dtype=torch.float32)
                data_all[j] = ds
                if isinstance(ss, list):
                    if seg_all is None:
                        seg_all = [torch.empty((self.batch_size, *s.shape), dtype=s.dtype) for s in ss]
                    for i, s in enumerate(ss):
                        seg_all[i][j] = s
                else:
                    if seg_all is None:
                        seg_all = torch.empty((self.batch_size, *ss.shape), dtype=ss.dtype)
                    seg_all[j] = ss
        return {"data": data_all, "target": seg_all, "keys": keys}


class _C2R2DetBase(N._C2DetBase):
    """stage-1 detector with renderer v2 on the cg family (online_dl only)."""
    RENDERER2 = True

    def __init__(self, plans, configuration, fold, dataset_json, device=torch.device("cuda")):
        super().__init__(plans, configuration, fold, dataset_json, device)
        assert self.CG_MODE == "online_dl", "renderer v2 runs in the DA workers only (C2_CG_MODE=online_dl)"

    def _loader(self, ds, patch, final, transforms, train):
        return C2R2DataLoader(ds, self.batch_size, patch, final, self.label_manager, self.oversample_foreground_percent,
                              transforms, groups=self.GROUPS if train else None, comp_table=self._comp_table() if train else None,
                              alpha=self.ALPHA, p_comp=self.P_COMP if train else 0.0, min_vox=self.MIN_VOX, vol_floor=self.VOL_FLOOR,
                              override=self._override_fn(), require_override=self.REQUIRE_OVERRIDE,
                              render_hook=self._render_hook(), timing_log=self._timing_log() if train else None,
                              decoy_codes=self._decoy_codes())

    def _render_hook(self):
        if "cg" not in self.GROUPS:
            return None
        import cascade2_render2 as R2
        self.print_to_log_file(f"C2R2: renderer render2-B (breadth; cascade2_render2.Render2B), knobs {R2.R2BKnobs()}, v1 overrides "
                               f"{R2.B_WIDE}; env C2_R2B_KNOBS={os.environ.get('C2_R2B_KNOBS', '')!r}")
        return R2.make_online_hook2b(return_negmap=True)

    def _decoy_codes(self):
        if "cg" not in self.GROUPS:
            return None
        import cascade2_render as R
        import cascade2_render2 as R2
        codes, src = R.decoy_ignore_codes("confirmgen")
        codes = sorted(set(codes) | set(R2.R2_IGNORE_CODES))       # user 2026-11-16: v2 bright-appearance codes -> IGNORE
        assert not set(codes) & set(R2.R2_LABEL0_CODES), "label-0 codes collide with the ignore rule"
        if not self.DECOY_IGNORE:
            raise RuntimeError("render2 trainers require C2_DECOY_IGNORE=1 (35n-addendum rule for pathology-like decoys)")
        self.print_to_log_file(f"C2R2 labelling: decoy codes {codes} -> ignore where seg == 0 ({src}); v2 codes "
                               f"{sorted(R2.R2_IGNORE_CODES)} also ignore; {sorted(R2.R2_LABEL0_CODES)} label 0; code {LES_IGNORE} (invisible lesion) -> ignore")
        return codes


_GEN = {}
for _d in ("ii", "iii", "iv"):
    _name = f"nnUNetTrainer_C2R2DetA_{_d}"
    _GEN[_name] = type(_name, (_C2R2DetBase,), {"DATA_OPTION": _d, "WARM": "d331", "OVERSAMPLE": True, "__module__": __name__,
                                                "__doc__": f"stage-1 detector, renderer v2, data option {_d}, D331 warm start"})
globals().update(_GEN)


for _d in ("ii", "iv"):
    _base = _GEN[f"nnUNetTrainer_C2R2DetA_{_d}"]
    _name = f"nnUNetTrainer_C2R2DetA_{_d}_Smoke"
    _GEN[_name] = type(_name, (N._C2Smoke, _base), {"__init__": N._mk_smoke_init(_base), "__module__": __name__,
                                                   "BACKBONE_WARMUP_EPOCHS": 0})
    globals()[_name] = _GEN[_name]

# ---- short-schedule PAIRED renderer screens (same D331 init, same schedule; renderer is the only difference). Not
# comparable in absolute terms with the 150-epoch arms; v1 vs v2 contrast only.
for _d in ("iv", "iii"):
    for _ep in (40,):
        _n2 = f"nnUNetTrainer_C2R2DetA_{_d}_e{_ep}"
        _GEN[_n2] = type(_n2, (_GEN[f"nnUNetTrainer_C2R2DetA_{_d}"],), {"EPOCHS": _ep, "__module__": __name__,
                         "__doc__": f"renderer v2, option {_d}, {_ep} epochs (paired short screen)"})
        _n1 = f"nnUNetTrainer_C2R2V1DetA_{_d}_e{_ep}"
        _GEN[_n1] = type(_n1, (N._GEN[f"nnUNetTrainer_C2DetA_{_d}"],), {"EPOCHS": _ep, "__module__": __name__,
                         "__doc__": f"renderer v1 (control), option {_d}, {_ep} epochs (paired short screen)"})
        globals()[_n2] = _GEN[_n2]; globals()[_n1] = _GEN[_n1]

__all__ = sorted(_GEN)