File size: 28,846 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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
#!/usr/bin/env python
"""classifier4/B: train the INDEPENDENT T1 EVIDENCE network (B_LOG.md §2 design) from scratch on D331's training data.

Network: nnU-Net ResidualEncoderUNet (dynamic_network_architectures; ResEnc stage layout 32-64-128-256-320-320, blocks 1-3-4-6-6-6,
deep supervision), RANDOM init (never D331 weights). Input = T1 only (D331-preprocessed z-score, zero outside brain), 1 mm.
Data = D331 fold-0 TRAIN keys (1,086; c4b_common.train_keys), held in RAM (fp16).
Recipe (each item attacks a cause of D331's blindness, B_LOG §1):
  * LESION-BALANCED sampling: p_les of patches are centred on a GT lesion picked uniformly over size bins (<0.1 / 0.1-1 / 1-5 / 5-30 /
    >30 mL) then uniformly within the bin (D331: nnU-Net centres 33 % of patches on a voxel drawn uniformly from the foreground, so
    tiny lesions are almost never centred); the rest are random brain locations.
  * SYNTHETIC tiny / faint lesions painted into the real T1 anatomy on the GPU: volume log-uniform 3-5000 vox (0.003-5 mL), irregular
    ellipsoids with soft partial-volume rims, placed in WM-like (deep / periventricular), GM-like (cortical / juxtacortical) or any
    brain tissue (never on a GT lesion), contrast relative to local tissue log-uniform 0.04-1.2 of the tissue-to-CSF gap (down to
    near-invisible), 10 % T1-bright; additive (keeps the tissue texture) or blended; labelled positive.
  * LESION-WISE loss: CE (deep supervision, max-pooled targets so tiny lesions survive at coarse scales) + batch soft Dice + BLOB Dice
    (per-instance Dice in the instance's neighbourhood, other instances ignored: every lesion weighs the same) + per-lesion
    MAX-EVIDENCE term (softplus(-max fg-margin inside each instance)) balanced by a HARD-NEGATIVE term (top-k background margins).
  * EXTREME domain randomisation on the GPU (renderer philosophy, breadth not realism): GIN random conv, gamma, bias field, thick
    slices (resolution randomisation), blur, isotropic low-res, noise; affine (rotation / scale) + flips.
Checkpoint every --save_every iters (requeue-safe; RNG states saved).
  c4b_train.py --tag b1 [--iters 30000] [--patch 128] [--bs 3] [--smoke]
"""
from __future__ import annotations
import argparse, math, os, queue, sys, threading, time, zlib
from pathlib import Path
import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parent))
import c4b_common as Q   # noqa: E402
import torch
import torch.nn.functional as F

BINS = (0, 100, 1000, 5000, 30000, 10 ** 9)


def log(*a):
    print(time.strftime("%H:%M:%S"), *a, flush=True)


# ---------------------------------------------------------------------------------------------------------------- network
def make_net(deep_supervision=True, ncls=2):
    from dynamic_network_architectures.architectures.unet import ResidualEncoderUNet
    return ResidualEncoderUNet(
        input_channels=1, n_stages=6, features_per_stage=[32, 64, 128, 256, 320, 320], conv_op=torch.nn.Conv3d,
        kernel_sizes=[[3, 3, 3]] * 6, strides=[[1, 1, 1]] + [[2, 2, 2]] * 5, n_blocks_per_stage=[1, 3, 4, 6, 6, 6], num_classes=ncls,
        n_conv_per_stage_decoder=[1] * 5, conv_bias=True, norm_op=torch.nn.InstanceNorm3d, norm_op_kwargs={"eps": 1e-5, "affine": True},
        dropout_op=None, dropout_op_kwargs=None, nonlin=torch.nn.LeakyReLU, nonlin_kwargs={"inplace": True},
        deep_supervision=deep_supervision)


# ---------------------------------------------------------------------------------------------------------------- data
class Data:
    def __init__(self, keys, index, bin_w=None, faint_w=0.0):
        t0 = time.time()
        self.X, self.S, self.bb = [], [], []
        for i, k in enumerate(keys):
            x = Q.load_b2(Q.D331P / f"{k}.b2nd", 0); s = Q.load_b2(Q.D331P / f"{k}_seg.b2nd", 0).astype(np.int8)
            br = s != -1
            x = np.where(br, x, 0).astype(np.float16)
            nz = (np.argwhere(br[::3, ::3, ::3]) * 3).astype(np.int16)
            self.X.append(x); self.S.append(s); self.bb.append(nz)
            if i % 100 == 0:
                log("load", i, len(keys), f"{time.time() - t0:.0f}s")
        self.keys = keys; kpos = {k: i for i, k in enumerate(keys)}
        les = index[index["key"].isin(kpos)]
        self.les_case = les["key"].map(kpos).to_numpy(); self.les_vox = les["vox"].to_numpy()
        self.les_xyz = [np.array(v) for v in les["vox_xyz"]]
        self.bin_members = [np.nonzero((self.les_vox >= lo) & (self.les_vox < hi))[0] for lo, hi in zip(BINS[:-1], BINS[1:])]
        bw = bin_w or [1.0] * len(self.bin_members)
        keep = [i for i, m in enumerate(self.bin_members) if len(m)]
        self.bin_p = np.array([bw[i] for i in keep], float); self.bin_p /= self.bin_p.sum()
        self.bin_members = [self.bin_members[i] for i in keep]
        ct = les["c_t1"].fillna(-9).to_numpy()
        lw = 1.0 + faint_w * (ct > -0.5)                       # faint real lesions (c_t1 > -0.5 whole-brain z; ~30 %) oversampled
        self.bin_lw = [lw[m] / lw[m].sum() for m in self.bin_members]
        log("data ready", len(keys), "lesions", len(les), "bins", [len(m) for m in self.bin_members], f"{time.time() - t0:.0f}s")

    def patch(self, rng, P, p_les):
        if rng.random() < p_les:
            bi_ = rng.choice(len(self.bin_members), p=self.bin_p)
            mem = self.bin_members[bi_]
            j = mem[rng.choice(len(mem), p=self.bin_lw[bi_])]; ci = self.les_case[j]
            c = self.les_xyz[j][rng.integers(len(self.les_xyz[j]))] + rng.integers(-(P // 2 - 12), P // 2 - 12 + 1, 3)
        else:
            ci = rng.integers(len(self.X)); bb = self.bb[ci]; c = bb[rng.integers(len(bb))]
        x, s = self.X[ci], self.S[ci]
        lo = np.array(c) - P // 2; hi = lo + P
        xo = np.zeros((P,) * 3, np.float16); so = np.full((P,) * 3, -1, np.int8)
        slo = np.maximum(lo, 0); shi = np.minimum(hi, x.shape)
        dst = tuple(slice(a - l, b - l) for a, b, l in zip(slo, shi, lo)); src = tuple(slice(a, b) for a, b in zip(slo, shi))
        xo[dst] = x[src]; so[dst] = s[src]
        return xo, so


def instances(seg):
    import cc3d
    les = (seg == 1).astype(np.uint8)
    if not les.any():
        return np.zeros(seg.shape, np.int16), 0
    L, n = cc3d.connected_components(les, connectivity=26, return_N=True)
    return L.astype(np.int16), int(n)


def producer(data, q, seed, P, bs, p_les, stop):
    rng = np.random.default_rng(seed)
    while not stop.is_set():
        xs, ss, ins, ns = [], [], [], []
        for _ in range(bs):
            x, s = data.patch(rng, P, p_les)
            L, n = instances(s)
            xs.append(x); ss.append(s); ins.append(L); ns.append(n)
        item = (np.stack(xs), np.stack(ss), np.stack(ins), ns)
        while not stop.is_set():
            try:
                q.put(item, timeout=1); break
            except queue.Full:
                pass


# ---------------------------------------------------------------------------------------------------------------- GPU augmentation
def u(gen, lo, hi, dev):
    return float(torch.empty(1, device=dev).uniform_(lo, hi, generator=gen))


def rand(gen, dev):
    return float(torch.rand(1, device=dev, generator=gen))


def spatial(x, br, ins, gen):
    """affine rotation / scale (p 0.35 each) + flips. x (B,1,P,P,P) float; br (B,1,..) float; ins (B,1,..) float (instance ids)."""
    B = x.shape[0]; dev = x.device
    thetas = []
    for b in range(B):
        R = torch.eye(3, device=dev)
        if rand(gen, dev) < 0.35:
            for ax in range(3):
                a = u(gen, -0.35, 0.35, dev); c, s = math.cos(a), math.sin(a)
                i, j = [k for k in range(3) if k != ax]
                M = torch.eye(3, device=dev); M[i, i] = c; M[j, j] = c; M[i, j] = -s; M[j, i] = s
                R = R @ M
        if rand(gen, dev) < 0.35:
            R = R * math.exp(u(gen, math.log(0.8), math.log(1.25), dev))
        for ax in range(3):
            if rand(gen, dev) < 0.5:
                R[:, ax] = -R[:, ax]
        thetas.append(torch.cat([R, torch.zeros(3, 1, device=dev)], 1))
    th = torch.stack(thetas)
    grid = F.affine_grid(th, x.shape, align_corners=False)
    x = F.grid_sample(x, grid, mode="bilinear", padding_mode="zeros", align_corners=False)
    br = F.grid_sample(br, grid, mode="bilinear", padding_mode="zeros", align_corners=False) > 0.5
    ins = F.grid_sample(ins, grid, mode="nearest", padding_mode="zeros", align_corners=False)
    return x, br, ins


def paint(x, br, ins, nreal, gen, a):
    """synthetic tiny / faint lesions. x (B,P,P,P) z-T1, br bool, ins float instance map (real ids 1..nreal[b]). In place."""
    B, P = x.shape[0], x.shape[1]; dev = x.device
    nsyn = []
    edges = torch.zeros_like(br)
    for b in range(B):
        k = 0
        if a.w_csf > 0 or a.mimic:
            bv0 = x[b][br[b]]
            if bv0.numel() > 5000:
                q = torch.quantile(bv0[torch.randint(bv0.numel(), (20000,), device=dev, generator=gen)].float(), torch.tensor([0.03, 0.25], device=dev))
                dark = (x[b] < q[0] + 0.5 * (q[1] - q[0])) & br[b]
                edges[b] = (F.max_pool3d(dark.float()[None, None], 5, 1, 2)[0, 0] > 0) & br[b]
        if rand(gen, dev) < a.p_syn:
            n = int(torch.randint(1, a.max_syn + 1, (1,), device=dev, generator=gen))
            xb = x[b]; bb = br[b]
            bv = xb[bb]
            if bv.numel() < 5000:
                nsyn.append(0); continue
            qs = torch.quantile(bv[torch.randint(bv.numel(), (20000,), device=dev, generator=gen)].float(),
                                torch.tensor([0.03, 0.25, 0.6], device=dev))
            csf, q25, q60 = qs.tolist()
            les_d = F.max_pool3d((ins[b] > 0).float()[None, None], 9, 1, 4)[0, 0] > 0
            csf_near = F.max_pool3d(((xb < csf + 0.5 * (q25 - csf)) & bb).float()[None, None], 2 * a.csf_gap + 1, 1, a.csf_gap)[0, 0] > 0
            for _ in range(n):
                V = math.exp(u(gen, math.log(3), math.log(5000), dev))
                r0 = (3 * V / (4 * math.pi)) ** (1 / 3)
                ar = torch.exp(torch.empty(3, device=dev).uniform_(-0.7, 0.7, generator=gen)); ar = ar / ar.prod() ** (1 / 3)
                rad = r0 * ar
                half = int(math.ceil(float(rad.max()) * 1.6 + 3))
                if 2 * half + 1 >= P - 8:
                    continue
                t = rand(gen, dev)
                rule = rand(gen, dev) < a.p_rule                                  # never-CSF-dark rule applied with prob p_rule
                cand = bb & ~les_d & ~(csf_near if (a.csf_gap > 0 and rule) else torch.zeros_like(bb))
                if t < 0.5:
                    cand = cand & (xb > q60)
                elif t < 0.85:
                    cand = cand & (xb > q25) & (xb <= q60)
                m = cand[half + 2:P - half - 2, half + 2:P - half - 2, half + 2:P - half - 2]
                idx = torch.nonzero(m)
                if len(idx) == 0:
                    continue
                c = idx[int(torch.randint(len(idx), (1,), device=dev, generator=gen))] + half + 2
                sl = tuple(slice(int(ci) - half, int(ci) + half + 1) for ci in c)
                S = 2 * half + 1
                g = torch.stack(torch.meshgrid(*[torch.arange(S, device=dev, dtype=torch.float32) - half] * 3, indexing="ij"), 0)
                Rm = torch.linalg.qr(torch.randn(3, 3, device=dev, generator=gen))[0]
                gr = torch.einsum("ij,jxyz->ixyz", Rm, g)
                d = torch.sqrt(((gr / rad.view(3, 1, 1, 1)) ** 2).sum(0))
                nz = F.interpolate(torch.randn(1, 1, 4, 4, 4, device=dev, generator=gen), size=(S,) * 3, mode="trilinear",
                                   align_corners=True)[0, 0]
                d = d + nz * u(gen, 0.0, 0.4, dev)
                w = u(gen, 0.05, 0.3, dev) * max(1.0, 2.0 / max(r0, 0.5))
                alpha = torch.sigmoid((1 - d) / w) * bb[sl] * (~les_d[sl])
                lab = alpha > 0.5
                if int(lab.sum()) < 3:
                    continue
                loc = xb[sl]; tis = loc[bb[sl] & ~lab]
                T = float(tis.median()) if tis.numel() > 10 else float(q60)
                gap = max(T - csf, 0.8)
                cr = math.exp(u(gen, math.log(a.c_lo), math.log(1.2), dev))
                if t >= 0.5 and rule:
                    cr = min(cr, a.gm_cmax)                                         # cortical / any-tissue lesions never CSF-dark
                shift = -cr * gap if rand(gen, dev) > 0.1 else cr * 0.6 * gap
                if shift < 0 and r0 >= 1.5 and rand(gen, dev) < 0.3:              # cavitation: CSF-dark core + milder gliotic rim
                    cf = u(gen, 0.4, 0.8, dev)
                    core = torch.sigmoid((cf - d) / (w * cf))
                    shift = shift + core * (-(u(gen, 0.7, 1.05, dev) * gap) - shift)
                tex = torch.randn((S,) * 3, device=dev, generator=gen) * u(gen, 0.0, 0.25, dev) * gap * min(1.0, cr * 3)
                if rand(gen, dev) < 0.5:
                    new = loc + alpha * (shift + tex)                                       # additive: keeps tissue texture
                else:
                    new = loc + alpha * ((T + shift + tex) - loc)                           # blended towards the target
                x[b][sl] = new.to(x.dtype)
                k += 1
                ins[b][sl] = torch.where(lab, torch.full_like(ins[b][sl], float(nreal[b] + k)), ins[b][sl])
                les_d[sl] = les_d[sl] | (F.max_pool3d(lab.float()[None, None], 9, 1, 4)[0, 0] > 0)
        nsyn.append(k)
    mim = torch.zeros_like(br)
    if a.mimic:
        for b in range(B):
            bb = br[b]; xb = x[b]
            bv = xb[bb]
            if bv.numel() < 5000:
                continue
            q3, q25, q60 = torch.quantile(bv[torch.randint(bv.numel(), (20000,), device=dev, generator=gen)].float(),
                                          torch.tensor([0.03, 0.25, 0.6], device=dev)).tolist()
            far = ~(F.max_pool3d((ins[b] > 0).float()[None, None], 9, 1, 4)[0, 0] > 0)
            nt = int(torch.randint(0, a.mimic + 1, (1,), device=dev, generator=gen))
            for _ in range(nt):
                L_ = u(gen, 6, 25, dev); r_ = u(gen, 0.6, 1.3, dev); half = int(L_ / 2 + 3)
                m = (bb & far & (xb > q60))[half:P - half, half:P - half, half:P - half]
                idx = torch.nonzero(m)
                if len(idx) == 0:
                    continue
                c = idx[int(torch.randint(len(idx), (1,), device=dev, generator=gen))] + half
                sl = tuple(slice(int(ci) - half, int(ci) + half + 1) for ci in c); S = 2 * half + 1
                g = torch.stack(torch.meshgrid(*[torch.arange(S, device=dev, dtype=torch.float32) - half] * 3, indexing="ij"), 0)
                dvec = torch.randn(3, device=dev, generator=gen); dvec = dvec / dvec.norm()
                along = torch.einsum("i,ixyz->xyz", dvec, g); perp = (g - along[None] * dvec.view(3, 1, 1, 1)).norm(dim=0)
                alpha = torch.sigmoid((r_ - perp) / 0.3) * torch.sigmoid((L_ / 2 - along.abs()) / 0.5) * bb[sl] * far[sl]
                tgt = q3 + u(gen, -0.1, 0.4, dev) * (q25 - q3)                               # CSF-like
                x[b][sl] = (xb[sl] + alpha * (tgt - xb[sl])).to(x.dtype)
                mim[b][sl] = mim[b][sl] | (alpha > 0.5)
            mim[b] = mim[b] | (edges[b] & far)                                              # sulcal CSF interface = mimic too
    return x, ins, nsyn, edges, mim


def intensity_dr(x, br, gen, a):
    """extreme intensity / resolution randomisation per sample; returns z-scored (inside brain) x, zero outside. x (B,P,P,P)."""
    B = x.shape[0]; dev = x.device; P = x.shape[1]
    out = []
    for b in range(B):
        t = x[b].float(); m = br[b]
        if m.sum() < 100:
            out.append(t * 0); continue
        v = t[m]
        sub = v[torch.randint(v.numel(), (20000,), device=dev, generator=gen)]
        lo, hi = torch.quantile(sub, torch.tensor([0.005, 0.995], device=dev)).tolist()
        t = ((t - lo) / max(hi - lo, 1e-3)).clamp(-0.2, 1.2)
        if rand(gen, dev) < a.p_aug:                                     # GIN random conv net (mixed with the original)
            C = 8; h = t[None, None]
            for i in range(3):
                cin = 1 if i == 0 else C; cout = 1 if i == 2 else C
                k = 3 if rand(gen, dev) < 0.5 else 1
                wgt = torch.randn(cout, cin, k, k, k, device=dev, generator=gen) / (cin * k ** 3) ** 0.5
                h = F.conv3d(h, wgt, padding=k // 2)
                if i < 2:
                    h = F.leaky_relu(h, 0.2)
            h = h[0, 0]; hv = h[m]
            h = (h - hv.mean()) / (hv.std() + 1e-6) * (t[m].std() + 1e-6) + t[m].mean()
            al = u(gen, 0.2, 1.0, dev)
            t = al * h + (1 - al) * t
        if rand(gen, dev) < a.p_aug:                                     # gamma
            mn = t[m].min(); rg = (t[m].max() - mn).clamp(min=1e-3)
            t = ((t - mn) / rg).clamp(min=0) ** math.exp(u(gen, math.log(0.5), math.log(2.0), dev)) * rg + mn
        if rand(gen, dev) < a.p_aug:                                     # multiplicative bias field
            f = F.interpolate(torch.randn(1, 1, 4, 4, 4, device=dev, generator=gen), size=(P,) * 3, mode="trilinear", align_corners=True)[0, 0]
            f = f / (f.abs().max() + 1e-6) * u(gen, 0.1, 0.5, dev)
            mn = t[m].min(); t = (t - mn) * torch.exp(f) + mn
        if rand(gen, dev) < 0.25:                                        # thick slices along one axis (resolution randomisation)
            ax = int(torch.randint(0, 3, (1,), device=dev, generator=gen)); fc = u(gen, 1.5, 4.0, dev)
            sz = [P, P, P]; sz[ax] = max(int(round(P / fc)), 8)
            lo_ = F.interpolate(t[None, None], size=sz, mode="area")
            t = F.interpolate(lo_, size=(P,) * 3, mode="trilinear", align_corners=False)[0, 0]
        if rand(gen, dev) < 0.15:                                        # isotropic low resolution
            fc = u(gen, 1.2, 2.0, dev); sz = [max(int(round(P / fc)), 8)] * 3
            t = F.interpolate(F.interpolate(t[None, None], size=sz, mode="area"), size=(P,) * 3, mode="trilinear", align_corners=False)[0, 0]
        if rand(gen, dev) < 0.2:                                         # blur
            s = u(gen, 0.3, 1.0, dev); r = 2; kx = torch.exp(-(torch.arange(-r, r + 1, device=dev, dtype=torch.float32) ** 2) / (2 * s * s))
            kx = kx / kx.sum()
            for ax in range(3):
                shp = [1, 1, 1, 1, 1]; shp[2 + ax] = 2 * r + 1
                pad = [0, 0, 0, 0, 0, 0]; pad[2 * (2 - ax)] = r; pad[2 * (2 - ax) + 1] = r
                t = F.conv3d(F.pad(t[None, None], pad, mode="replicate"), kx.view(shp))[0, 0]
        if rand(gen, dev) < 0.4:                                         # noise (Gaussian or Rician)
            sd = u(gen, 0.0, 0.08, dev)
            if rand(gen, dev) < 0.5:
                t = t + torch.randn_like(t) * sd
            else:
                t = torch.sqrt((t + torch.randn_like(t) * sd) ** 2 + (torch.randn_like(t) * sd) ** 2)
        v = t[m]
        t = (t - v.mean()) / (v.std() + 1e-6)
        out.append(t * m)
    return torch.stack(out)


# ---------------------------------------------------------------------------------------------------------------- loss
def losses(outs, y, valid, ins, a, edges=None, mim=None):
    """outs: list of logits (B,2,...) full res first; y (B,P,P,P) bool; valid (B,..) bool (brain); ins (B,..) long instance ids."""
    lo = outs[0].float()
    margin = lo[:, 1] - (torch.logsumexp(lo[:, [0, 2]], 1) if lo.shape[1] == 3 else lo[:, 0])
    # CE with deep supervision (targets max-pooled so tiny lesions survive at coarse scales)
    ce = 0.0; wsum = 0.0
    for i, o in enumerate(outs):
        o = o.float(); s = o.shape[2:]
        if i == 0:
            yt, vt = y, valid
            mt = mim if mim is not None else None
        else:
            f = y.shape[1] // s[0]
            yt = F.max_pool3d(y.float()[:, None], f, f)[:, 0] > 0
            mt = (F.max_pool3d(mim.float()[:, None], f, f)[:, 0] > 0) if mim is not None else None
            vt = F.max_pool3d(valid.float()[:, None], f, f)[:, 0] > 0
        w = 0.5 ** i
        tgt = yt.long() if mt is None or o.shape[1] == 2 else torch.where(yt, 1, torch.where(mt, 2, 0)).long()
        l = F.cross_entropy(o, tgt, reduction="none")
        ce = ce + w * (l * vt).sum() / vt.sum().clamp(min=1); wsum += w
    ce = ce / wsum
    p = torch.softmax(lo, 1)[:, 1] * valid
    yf = y.float()
    dice = 1 - (2 * (p * yf).sum() + 1) / (p.sum() + yf.sum() + 1)
    # instance terms
    blob, det, nin = 0.0, 0.0, 0
    B = y.shape[0]
    for b in range(B):
        ib = ins[b]
        ids = torch.unique(ib); ids = ids[ids > 0]
        if len(ids) == 0:
            continue
        others_all = ib > 0
        for i in ids.tolist():
            mi = ib == i
            nzi = torch.nonzero(mi)
            lo_ = (nzi.min(0)[0] - 6).clamp(min=0); hi_ = nzi.max(0)[0] + 7
            sl = tuple(slice(int(l_), int(h_)) for l_, h_ in zip(lo_, hi_))
            m_ = mi[sl].float(); keep = (~(others_all[sl] & ~mi[sl])) & valid[b][sl]
            pp = p[b][sl] * keep
            blob = blob + 1 - (2 * (pp * m_).sum() + 1) / (pp.sum() + m_.sum() + 1)
            mm = margin[b][sl][mi[sl]].max()
            det = det + F.softplus(-mm)
            nin += 1
    blob = blob / max(nin, 1); det = det / max(nin, 1)
    # hard negatives: top-k background margins per sample (balances the max-evidence term)
    neg = margin.masked_fill(~(valid & ~(F.max_pool3d(yf[:, None], 5, 1, 2)[:, 0] > 0)), -1e4).flatten(1)
    k = a.hn_k
    hn = F.softplus(torch.topk(neg, k, 1)[0]).mean() if a.w_hn > 0 else margin.sum() * 0   # top-k caps the map (B_LOG §6) -> off in b2t family
    tot = ce + dice + a.w_blob * blob + a.w_det * det + a.w_hn * hn
    csfl = 0.0
    if edges is not None and a.w_csf > 0:
        em = edges & valid & ~(F.max_pool3d(yf[:, None], 7, 1, 3)[:, 0] > 0)                # CSF-adjacent, away from any lesion
        if a.csf_mode == "wce":                          # calibration-safe: weighted CE over ALL CSF-edge voxels (no top-k ceiling)
            csfl = (F.softplus(margin) * em).sum() / em.sum().clamp(min=1)
        else:
            ne = margin.masked_fill(~em, -1e4).flatten(1)
            csfl = F.softplus(torch.topk(ne, a.hn_k, 1)[0]).mean()
        tot = tot + a.w_csf * csfl
    return tot, dict(ce=float(ce), dice=float(dice), blob=float(blob), det=float(det), hn=float(hn), csf=float(csfl), nin=nin)


# ---------------------------------------------------------------------------------------------------------------- train
def main():
    import pandas as pd
    ap = argparse.ArgumentParser()
    ap.add_argument("--tag", default="b1"); ap.add_argument("--iters", type=int, default=30000); ap.add_argument("--patch", type=int, default=128)
    ap.add_argument("--bs", type=int, default=3); ap.add_argument("--lr", type=float, default=1e-2); ap.add_argument("--save_every", type=int, default=500)
    ap.add_argument("--p_les", type=float, default=0.5); ap.add_argument("--p_syn", type=float, default=0.8); ap.add_argument("--max_syn", type=int, default=6)
    ap.add_argument("--p_aug", type=float, default=0.5); ap.add_argument("--w_blob", type=float, default=1.0); ap.add_argument("--w_det", type=float, default=0.5)
    ap.add_argument("--c_lo", type=float, default=0.04); ap.add_argument("--xfold", type=int, default=-1); ap.add_argument("--csf_mode", default="topk"); ap.add_argument("--mimic", type=int, default=0); ap.add_argument("--p_rule", type=float, default=1.0)
    ap.add_argument("--bin_w", default=""); ap.add_argument("--faint_w", type=float, default=0.0); ap.add_argument("--gm_cmax", type=float, default=1.2)
    ap.add_argument("--csf_gap", type=int, default=0); ap.add_argument("--w_csf", type=float, default=0.0); ap.add_argument("--w_hn", type=float, default=0.5); ap.add_argument("--hn_k", type=int, default=400)
    ap.add_argument("--nkeys", type=int, default=0); ap.add_argument("--smoke", action="store_true"); ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--dump", type=int, default=0, help="save N augmented batches for visual QC and exit")
    a = ap.parse_args()
    dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    torch.backends.cudnn.benchmark = True
    if (Q.OUT / "models" / f"{a.tag}.pt").exists() and not (a.smoke or a.dump):
        log("ALREADY_DONE", a.tag); return
    keys = Q.train_keys()
    if a.xfold >= 0:                                   # OOF evidence for the drawer: train on 2 of the 3 cascade2 patient folds
        import json as _j
        asg = _j.load(open(Q.guard(Q.WS / "outputs/direction2/cascade2/patient_folds.json")))["assign"]
        miss = [k for k in keys if k not in asg]
        assert not miss, ("keys without a cascade2 fold", miss[:5])
        keys = [k for k in keys if asg[k] != a.xfold]
        log("xfold", a.xfold, "training keys", len(keys))
    if a.nkeys:
        keys = keys[:a.nkeys]
    index = pd.read_pickle(Q.OUT / "index" / "index.pkl")
    data = Data(keys, index, [float(v) for v in a.bin_w.split(',')] if a.bin_w else None, a.faint_w)
    md = Q.OUT / "models"; md.mkdir(parents=True, exist_ok=True)
    ck = md / f"{a.tag}.ckpt"
    net = make_net(True, 3 if a.mimic else 2).to(dev)
    opt = torch.optim.SGD(net.parameters(), lr=a.lr, momentum=0.99, nesterov=True, weight_decay=3e-5)
    it0 = 0
    gen = torch.Generator(device=dev); gen.manual_seed(a.seed)
    if ck.exists():
        s = torch.load(ck, map_location=dev, weights_only=False)
        net.load_state_dict(s["net"]); opt.load_state_dict(s["opt"]); it0 = s["it"]
        gen.set_state(s["gen"].to(gen.get_state().device) if hasattr(s["gen"], "to") else s["gen"])
        log("RESUME", it0)
    q = queue.Queue(maxsize=6); stop = threading.Event()
    ths = [threading.Thread(target=producer, args=(data, q, zlib.crc32(f"{a.tag}{a.seed}{it0}{w}".encode()), a.patch, a.bs, a.p_les, stop), daemon=True)
           for w in range(3)]
    for t in ths:
        t.start()
    net.train(); t0 = time.time(); run = {}
    for it in range(it0, a.iters):
        lr = a.lr * (1 - it / a.iters) ** 0.9
        for gp in opt.param_groups:
            gp["lr"] = lr
        xs, ss, ins, ns = q.get()
        x = torch.from_numpy(xs).to(dev).float()[:, None]; s = torch.from_numpy(ss).to(dev)
        br = (s >= 0).float()[:, None]; insf = torch.from_numpy(ins).to(dev).float()[:, None]
        with torch.no_grad():
            x, brb, insf = spatial(x, br, insf, gen)
            x = x[:, 0]; brb = brb[:, 0]; insf = insf[:, 0]
            x, insf, nsyn, edges, mim = paint(x, brb, insf, ns, gen, a)
            x = intensity_dr(x, brb, gen, a)
            y = insf > 0
        if a.dump:
            Q.save_npz(Q.OUT / "qc" / f"{a.tag}_batch{it}.npz", x=x.cpu().numpy().astype(np.float16), y=y.cpu().numpy(), ins=insf.cpu().numpy().astype(np.int16),
                       nreal=np.array(ns), nsyn=np.array(nsyn))
            if it - it0 + 1 >= a.dump:
                break
            continue
        with torch.autocast(dev.type, dtype=torch.bfloat16, enabled=dev.type == "cuda"):
            outs = net(x[:, None])
        loss, parts = losses(outs, y, brb, insf.long(), a, edges, mim if a.mimic else None)
        opt.zero_grad(set_to_none=True); loss.backward()
        torch.nn.utils.clip_grad_norm_(net.parameters(), 12.0); opt.step()
        for k_, v_ in dict(parts, loss=float(loss), nsyn=float(np.mean(nsyn)), nreal=float(np.mean(ns))).items():
            run[k_] = 0.98 * run.get(k_, v_) + 0.02 * v_
        if it % 100 == 0 or a.smoke:
            log(f"it {it}/{a.iters} lr {lr:.4f} " + " ".join(f"{k_} {v_:.3f}" for k_, v_ in run.items()) + f" {time.time() - t0:.0f}s qsize {q.qsize()}")
        if (it + 1) % a.save_every == 0 and it + 1 < a.iters:
            tmp = str(ck) + ".tmp"
            torch.save({"net": net.state_dict(), "opt": opt.state_dict(), "it": it + 1, "gen": gen.get_state()}, Q.guard_write(tmp)); os.replace(tmp, ck)
        if a.smoke and it - it0 >= 20:
            break
    stop.set()
    if not a.smoke and not a.dump:
        torch.save(net.state_dict(), Q.guard_write(md / f"{a.tag}.pt"))
        Q.jdump({"ncls": 3 if a.mimic else 2, "patch": a.patch, "args": vars(a)}, md / f"{a.tag}.json")
        if ck.exists():
            ck.unlink()                                            # storage: the final .pt is all that is kept (410 MB)
        log("C4B_TRAIN_DONE", a.tag)
    else:
        if a.smoke:
            torch.save(net.state_dict(), Q.guard_write(md / f"{a.tag}.pt"))
        log("SMOKE_DONE", f"{(time.time() - t0):.0f}s")


if __name__ == "__main__":
    main()