File size: 39,612 Bytes
7462f1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a39e70
7462f1a
 
 
 
6a39e70
7462f1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a39e70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e4f237
 
6a39e70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e4f237
 
 
 
 
 
6a39e70
 
 
 
 
 
4e4f237
 
6a39e70
 
 
 
 
 
 
 
 
 
 
 
4e4f237
6a39e70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e4f237
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a39e70
 
7462f1a
 
 
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
"""Method F - PhysMode-LNP (LaRIN-style) and Method G - DiffMode-LNP (CoDiffGRN-style).

Both methods keep the leak-free chemistry encoder of PhysSet-LNP but replace the
single regressor with a two-part *base + residual-expert* decoder

    y_hat = s_base(h) + alpha * log sum_k pi_k exp(Delta_k(h, c_k))

in which a small set of K discrete "formulation modes" carries a residual
correction on top of a base scorer.  The two implementations differ only in how
the mode posterior ``pi`` is obtained, which is exactly the axis on which the
two source papers differ.

PhysMode-LNP  (LaRIN, Sec. 3.2-3.3)
    A VQ codebook assigns each formulation to K prototypes with a cosine
    metric and temperature tau.  The codebook is updated by exponential moving
    averages over assigned formulations; the encoder is trained through the
    soft posterior and through a commitment term.  Usage balancing (KL to the
    uniform prior) and codebook orthogonality keep the prototypes apart.  The
    residual is marginalised over the soft posterior, i.e. LaRIN's
    "residual latent-relation odds" decoder with the relation index replaced by
    the formulation-mode index.

DiffMode-LNP  (CoDiffGRN, Sec. 4.1-4.3)
    The mode token is treated as a categorical state and corrupted with a D3PM
    uniform transition matrix on a cosine schedule, Q_t = a_t I + (1-a_t) 1 m^T.
    A denoiser conditioned on the chemistry embedding, the noisy one-hot state
    and a sinusoidal timestep embedding predicts x_0; inference starts from the
    marginal m and runs the closed-form reverse chain.  The resulting x_0
    posterior becomes ``pi``.  CoDiffGRN's teacher forcing corresponds to
    always conditioning on the observed chemistry (there is no hidden node
    component to force), and its node-level auxiliary MSE corresponds to the
    physics auxiliary head.  The optional ``tass_p`` switch adds CoDiffGRN's
    TF-ALL sub-graph sampling as node-subset training.

Both modules share everything else with PhysSet-LNP: the dual protonation-state
graph encoder, the 10-node physically biased set attention, the smooth-L1 +
within-study ranking objective, the MD physics auxiliary, and the k-shot
calibration protocol.  Any improvement therefore isolates the mode decoder.
"""

from __future__ import annotations

import math
from typing import Sequence

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

from ..store import FeatureStore
from ..trainer import NeuralModel, TrainConfig
from .backbone import _BackboneLoss, FormulationEncoder


# ---------------------------------------------------------------------------
# LaRIN Sec. 3.2 - discrete latent mode codebook
# ---------------------------------------------------------------------------


class LatentModeCodebook(nn.Module):
    """VQ codebook over formulation-mode representations.

    Assignment is cosine (LaRIN uses ``argmax_k cos(z, c_k)``); the posterior
    used by the decoder is the tempered softmax of the same cosine scores.  The
    code vectors are *not* optimised by gradient descent: they follow the
    encoder by exponential moving averages, which is what makes the assignment
    stable enough to be read as a discrete mode.
    """

    def __init__(self, dim: int, n_codes: int = 16, tau: float = 0.2,
                 beta: float = 0.25, decay: float = 0.99, eps: float = 1e-5):
        super().__init__()
        self.dim, self.K, self.tau, self.beta = dim, n_codes, tau, beta
        self.decay, self.eps = decay, eps
        w = F.normalize(torch.randn(n_codes, dim), dim=-1)
        self.weight = nn.Parameter(w, requires_grad=False)
        self.register_buffer("ema_count", torch.zeros(n_codes))
        self.register_buffer("ema_weight", w.clone())

    # -- assignment ------------------------------------------------------
    def posterior(self, u: torch.Tensor):
        cos = F.normalize(u, dim=-1) @ F.normalize(self.weight, dim=-1).t()
        return F.softmax(cos / self.tau, dim=-1), cos

    # -- EMA bookkeeping -------------------------------------------------
    @torch.no_grad()
    def ema_update(self, u: torch.Tensor, idx: torch.Tensor) -> None:
        onehot = F.one_hot(idx, self.K).float()
        n = onehot.sum(0)
        self.ema_count.mul_(self.decay).add_(n, alpha=1.0 - self.decay)
        dw = onehot.t() @ u.detach()
        self.ema_weight.mul_(self.decay).add_(dw, alpha=1.0 - self.decay)
        # Laplace-smoothed normalisation, as in the VQ-VAE / SwAV implementations
        cnt = self.ema_count.sum()
        weight = (self.ema_weight + self.eps) / (self.ema_count + self.eps).unsqueeze(-1)
        weight = weight * (cnt / (cnt + self.K * self.eps))
        self.weight.data.copy_(F.normalize(weight, dim=-1))

    # -- losses ----------------------------------------------------------
    def losses(self, u: torch.Tensor, pi: torch.Tensor, idx: torch.Tensor) -> dict:
        c = self.weight[idx]
        # LaRIN L_com: pull the code vector onto the encoder output.  With an EMA
        # codebook this is already handled by ``ema_update``; it is computed for
        # monitoring only and carries no gradient.
        code = (u.detach() - c).pow(2).mean()
        # commitment: keep the encoder output close to its assigned prototype
        commit = (u - c.detach()).pow(2).mean()
        # usage balancing: KL(mean posterior || uniform)
        pbar = pi.mean(0)
        bal = (pbar * torch.log(pbar * self.K + 1e-9)).sum()
        # L_orth: prototypes should not collapse onto a low-dimensional subspace
        cn = F.normalize(self.weight, dim=-1)
        gram = cn @ cn.t()
        orth = (gram - torch.eye(self.K, device=gram.device)).pow(2).mean()
        return {"code": code, "commit": commit, "bal": bal, "orth": orth}


# ---------------------------------------------------------------------------
# Residual latent-mode decoder (shared by both methods)
# ---------------------------------------------------------------------------


class ResidualModeDecoder(nn.Module):
    """``s_base(h) + alpha * mix_k pi_k Delta(h, c_k)``."""

    def __init__(self, in_dim: int, code_dim: int, n_codes: int, hidden: int = 128,
                 dropout: float = 0.1, alpha_init: float = 0.1, mix: str = "logsumexp"):
        super().__init__()
        self.base = nn.Sequential(
            nn.Linear(in_dim, 64), nn.SiLU(), nn.Dropout(dropout), nn.Linear(64, 1)
        )
        self.expert = nn.Sequential(
            nn.Linear(in_dim + code_dim, hidden), nn.SiLU(), nn.Dropout(dropout),
            nn.Linear(hidden, 1),
        )
        self.alpha = nn.Parameter(torch.tensor(float(alpha_init)))
        self.mix = mix

    def forward(self, h: torch.Tensor, pi: torch.Tensor, codes: torch.Tensor,
                hard: bool = False, use_residual: bool = True,
                residual_only: bool = False, h_expert: torch.Tensor | None = None):
        s_base = self.base(h).squeeze(-1)
        if not use_residual:
            return s_base, s_base, None
        B, K = pi.shape
        he = h if h_expert is None else h_expert
        delta = self.expert(
            torch.cat([he.unsqueeze(1).expand(B, K, -1), codes.unsqueeze(0).expand(B, K, -1)], -1)
        ).squeeze(-1)
        if hard:
            oh = F.one_hot(pi.argmax(-1), K).to(delta.dtype)
            mixed = (oh * delta).sum(-1)
        elif self.mix == "logsumexp":
            # LaRIN's marginalisation log sum_r pi_r exp(alpha Delta_r); the sum is
            # exactly zero when every expert agrees with the base (Delta = 0)
            mixed = torch.logsumexp(torch.log(pi + 1e-9) + self.alpha * delta, dim=-1)
        else:
            mixed = self.alpha * (pi * delta).sum(-1)
        if residual_only:
            y = mixed
        else:
            y = s_base + mixed
        return y, s_base, delta


def _sinusoid(t: torch.Tensor, dim: int) -> torch.Tensor:
    half = max(1, dim // 2)
    freqs = torch.exp(
        -math.log(10000.0) * torch.arange(half, device=t.device, dtype=torch.float32) / half
    )
    args = t.float().unsqueeze(-1) * freqs.unsqueeze(0)
    return torch.cat([torch.sin(args), torch.cos(args)], dim=-1)


# ---------------------------------------------------------------------------
# CoDiffGRN Sec. 4.1-4.2 - D3PM uniform discrete diffusion on the mode token
# ---------------------------------------------------------------------------


class DiscreteModeDiffusion(nn.Module):
    """Forward corruption and closed-form reverse chain for one categorical token."""

    def __init__(self, n_codes: int, n_steps: int = 30):
        super().__init__()
        self.K, self.T = n_codes, n_steps
        t = torch.arange(n_steps + 1, dtype=torch.float64)
        abar = torch.cos(((t / n_steps) + 0.008) / 1.008 * math.pi / 2.0) ** 2
        abar = (abar / abar[0]).clamp(1e-3, 1.0 - 1e-3)
        abar[0] = 1.0
        self.register_buffer("abar", abar.to(torch.float32))

    def q_sample(self, x0: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
        a = self.abar[t].unsqueeze(-1)
        p = a * x0 + (1.0 - a) / self.K
        idx = torch.multinomial(p, 1).squeeze(-1)
        return F.one_hot(idx, self.K).to(x0.dtype)

    def posterior(self, x0_probs: torch.Tensor, xt: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
        """q(x_{t-1} | x_t, x_0) with the uniform transition matrix."""
        a = (self.abar[t] / self.abar[t - 1]).clamp(0.0, 1.0).unsqueeze(-1)
        x0_prev = self.abar[t - 1].unsqueeze(-1) * x0_probs + (1.0 - self.abar[t - 1]).unsqueeze(-1) / self.K
        post = (a * xt + (1.0 - a) / self.K * xt.sum(-1, keepdim=True)) * x0_prev
        return post / post.sum(-1, keepdim=True).clamp_min(1e-12)

    @torch.no_grad()
    def reverse(self, denoiser: nn.Module, h: torch.Tensor) -> torch.Tensor:
        """Mean-field reverse chain from the marginal; returns the x_0 posterior."""
        B = h.shape[0]
        xt = torch.full((B, self.K), 1.0 / self.K, device=h.device, dtype=h.dtype)
        for step in range(self.T, 0, -1):
            t = torch.full((B,), step, device=h.device, dtype=torch.long)
            x0 = torch.softmax(denoiser(h, xt, t), dim=-1)
            xt = self.posterior(x0, xt, t)
        return xt


class ModeDenoiser(nn.Module):
    """Conditional graph-free denoiser: (chemistry, noisy state, timestep) -> x_0 logits."""

    def __init__(self, in_dim: int, n_codes: int, hidden: int = 192, t_dim: int = 32,
                 dropout: float = 0.1):
        super().__init__()
        self.t_dim = t_dim
        self.t_proj = nn.Sequential(nn.Linear(t_dim, hidden), nn.SiLU(), nn.Linear(hidden, hidden))
        self.inp = nn.Linear(in_dim + n_codes + t_dim, hidden)
        self.body = nn.Sequential(
            nn.SiLU(), nn.Dropout(dropout), nn.Linear(hidden, hidden), nn.SiLU(),
        )
        self.out = nn.Linear(hidden, n_codes)

    def forward(self, h: torch.Tensor, xt: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
        te = _sinusoid(t, self.t_dim)
        x = torch.cat([h, xt, te], dim=-1)
        return self.out(self.body(self.inp(x)) + self.t_proj(te))


# ---------------------------------------------------------------------------
# Shared trunk
# ---------------------------------------------------------------------------


class _ModeTrunk(nn.Module, _BackboneLoss):
    def __init__(self, fp_dim: int, ctx_dim: int, desc_dim: int, d_model: int = 192,
                 n_heads: int = 6, n_layers: int = 3, dropout: float = 0.1,
                 lam_rank: float = 0.5, lam_phys: float = 0.2, rank_gamma: float = 2.0,
                 dual_state: bool = True, use_md_aux: bool = True,
                 cond_mode: str = "concat", node_mode: str = "phys",
                 mode_space: str = "full", enc_extra: dict | None = None, **kw):
        super().__init__()
        self.enc = FormulationEncoder(
            fp_dim=fp_dim, ctx_dim=ctx_dim, desc_dim=desc_dim, d_model=d_model,
            n_heads=n_heads, n_layers=n_layers, dropout=dropout, dual_state=dual_state,
            cond_mode=cond_mode, node_mode=node_mode, **(enc_extra or {}),
        )
        self.lam_rank, self.lam_phys, self.rank_gamma = lam_rank, lam_phys, rank_gamma
        self.use_md_aux, self.dual_state = use_md_aux, dual_state
        out = self.enc.out_dim
        self.trunk = nn.Sequential(
            nn.Linear(out, 256), nn.LayerNorm(256), nn.SiLU(), nn.Dropout(dropout),
        )
        self.phys_head = nn.Sequential(nn.Linear(out, 96), nn.SiLU(), nn.Linear(96, 3))
        # "chem": the mode space and the residual experts see chemistry only,
        #         i.e. the message-passed dual-state graph embedding and the
        #         descriptor vector, never the experiment context.  The base
        #         scorer keeps the full representation.  This stops a mode from
        #         degenerating into a study identifier, which is the failure mode
        #         documented for fingerprint nodes and helper-lipid identity.
        self.mode_space = mode_space
        if mode_space == "chem":
            chem_dim = d_model * (2 if dual_state else 1) + 128
            self.chem_trunk = nn.Sequential(
                nn.Linear(chem_dim, 256), nn.LayerNorm(256), nn.SiLU(), nn.Dropout(dropout)
            )
        else:
            self.chem_trunk = None

    def encode(self, batch, node_drop_p: float = 0.0):
        e = self.enc.encode(batch, node_drop_p=node_drop_p)
        feats = torch.cat([e["z_form"], e["g_il_dual"], e["d_il"]], dim=-1)
        h = self.trunk(feats)
        h_mode = h
        if self.chem_trunk is not None:
            h_mode = self.chem_trunk(torch.cat([e["g_il_dual"], e["d_il"]], dim=-1))
        return h, feats, h_mode

    def _aux_losses(self, batch, feat_vec, total, logs):
        if self.use_md_aux:
            target = batch["cpp"][:, [2, 3]]
            phys = F.l1_loss(self.phys_head(feat_vec)[:, :2], target)
            stable = torch.sigmoid(self.phys_head(feat_vec)[:, 2])
            flag = batch["md_flag"] > 0
            if bool(flag.any()):
                phys = phys + F.binary_cross_entropy(
                    stable[flag].clamp(1e-6, 1 - 1e-6), batch["md_stable"][flag], reduction="mean"
                )
            total = total + self.lam_phys * phys
            logs["phys"] = float(phys.detach())
        return total# ---------------------------------------------------------------------------
# Method F - PhysMode-LNP
# ---------------------------------------------------------------------------


class PhysModeModule(_ModeTrunk):
    def __init__(self, fp_dim: int, ctx_dim: int, desc_dim: int, n_codes: int = 16,
                 code_dim: int = 64, tau: float = 0.2, beta: float = 0.25,
                 alpha_init: float = 0.1, mix: str = "logsumexp",
                 lam_vq: float = 0.1, lam_bal: float = 0.05, lam_orth: float = 0.01,
                 lam_base: float = 0.5, use_vq: bool = True, hard_mode: bool = False,
                 use_residual: bool = True, residual_only: bool = False, **kw):
        super().__init__(fp_dim=fp_dim, ctx_dim=ctx_dim, desc_dim=desc_dim, **kw)
        self.n_codes, self.code_dim = n_codes, code_dim
        self.mode_proj = nn.Sequential(
            nn.Linear(256, 256), nn.SiLU(), nn.Linear(256, code_dim)
        )
        self.use_vq = use_vq
        if use_vq:
            self.codebook = LatentModeCodebook(code_dim, n_codes, tau, beta)
        else:
            # ablation: freely learned prototypes, no EMA, no commitment
            self.codes = nn.Parameter(F.normalize(torch.randn(n_codes, code_dim), dim=-1) * 0.5)
        self.decoder = ResidualModeDecoder(256, code_dim, n_codes, alpha_init=alpha_init, mix=mix)
        self.lam_vq, self.lam_bal, self.lam_orth, self.lam_base = lam_vq, lam_bal, lam_orth, lam_base
        self.hard_mode, self.use_residual, self.residual_only = hard_mode, use_residual, residual_only

    @property
    def codes_weight(self):
        return self.codebook.weight if self.use_vq else F.normalize(self.codes, dim=-1)

    def forward(self, batch):
        h, feat_vec, h_mode = self.encode(batch)
        if not self.use_residual:
            # nested Base-Only ablation: the mode machinery is switched off
            # entirely, so this is PhysSet-LNP with an unused extra parameter set
            y_hat, s_base, _ = self.decoder(
                h, torch.zeros(h.shape[0], self.n_codes, device=h.device),
                self.codes_weight, use_residual=False,
            )
            return {"y_hat": y_hat, "s_base": s_base, "phys": self.phys_head(feat_vec),
                    "z": h, "pi": None, "vq": {}, "feats": feat_vec}
        u = self.mode_proj(h_mode)
        if self.use_vq:
            pi, cos = self.codebook.posterior(u)
            idx = cos.argmax(-1)
            if self.training:
                self.codebook.ema_update(u, idx)
            vq = self.codebook.losses(u, pi, idx) if self.training else {}
        else:
            pi = F.softmax(F.normalize(u, dim=-1) @ self.codes_weight.t() / 0.2, dim=-1)
            vq = {}
        y_hat, s_base, delta = self.decoder(
            h, pi, self.codes_weight, hard=self.hard_mode, h_expert=h_mode,
            use_residual=self.use_residual, residual_only=self.residual_only,
        )
        return {"y_hat": y_hat, "s_base": s_base, "phys": self.phys_head(feat_vec),
                "z": h, "pi": pi, "vq": vq, "feats": feat_vec}

    def compute_loss(self, batch, out, epoch=0, n_epochs=1):
        reg = F.smooth_l1_loss(out["y_hat"], batch["y"])
        rank = self._rank_loss(out["y_hat"], batch)
        total = reg + self.lam_rank * rank
        logs = {"reg": float(reg.detach()), "rank": float(rank.detach())}
        if self.lam_base > 0:
            base_reg = F.smooth_l1_loss(out["s_base"], batch["y"])
            total = total + self.lam_base * base_reg
            logs["base"] = float(base_reg.detach())
        if self.use_vq and out.get("vq"):
            v = out["vq"]
            vq_loss = self.lam_vq * (v["commit"]) + self.lam_bal * v["bal"] + self.lam_orth * v["orth"]
            total = total + vq_loss
            logs.update({k: float(val.detach()) for k, val in v.items()})
        total = self._aux_losses(batch, out["feats"], total, logs)
        return total, logs


class PhysModeLNP(NeuralModel):
    name = "physmode"

    def build(self, store: FeatureStore, cfg: TrainConfig) -> nn.Module:
        return PhysModeModule(
            fp_dim=store.il_fp.shape[1], ctx_dim=store.ctx_dim,
            desc_dim=store.il_desc.shape[1], **self.kwargs
        )

    def need(self) -> Sequence[str]:
        return ("y", "ctx", "ratios", "nodes", "nodes_prot", "helpers", "study_id",
                "cpp", "md_flag", "graph", "desc")


# ---------------------------------------------------------------------------
# Method G - DiffMode-LNP
# ---------------------------------------------------------------------------


def _kmeans(x: np.ndarray, k: int, seed: int = 0, iters: int = 30, sub: int = 8192) -> np.ndarray:
    """Plain Lloyd k-means with k-means++ seeding (label-free discretisation)."""
    rng = np.random.default_rng(seed)
    if len(x) > sub:
        x = x[rng.choice(len(x), sub, replace=False)]
    x = x.astype(np.float64)
    # k-means++ initialisation
    c = [x[rng.integers(len(x))]]
    d2 = ((x - c[0]) ** 2).sum(1)
    for _ in range(1, k):
        p = d2 / max(d2.sum(), 1e-12)
        c.append(x[rng.choice(len(x), p=p)])
        d2 = np.minimum(d2, ((x - c[-1]) ** 2).sum(1))
    c = np.stack(c)
    for _ in range(iters):
        lab = np.argmin(((x[:, None, :] - c[None]) ** 2).sum(-1), axis=1)
        for j in range(k):
            m = lab == j
            if m.any():
                c[j] = x[m].mean(0)
    return c


class DiffModeModule(_ModeTrunk):
    def __init__(self, fp_dim: int, ctx_dim: int, desc_dim: int, n_codes: int = 16,
                 code_dim: int = 64, n_steps: int = 30, alpha_init: float = 0.1,
                 mix: str = "logsumexp", lam_mode: float = 0.5, lam_base: float = 0.5,
                 use_residual: bool = True, residual_only: bool = False,
                 hard_mode: bool = False, tass_p: float = 0.0, **kw):
        super().__init__(fp_dim=fp_dim, ctx_dim=ctx_dim, desc_dim=desc_dim, **kw)
        self.n_codes = n_codes
        self.register_buffer("mode_token", torch.full((0,), -1, dtype=torch.long))
        self.mode_embed = nn.Embedding(n_codes, code_dim)
        nn.init.normal_(self.mode_embed.weight, std=0.05)
        self.diffusion = DiscreteModeDiffusion(n_codes, n_steps)
        self.denoiser = ModeDenoiser(256, n_codes)
        self.decoder = ResidualModeDecoder(256, code_dim, n_codes, alpha_init=alpha_init, mix=mix)
        self.lam_mode, self.lam_base = lam_mode, lam_base
        self.use_residual, self.residual_only, self.hard_mode = use_residual, residual_only, hard_mode
        self.tass_p = tass_p

    def set_mode_token(self, token: np.ndarray) -> None:
        self.mode_token = torch.from_numpy(np.asarray(token, dtype=np.int64))

    def forward(self, batch):
        if self.training and self.tass_p > 0:
            h, feat_vec, h_mode = self.encode(batch, node_drop_p=self.tass_p)
        else:
            h, feat_vec, h_mode = self.encode(batch)
        if not self.use_residual:
            y_hat, s_base, _ = self.decoder(
                h, torch.zeros(h.shape[0], self.n_codes, device=h.device),
                self.mode_embed.weight, use_residual=False,
            )
            return {"y_hat": y_hat, "s_base": s_base, "phys": self.phys_head(feat_vec),
                    "z": h, "pi": None, "feats": feat_vec}
        mode_logits = None
        if self.training:
            tok = self.mode_token.to(h.device)[batch["row"]]
            x0 = F.one_hot(tok, self.n_codes).to(h.dtype)
            t = torch.randint(1, self.diffusion.T + 1, (h.shape[0],), device=h.device)
            xt = self.diffusion.q_sample(x0, t)
            mode_logits = self.denoiser(h_mode, xt, t)
            pi = torch.softmax(mode_logits, dim=-1)
        else:
            pi = self.diffusion.reverse(self.denoiser, h_mode)
        y_hat, s_base, delta = self.decoder(
            h, pi, self.mode_embed.weight, hard=self.hard_mode, h_expert=h_mode,
            use_residual=self.use_residual, residual_only=self.residual_only,
        )
        out = {"y_hat": y_hat, "s_base": s_base, "phys": self.phys_head(feat_vec),
               "z": h, "pi": pi, "feats": feat_vec}
        if mode_logits is not None:
            out["mode_logits"], out["mode_token"] = mode_logits, tok
        return out

    def compute_loss(self, batch, out, epoch=0, n_epochs=1):
        reg = F.smooth_l1_loss(out["y_hat"], batch["y"])
        rank = self._rank_loss(out["y_hat"], batch)
        total = reg + self.lam_rank * rank
        logs = {"reg": float(reg.detach()), "rank": float(rank.detach())}
        if self.lam_base > 0:
            base_reg = F.smooth_l1_loss(out["s_base"], batch["y"])
            total = total + self.lam_base * base_reg
            logs["base"] = float(base_reg.detach())
        if "mode_logits" in out:
            ce = F.cross_entropy(out["mode_logits"], out["mode_token"])
            total = total + self.lam_mode * ce
            logs["mode_ce"] = float(ce.detach())
        total = self._aux_losses(batch, out["feats"], total, logs)
        return total, logs


class DiffModeLNP(NeuralModel):
    name = "diffmode"

    def fit(self, store: FeatureStore, train_idx, val_idx, cfg: TrainConfig):
        # the discretisation must not see held-out formulations, so hand the
        # training rows to ``build`` through the config
        cfg.extra = {**cfg.extra, "train_idx": np.asarray(train_idx)}
        return super().fit(store, train_idx, val_idx, cfg)

    def build(self, store: FeatureStore, cfg: TrainConfig) -> nn.Module:
        kw = dict(self.kwargs)
        n_codes = kw.get("n_codes", 16)
        module = DiffModeModule(
            fp_dim=store.il_fp.shape[1], ctx_dim=store.ctx_dim,
            desc_dim=store.il_desc.shape[1], **kw
        )
        idx = cfg.extra.get("train_idx")
        if idx is None:
            idx = np.arange(len(store.y))
        # CoDiffGRN's cell-cluster discretisation, transferred to formulations:
        # cluster the label-free physicochemical profile (descriptors, conformer
        # packing, molar composition) into K discrete formulation modes.
        il = store.il_id[idx]
        desc = store.il_desc[il].astype(np.float32)
        cpp = store.il_cpp[il].astype(np.float32)
        lo, hi = np.percentile(desc, [0.5, 99.5], axis=0)
        desc = (np.clip(desc, lo, hi) - desc.mean(0)) / (desc.std(0) + 1e-6)
        cpp = (cpp - cpp.mean(0)) / (cpp.std(0) + 1e-6)
        comp = store.ratios[idx].astype(np.float32)
        x = np.concatenate([desc, cpp, comp], axis=1)
        # subsample rows for the k-means step, then assign every formulation
        rng = np.random.default_rng(cfg.seed)
        sel = rng.choice(len(idx), size=min(len(idx), 20000), replace=False)
        centres = _kmeans(x[sel], n_codes, seed=cfg.seed)
        d = ((x[:, None, :] - centres[None]) ** 2).sum(-1)
        token = np.full(len(store.y), 0, dtype=np.int64)
        token[idx] = np.argmin(d, axis=1)
        module.set_mode_token(token)
        sizes = np.bincount(token[idx], minlength=n_codes)
        print(f"[diffmode] {n_codes} formulation modes, cluster sizes {sizes.tolist()}")
        return module

    def need(self) -> Sequence[str]:
        return ("y", "ctx", "ratios", "nodes", "nodes_prot", "helpers", "study_id",
                "cpp", "md_flag", "graph", "desc")# ---------------------------------------------------------------------------
# Method H - RelMode-LNP : LaRIN's latent-relation decoder on node pairs
# ---------------------------------------------------------------------------


class PairRelationModes(nn.Module):
    """Discrete latent relation modes over the node pairs of a formulation.

    LaRIN's design has three parts, and all three are kept here verbatim in
    structure:

    1. a pair encoder ``z_uv = f([x_u || x_v])``;
    2. a codebook over those pair representations, assigned by cosine
       similarity and updated by exponential moving averages from the pairs
       that actually occur in the batch;
    3. a residual latent-relation odds decoder: each prototype contributes a
       scalar correction ``Delta_k(z_uv)`` and the corrections are marginalised
       with the tempered posterior,
       ``b_uv = log sum_k pi_uv,k exp(alpha Delta_k)``.

    The one transposition is the unit of the discrete variable. LaRIN indexes
    *relations between two drugs*; here a relation is an *intermolecular contact
    between two formulation components* (ionisable lipid <-> helper lipid,
    ionisable lipid <-> cholesterol, fragment <-> fragment, ...). The scalar
    ``b_uv`` enters the set attention as an additive logit, so the discrete mode
    modifies the message passing itself rather than only the output.
    """

    def __init__(self, d_model: int = 192, n_codes: int = 16, code_dim: int = 64,
                 tau: float = 0.2, beta: float = 0.25, alpha_init: float = 0.5,
                 hidden: int = 64, mix: str = "logsumexp", hard: bool = False,
                 use_vq: bool = True, center: bool = True, drop: float = 0.0,
                 expert_mode: str = "mlp", n_heads: int = 1, schema_only: bool = False):
        super().__init__()
        self.n_codes, self.code_dim = n_codes, code_dim
        self.tau, self.mix, self.hard = tau, mix, hard
        self.use_vq, self.center = use_vq, center
        self.pair_proj = nn.Sequential(
            nn.Linear(2 * d_model, d_model), nn.SiLU(),
            nn.Linear(d_model, code_dim),
        )
        self.codebook = LatentModeCodebook(code_dim, n_codes, tau, beta) if use_vq else None
        self.codes = (
            nn.Parameter(F.normalize(torch.randn(n_codes, code_dim), dim=-1) * 0.5)
            if not use_vq else None
        )
        # The residual expert is the only place where the mode can add capacity.
        #   "mlp"    full MLP over [z_uv || c_k]      (K * (2 d + 1) free params,
        #            can memorise pair-level patterns)
        #   "linear" rank-1 in z_uv: Delta_k = w.z_uv + b_k
        #   "scalar" Delta_k = b_k                    (K free parameters: the mode
        #            can only set an interaction archetype, not a pattern)
        #   "head"   Delta_kh = b_kh                  (K x H, one coupling per head)
        self.expert_mode, self.n_heads = expert_mode, n_heads
        self.schema_only = schema_only
        if schema_only:
            from .set_base import schema_edge_mask

            self.register_buffer("_schema", schema_edge_mask(), persistent=False)
        if expert_mode == "mlp":
            self.expert = nn.Sequential(
                nn.Linear(2 * code_dim, hidden), nn.SiLU(), nn.Dropout(drop), nn.Linear(hidden, 1)
            )
            self.gain = None
            self.bias = None
        elif expert_mode == "linear":
            self.gain = nn.Linear(code_dim, n_codes)
            self.expert = None
            self.bias = None
        elif expert_mode == "scalar":
            self.expert = None
            self.gain = None
            self.bias = nn.Parameter(torch.zeros(n_codes))
        elif expert_mode == "head":
            self.expert = None
            self.gain = None
            self.bias = nn.Parameter(torch.zeros(n_codes, n_heads))
        else:
            raise ValueError(expert_mode)
        self.alpha = nn.Parameter(torch.tensor(float(alpha_init)))
        # delayed activation: 0 -> 1 over ``warmup`` epochs so that the base
        # set encoder is fitted before the discrete bias starts to move the
        # attention logits; held at 1.0 at inference
        self.scale = 1.0
        self.warmup = 0

    @property
    def weight(self) -> torch.Tensor:
        return self.codebook.weight if self.use_vq else F.normalize(self.codes, dim=-1)

    def forward(self, x: torch.Tensor, mask: torch.Tensor):
        B, N, _ = x.shape
        codes = self.weight
        z = self.pair_proj(
            torch.cat([x.unsqueeze(2).expand(B, N, N, -1),
                       x.unsqueeze(1).expand(B, N, N, -1)], dim=-1)
        )
        cos = F.normalize(z, dim=-1) @ F.normalize(codes, dim=-1).t()
        pi = F.softmax(cos / self.tau, dim=-1)
        idx = cos.argmax(-1)

        if self.expert_mode == "mlp":
            delta = self.expert(
                torch.cat([z.unsqueeze(3).expand(B, N, N, self.n_codes, -1),
                           codes.view(1, 1, 1, self.n_codes, -1).expand(B, N, N, self.n_codes, -1)],
                          dim=-1)
            ).squeeze(-1)
        elif self.expert_mode == "linear":
            # [B, N, N, d] @ [d, K] -> [B, N, N, K]
            delta = z @ self.gain.weight.t() + self.gain.bias
        else:  # scalar / head: broadcast a K (x H) parameter vector over pairs
            ones = torch.ones(B, N, N, *([1] * self.bias.dim()),
                              device=z.device, dtype=z.dtype)
            delta = self.bias.view(1, 1, 1, *self.bias.shape) * ones
        if self.center:
            # a zero-mean correction over the codebook: at initialisation every
            # expert agrees, so the bias is exactly zero and the model starts as
            # PhysSet-LNP rather than at an arbitrary offset
            delta = delta - delta.mean(3, keepdim=True)

        per_head = delta.dim() == 5          # [B, N, N, K, H]
        if self.hard:
            oh = F.one_hot(pi.argmax(-1), self.n_codes).to(delta.dtype)
            bias = ((oh.unsqueeze(-1) * delta).sum(3) if per_head
                    else (oh * delta).sum(-1))
        elif self.mix == "logsumexp":
            lp = torch.log(pi + 1e-9)
            bias = (torch.logsumexp(lp.unsqueeze(-1) + self.alpha * delta, dim=3) if per_head
                    else torch.logsumexp(lp + self.alpha * delta, dim=-1))
        else:
            bias = (self.alpha * (pi.unsqueeze(-1) * delta).sum(3) if per_head
                    else self.alpha * (pi * delta).sum(-1))

        valid = ~(mask[:, :, None] | mask[:, None, :])
        diag = torch.eye(N, device=x.device, dtype=torch.bool)
        contact = valid & ~diag.unsqueeze(0)
        if self.schema_only:
            contact = contact & self._schema.to(x.device).unsqueeze(0)
        # [B, N, N] or [B, N, N, H]
        m = valid.to(bias.dtype)
        m = m.unsqueeze(-1) if bias.dim() == 4 else m
        bias = bias * m
        dmask = diag.view(1, N, N, *([1] * (bias.dim() - 3)))
        bias = bias.masked_fill(dmask, 0.0)
        # kept for the interpretability pass (scripts/mode_interpret.py); the
        # tensors are detached and never enter the graph
        self.last = {"pi": pi.detach(), "idx": idx.detach(), "valid": valid.detach()}
        if self.scale != 1.0:
            bias = bias * self.scale

        stats = {}
        if self.training:
            u = z[contact]
            pi_c = pi[contact]
            idx_c = idx[contact]
            if len(u):
                if self.use_vq:
                    self.codebook.ema_update(u, idx_c)
                    c = self.codebook.weight[idx_c]
                    stats["commit"] = (u - c.detach()).pow(2).mean()
                else:
                    c = codes[idx_c]
                    stats["commit"] = (u - c).pow(2).mean()
                pbar = pi_c.mean(0)
                stats["bal"] = (pbar * torch.log(pbar * self.n_codes + 1e-9)).sum()
                cn = F.normalize(self.weight, dim=-1)
                stats["orth"] = (cn @ cn.t()
                                 - torch.eye(self.n_codes, device=cn.device)).pow(2).mean()
                stats["usage"] = pbar.detach()
        return bias, stats


class RelModeModule(_ModeTrunk):
    """PhysSet-LNP whose attention logits carry discrete relation-mode biases."""

    def __init__(self, fp_dim: int, ctx_dim: int, desc_dim: int, n_heads: int = 6,
                 rel_n_codes: int = 16, rel_code_dim: int = 64, rel_tau: float = 0.2,
                 rel_alpha: float = 0.5, rel_mix: str = "logsumexp", rel_hard: bool = False,
                 rel_use_vq: bool = True, rel_center: bool = True,
                 rel_expert: str = "mlp", rel_use_ratio: bool = True,
                 rel_schema_only: bool = False, rel_warmup: int = 0,
                 lam_vq: float = 0.02, lam_bal: float = 0.02, lam_orth: float = 0.005,
                 use_rel_mode: bool = True, use_block: bool = False,
                 ctx_mode: str = "full", lam_reg: float = 1.0, **kw):
        rel_kw = dict(n_codes=rel_n_codes, code_dim=rel_code_dim, tau=rel_tau,
                      alpha_init=rel_alpha, mix=rel_mix, hard=rel_hard,
                      use_vq=rel_use_vq, center=rel_center, expert_mode=rel_expert,
                      n_heads=n_heads, schema_only=rel_schema_only)
        super().__init__(fp_dim=fp_dim, ctx_dim=ctx_dim, desc_dim=desc_dim,
                         enc_extra={"use_rel_mode": use_rel_mode, "rel_kw": rel_kw,
                                    "rel_use_ratio": rel_use_ratio}, **kw)
        out = self.enc.out_dim
        self.pred = nn.Sequential(nn.Linear(256, 64), nn.SiLU(), nn.Linear(64, 1))
        self.lam_vq, self.lam_bal, self.lam_orth = lam_vq, lam_bal, lam_orth
        self.rel_warmup, self._epoch = rel_warmup, 0
        # hybrid read-out: the same identity-free 398-d chemistry block that the
        # tree models consume is projected and concatenated with the set
        # representation before the head.  The representation is identical, so
        # this isolates the *read-out* as the source of the neural/tree gap.
        self.use_block = use_block
        if use_block:
            self.block_proj = nn.Sequential(
                nn.Linear(398, 192), nn.SiLU(), nn.Linear(192, 192)
            )
        # "full"  : the 109-d context as published (carries the study identity)
        # "coarse": only the fields shared across studies -- cargo type, model
        #           type/target, route, mixing, and the nine numeric features
        # "none"  : chemistry only
        self.ctx_mode = ctx_mode
        self.lam_reg = lam_reg

    def forward(self, batch):
        if self.enc.rel_mode is not None:
            self.enc.rel_mode.scale = (
                min(1.0, (self._epoch + 1) / self.rel_warmup) if self.rel_warmup else 1.0
            )
        if getattr(self, "ctx_mask", None) is not None:
            batch = {**batch, "ctx": batch["ctx"] * self.ctx_mask}
        h, feats, _ = self.encode(batch)
        stats = getattr(self.enc, "_rel_stats", None) or {}
        hh = h
        if self.use_block:
            hh = torch.cat([h, self.block_proj(self.block[batch["row"]])], dim=-1)
        return {"y_hat": self.pred(hh).squeeze(-1), "phys": self.phys_head(feats),
                "z": h, "feats": feats, "rel": stats}

    def compute_loss(self, batch, out, epoch=0, n_epochs=1):
        self._epoch = epoch
        reg = F.smooth_l1_loss(out["y_hat"], batch["y"])
        rank = self._rank_loss(out["y_hat"], batch)
        total = self.lam_reg * reg + self.lam_rank * rank
        logs = {"reg": float(reg.detach()), "rank": float(rank.detach())}
        rel = out["rel"]
        if rel:
            vq = (
                self.lam_vq * rel.get("commit", 0.0)
                + self.lam_bal * rel.get("bal", 0.0)
                + self.lam_orth * rel.get("orth", 0.0)
            )
            total = total + vq
            logs.update({k: float(v.detach()) for k, v in rel.items() if torch.is_tensor(v) and v.dim() == 0})
        total = self._aux_losses(batch, out["feats"], total, logs)
        return total, logs


class RelModeLNP(NeuralModel):
    name = "relmode"

    def build(self, store: FeatureStore, cfg: TrainConfig) -> nn.Module:
        kw = dict(self.kwargs)
        block = None
        if kw.get("use_block"):
            import numpy as np

            from .. import paths

            z = np.load(paths.CACHE_DIR / "schema_blocks.npz", allow_pickle=True)
            x = np.asarray(z["base"], dtype=np.float32)
            x = (x - x.mean(0)) / (x.std(0) + 1e-6)
            block = torch.from_numpy(x)
        module = RelModeModule(
            fp_dim=store.il_fp.shape[1], ctx_dim=store.ctx_dim,
            desc_dim=store.il_desc.shape[1], **kw
        )
        if block is not None:
            module.register_buffer("block", block)
            module.pred[0] = nn.Linear(256 + 192, 64)
            print(f"[block] hybrid read-out: {x.shape[1]} chemistry features + 256 learned")
        if kw.get("ctx_mode") in ("coarse", "none"):
            import numpy as _np

            from .. import paths as _paths
            from ..context import coarse_mask, load_vocab

            vocab = load_vocab(_paths.CACHE_DIR / "sample_features.npz")
            n = int(sum(len(v) for v in vocab.values())) + 9
            if kw["ctx_mode"] == "coarse":
                mask = torch.from_numpy(coarse_mask(vocab).astype(_np.float32))
                kept = int(mask.sum())
            else:
                mask = torch.zeros(n)
                kept = 0
            module.register_buffer("ctx_mask", mask)
            print(f"[ctx] {kw['ctx_mode']}: {kept}/{n} context features kept")
        return module

    def need(self) -> Sequence[str]:
        return ("y", "ctx", "ratios", "nodes", "nodes_prot", "helpers", "study_id",
                "cpp", "md_flag", "graph", "desc")