File size: 40,159 Bytes
b62faac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
"""Inkling2 Loop V20 trainable memory modules: stem-invariant contextual encoder and two-timescale gated-delta state."""

from __future__ import annotations

import math

import torch
from torch import nn
from torch.nn import functional as F


def _rms_norm(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
    return F.rms_norm(x.float(), (x.shape[-1],), eps=eps)


def _soft_rms_norm(x: torch.Tensor, eps: float = 0.05) -> torch.Tensor:
    """Zero-preserving, noise-safe soft RMS normalization for scale-invariant neural state readouts."""
    xf = x.float()
    return xf * (xf.pow(2).mean(dim=-1, keepdim=True) + eps).rsqrt()


def _apply_rope_1d(q: torch.Tensor, k: torch.Tensor, base: float = 10000.0):
    """Apply 1D rotary embeddings to [B, H, T, D] tensors (D even)."""
    seq_len, head_dim = q.shape[-2], q.shape[-1]
    half = head_dim // 2
    inv_freq = 1.0 / (
        base ** (torch.arange(0, half, device=q.device, dtype=torch.float32) / half)
    )
    pos = torch.arange(seq_len, device=q.device, dtype=torch.float32)
    freqs = torch.outer(pos, inv_freq)
    cos = freqs.cos()[None, None, :, :]
    sin = freqs.sin()[None, None, :, :]

    def rotate(x: torch.Tensor) -> torch.Tensor:
        x_f = x.float()
        x1, x2 = x_f[..., :half], x_f[..., half:]
        out = torch.cat((x1 * cos - x2 * sin, x2 * cos + x1 * sin), dim=-1)
        return out.to(x.dtype)

    return rotate(q), rotate(k)


class _HybridContextBlock(nn.Module):
    """Order-preserving causal short-conv + bidirectional RoPE self-attention + SwiGLU block."""

    def __init__(self, dim: int, num_heads: int, conv_kernel: int = 4):
        super().__init__()
        self.dim = dim
        self.num_heads = num_heads
        self.head_dim = dim // num_heads
        self.conv_kernel = conv_kernel

        self.dw_conv = nn.Conv1d(
            dim, dim, kernel_size=conv_kernel, groups=dim, bias=True
        )
        self.conv_gate = nn.Linear(dim, dim, bias=True)
        self.conv_out = nn.Linear(dim, dim, bias=False)

        self.q_proj = nn.Linear(dim, dim, bias=False)
        self.k_proj = nn.Linear(dim, dim, bias=False)
        self.v_proj = nn.Linear(dim, dim, bias=False)
        self.o_proj = nn.Linear(dim, dim, bias=False)

        ffn_dim = dim * 2
        self.ffn_gate_up = nn.Linear(dim, ffn_dim * 2, bias=False)
        self.ffn_down = nn.Linear(ffn_dim, dim, bias=False)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        # x: [B, T, D]
        bsz, seq_len, dim = x.shape
        dtype = self.q_proj.weight.dtype

        # 1. Causal depthwise short-conv for strict directional token-order sensitivity
        h = _rms_norm(x).to(dtype)
        padded = F.pad(h.transpose(1, 2), (self.conv_kernel - 1, 0))
        conv = self.dw_conv(padded).transpose(1, 2)
        x = x + self.conv_out(F.silu(conv) * self.conv_gate(h).sigmoid()).to(x.dtype)

        # 2. Bidirectional RoPE self-attention with QK RMSNorm
        h = _rms_norm(x).to(dtype)
        q = self.q_proj(h).view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
        k = self.k_proj(h).view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
        v = self.v_proj(h).view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
        q = _rms_norm(q).to(dtype)
        k = _rms_norm(k).to(dtype)
        q, k = _apply_rope_1d(q, k)
        attn = F.scaled_dot_product_attention(q, k, v, is_causal=False)
        attn = attn.transpose(1, 2).contiguous().view(bsz, seq_len, dim)
        x = x + self.o_proj(attn).to(x.dtype)

        # 3. SwiGLU FFN
        h = _rms_norm(x).to(dtype)
        gate, up = self.ffn_gate_up(h).chunk(2, dim=-1)
        x = x + self.ffn_down(F.silu(gate) * up).to(x.dtype)
        return x


def _pool_2d_windows(grid_tokens: torch.Tensor, rows: int, cols: int, out_r: int, out_c: int):
    """Pool [H, W, D] grid into true 2D rectangular windows returning (vectors, norm_boxes)."""
    out_r = min(out_r, rows)
    out_c = min(out_c, cols)
    r_edges = [round(i * rows / out_r) for i in range(out_r + 1)]
    c_edges = [round(j * cols / out_c) for j in range(out_c + 1)]
    vecs, boxes = [], []
    for ri in range(out_r):
        y0, y1 = r_edges[ri], r_edges[ri + 1]
        if y1 <= y0:
            continue
        for ci in range(out_c):
            x0, x1 = c_edges[ci], c_edges[ci + 1]
            if x1 <= x0:
                continue
            patch = grid_tokens[y0:y1, x0:x1].reshape(-1, grid_tokens.shape[-1])
            vecs.append(patch.mean(0))
            boxes.append([x0 / cols, y0 / rows, x1 / cols, y1 / rows])
    return vecs, boxes


class MemoryEncoderV20(nn.Module):
    """Stem-invariant 2-layer hybrid contextual encoder, 2D multi-scale grid pooler, and pre-prefill hop router."""

    ROUTE_NAMES = ("lexical", "semantic_order", "region_2d", "working_state", "relation_graph")

    def __init__(
        self,
        hidden_size: int,
        *,
        encoder_dim: int = 512,
        encoder_layers: int = 2,
        encoder_heads: int = 8,
        conv_kernel: int = 4,
        key_dim: int = 256,
        region_dim: int = 128,
        text_regions: int = 16,
    ):
        super().__init__()
        self.hidden_size = hidden_size
        self.encoder_dim = encoder_dim
        self.key_dim = key_dim
        self.region_dim = region_dim
        self.text_regions = text_regions

        self.stem_in = nn.Linear(hidden_size, encoder_dim, bias=False)
        self.modality_embed = nn.Embedding(3, encoder_dim)  # 0=text, 1=image, 2=query_cls
        self.query_cls = nn.Parameter(torch.empty(1, 1, encoder_dim))
        self.blocks = nn.ModuleList(
            [
                _HybridContextBlock(encoder_dim, encoder_heads, conv_kernel=conv_kernel)
                for _ in range(encoder_layers)
            ]
        )

        # Event indexing heads (contextual order + 2D multi-scale regions)
        self.order_pool_query = nn.Parameter(torch.empty(encoder_dim))
        self.event_key_head = nn.Linear(encoder_dim, key_dim, bias=False)
        self.order_tail_proj = nn.Linear(encoder_dim, key_dim, bias=False)
        self.text_slot_queries = nn.Parameter(torch.empty(text_regions, encoder_dim))
        self.region_key_head = nn.Linear(encoder_dim, region_dim, bias=False)

        # Pre-prefill query & adaptive 5-route gating heads
        self.query_sem_head = nn.Linear(encoder_dim, key_dim, bias=False)
        self.query_region_head = nn.Linear(encoder_dim, region_dim, bias=False)
        self.route_gate = nn.Linear(encoder_dim, len(self.ROUTE_NAMES))
        self.abstain_head = nn.Linear(encoder_dim, 1)

        # Lightweight cross-attention hop reformulator + 2D visual crop zoom head
        self.hop_q = nn.Linear(encoder_dim, encoder_dim, bias=False)
        self.hop_k = nn.Linear(key_dim, encoder_dim, bias=False)
        self.hop_v = nn.Linear(key_dim, encoder_dim, bias=False)
        self.hop_out = nn.Linear(encoder_dim, encoder_dim, bias=False)
        self.visual_zoom_head = nn.Linear(encoder_dim, region_dim, bias=False)
        self.visual_zoom_gate = nn.Linear(encoder_dim, 1)

    @torch.no_grad()
    def reset_parameters(self):
        for mod in self.modules():
            if isinstance(mod, (nn.Linear, nn.Conv1d)):
                nn.init.normal_(mod.weight, std=0.02)
                if mod.bias is not None:
                    nn.init.zeros_(mod.bias)
            elif isinstance(mod, nn.Embedding):
                nn.init.normal_(mod.weight, std=0.02)
        nn.init.normal_(self.query_cls, std=0.02)
        nn.init.normal_(self.order_pool_query, std=0.02)
        nn.init.normal_(self.text_slot_queries, std=0.02)
        # Zero-init residual hop updater so step-0 hop2 matches hop1 cleanly
        nn.init.zeros_(self.hop_out.weight)
        # Mild conservative initial zoom bias (only crop when triggered or trained)
        nn.init.constant_(self.visual_zoom_gate.bias, -1.0)

    def _modality_ids(self, length: int, spans, device) -> torch.Tensor:
        ids = torch.zeros(length, dtype=torch.long, device=device)
        if spans:
            for span in spans:
                kind = span.get("kind")
                if kind in ("image", "projected_image") and "start" in span and "end" in span:
                    start = max(0, int(span["start"]))
                    end = min(length, int(span["end"]))
                    if end > start:
                        ids[start:end] = 1
        return ids

    def contextualize(self, states: torch.Tensor, spans=None, *, append_cls: bool = False) -> torch.Tensor:
        """Encode [T, hidden_size] stem sequence into [T (+1), encoder_dim] contextual vectors."""
        if states.ndim != 2 or states.shape[0] == 0:
            raise ValueError("MemoryEncoderV20 expects nonempty [tokens, hidden_size] states")
        dev = self.stem_in.weight.device
        dtype = self.stem_in.weight.dtype
        x = self.stem_in(_rms_norm(states.to(dev)).to(dtype))
        mod_ids = self._modality_ids(states.shape[0], spans, dev)
        x = x + self.modality_embed(mod_ids).to(dtype)
        x = x.unsqueeze(0)
        if append_cls:
            cls_tok = self.query_cls.to(device=dev, dtype=dtype) + self.modality_embed.weight[2].to(dtype)
            x = torch.cat((x, cls_tok), dim=1)
        for block in self.blocks:
            x = block(x)
        return x.squeeze(0)

    def _extract_regions(self, u: torch.Tensor, spans, head: nn.Linear, *, max_text_regions: int | None = None):
        """Extract 2D multi-scale image regions (4x4 + 2x2 + global) and contextual text phrase regions."""
        max_text = self.text_regions if max_text_regions is None else max_text_regions
        region_vecs = []
        region_boxes = []
        region_meta = []
        if not spans:
            spans = [{"kind": "text", "start": 0, "end": u.shape[0]}]

        for span in spans:
            kind = span.get("kind")
            if "start" not in span or "end" not in span:
                continue
            start, end = max(0, int(span["start"])), min(u.shape[0], int(span["end"]))
            if end <= start:
                continue
            sub = u[start:end]
            if kind == "text":
                slots = min(max_text, sub.shape[0])
                parts = torch.tensor_split(sub, slots, dim=0)
                offset = start
                for query, part in zip(self.text_slot_queries.unbind(0)[:slots], parts):
                    score = (part.float() @ query.float()) * (self.encoder_dim ** -0.5)
                    pooled = score.softmax(0).to(part.dtype) @ part
                    region_vecs.append(pooled)
                    region_boxes.append([0.0, 0.0, 1.0, 1.0])
                    region_meta.append(
                        {
                            "kind": "text",
                            "scale": "phrase",
                            "token_span": [offset, offset + part.shape[0]],
                        }
                    )
                    offset += part.shape[0]
            elif kind in ("image", "projected_image"):
                grid = span.get("grid")
                image_index = span.get("image", span.get("index", 0))
                if grid and len(grid) == 3 and math.prod(grid) == sub.shape[0]:
                    frames, rows, cols = (int(grid[0]), int(grid[1]), int(grid[2]))
                    grid_tok = sub.view(frames, rows, cols, self.encoder_dim).mean(0)
                    # Fine 4x4 2D grid (up to 16)
                    fine_v, fine_b = _pool_2d_windows(grid_tok, rows, cols, 4, 4)
                    for vec, box in zip(fine_v, fine_b):
                        region_vecs.append(vec)
                        region_boxes.append(box)
                        region_meta.append(
                            {"kind": kind, "scale": "4x4", "image_index": image_index, "norm_box": box}
                        )
                    # Mid-scale 2x2 quadrants (up to 4, only when coarser than 4x4 and finer than 1x1)
                    if rows >= 2 or cols >= 2:
                        mid_v, mid_b = _pool_2d_windows(grid_tok, rows, cols, 2, 2)
                        for vec, box in zip(mid_v, mid_b):
                            if box not in fine_b:
                                region_vecs.append(vec)
                                region_boxes.append(box)
                                region_meta.append(
                                    {
                                        "kind": kind,
                                        "scale": "2x2",
                                        "image_index": image_index,
                                        "norm_box": box,
                                    }
                                )
                    # Global 1x1 image descriptor
                    region_vecs.append(grid_tok.reshape(-1, self.encoder_dim).mean(0))
                    region_boxes.append([0.0, 0.0, 1.0, 1.0])
                    region_meta.append(
                        {
                            "kind": kind,
                            "scale": "1x1",
                            "image_index": image_index,
                            "norm_box": [0.0, 0.0, 1.0, 1.0],
                        }
                    )
                else:
                    # Fallback if grid metadata absent
                    region_vecs.append(sub.mean(0))
                    region_boxes.append([0.0, 0.0, 1.0, 1.0])
                    region_meta.append(
                        {
                            "kind": kind,
                            "scale": "1x1",
                            "image_index": image_index,
                            "norm_box": [0.0, 0.0, 1.0, 1.0],
                        }
                    )

        if not region_vecs:
            region_vecs = [u.mean(0)]
            region_boxes = [[0.0, 0.0, 1.0, 1.0]]
            region_meta = [{"kind": "text", "scale": "global", "token_span": [0, u.shape[0]]}]

        stacked = torch.stack(region_vecs, dim=0)
        projected = F.normalize(head(_rms_norm(stacked).to(head.weight.dtype)).float(), dim=-1)
        return projected, region_boxes, region_meta

    def encode_event(self, states: torch.Tensor, spans=None) -> dict:
        """Encode an immutable source event into contextualized global order key, 2D regions, and token states."""
        u = self.contextualize(states, spans, append_cls=False)
        dtype = self.event_key_head.weight.dtype
        weights = (u.float() @ self.order_pool_query.float()) * (self.encoder_dim ** -0.5)
        pooled = weights.softmax(0).to(dtype) @ u.to(dtype)
        global_vec = self.event_key_head(_rms_norm(pooled).to(dtype)).float()
        tail_vec = self.order_tail_proj(_rms_norm(u[-1]).to(dtype)).float()
        key = F.normalize(global_vec + tail_vec, dim=-1)
        regions, boxes, meta = self._extract_regions(u, spans, self.region_key_head)
        return {
            "key": key,
            "regions": regions,
            "region_boxes": boxes,
            "region_meta": meta,
            "contextual": u,
            "stem": states.to(u.device),
        }

    def encode_query(
        self,
        states: torch.Tensor,
        spans=None,
        *,
        state: torch.Tensor | None = None,
        neural_state: "NeuralStateV20 | None" = None,
    ) -> dict:
        """Encode user query (text and/or query images) before main LLM prefill."""
        u_all = self.contextualize(states, spans, append_cls=True)
        u_tokens, q_cls = u_all[:-1], u_all[-1]
        dtype = self.query_sem_head.weight.dtype
        q_sem = F.normalize(self.query_sem_head(_rms_norm(q_cls).to(dtype)).float(), dim=-1)

        has_image = bool(
            spans and any(s.get("kind") in ("image", "projected_image") for s in spans)
        )
        # Keep query region vectors expressive (up to 8 text phrase regions for multi-clause queries, 16 max total)
        q_regions, q_boxes, q_meta = self._extract_regions(
            u_tokens, spans, self.query_region_head, max_text_regions=8 if not has_image else 2
        )
        if q_regions.shape[0] > 16:
            # Prefer visual 2D fine/mid patches + text queries
            img_idx = [i for i, m in enumerate(q_meta) if m["kind"] != "text"]
            txt_idx = [i for i, m in enumerate(q_meta) if m["kind"] == "text"]
            keep = (img_idx[:14] + txt_idx[:2])[:16]
            q_regions = q_regions[keep]
            q_boxes = [q_boxes[i] for i in keep]
            q_meta = [q_meta[i] for i in keep]

        route_logits = self.route_gate(_rms_norm(q_cls).to(dtype)).float()
        route_weights = route_logits.softmax(dim=-1)
        abstain_logit = self.abstain_head(_rms_norm(q_cls).to(dtype)).float().squeeze(-1)

        q_state = None
        if state is not None and neural_state is not None:
            delta_q = neural_state.query_search(q_cls, state)
            q_state = F.normalize(q_sem + delta_q.float(), dim=-1)

        zoom_query = F.normalize(
            self.visual_zoom_head(_rms_norm(q_cls).to(dtype)).float(), dim=-1
        )
        zoom_prob = self.visual_zoom_gate(_rms_norm(q_cls).to(dtype)).float().sigmoid().squeeze(-1)

        return {
            "q_cls": q_cls,
            "q_sem": q_sem,
            "q_regions": q_regions,
            "q_boxes": q_boxes,
            "q_meta": q_meta,
            "q_state": q_state,
            "route_logits": route_logits,
            "route_weights": route_weights,
            "abstain_logit": abstain_logit,
            "zoom_query": zoom_query,
            "zoom_prob": zoom_prob,
            "has_query_image": has_image,
        }

    def reformulate_hop(self, q_cls: torch.Tensor, hop_keys: torch.Tensor) -> dict:
        """Refine query representation using Hop-1 retrieved event keys (< 1 ms, pre-prefill)."""
        dtype = self.hop_q.weight.dtype
        if hop_keys.ndim == 2 and hop_keys.shape[0] > 0:
            q = self.hop_q(_rms_norm(q_cls).to(dtype))
            k = self.hop_k(hop_keys.to(device=q.device, dtype=dtype))
            v = self.hop_v(hop_keys.to(device=q.device, dtype=dtype))
            attn = ((q.float() @ k.float().T) * (self.encoder_dim ** -0.5)).softmax(dim=-1)
            ctx = attn.to(dtype) @ v
            q_next = q_cls + self.hop_out(ctx).to(q_cls.dtype)
        else:
            q_next = q_cls
        q_sem = F.normalize(self.query_sem_head(_rms_norm(q_next).to(dtype)).float(), dim=-1)
        zoom_query = F.normalize(self.visual_zoom_head(_rms_norm(q_next).to(dtype)).float(), dim=-1)
        zoom_prob = self.visual_zoom_gate(_rms_norm(q_next).to(dtype)).float().sigmoid().squeeze(-1)
        return {
            "q_cls": q_next,
            "q_sem": q_sem,
            "zoom_query": zoom_query,
            "zoom_prob": zoom_prob,
        }


class NeuralStateV20(nn.Module):
    """Two-timescale [H_s, D_k, D_v] Gated Delta-Product memory with chunkwise WY writes and static-shape loop readout."""

    def __init__(
        self,
        hidden_size: int,
        *,
        encoder_dim: int = 512,
        key_dim: int = 256,
        state_heads: int = 16,
        fast_heads: int = 8,
        state_key_dim: int = 128,
        state_value_dim: int = 128,
        chunk_size: int = 64,
        num_readout_sites: int = 2,
        max_pass_embeddings: int = 10,
        use_stem_value_bypass: bool = False,
    ):
        super().__init__()
        self.hidden_size = hidden_size
        self.encoder_dim = encoder_dim
        self.key_dim = key_dim
        self.state_heads = state_heads
        self.fast_heads = fast_heads
        self.slow_heads = state_heads - fast_heads
        self.state_key_dim = state_key_dim
        self.state_value_dim = state_value_dim
        self.chunk_size = chunk_size
        self.num_readout_sites = num_readout_sites
        self.max_pass_embeddings = max_pass_embeddings
        self.use_stem_value_bypass = bool(use_stem_value_bypass)

        # Token-level chunkwise Gated Delta-Product writer projections
        self.write_k = nn.Linear(encoder_dim, state_heads * state_key_dim, bias=False)
        self.write_v = nn.Linear(encoder_dim, state_heads * state_value_dim, bias=False)
        self.write_beta = nn.Linear(encoder_dim, state_heads, bias=True)
        self.write_gamma = nn.Linear(encoder_dim, state_heads, bias=True)

        # V20-v3 direct gated lexical stem bypass into associative values (preserves verbatim codes/names/dates)
        if self.use_stem_value_bypass:
            self.stem_v_proj = nn.Linear(hidden_size, state_heads * state_value_dim, bias=False)
            self.stem_v_gate = nn.Linear(encoder_dim, state_heads, bias=True)
        else:
            self.stem_v_proj = None
            self.stem_v_gate = None

        # Associative retrieval query head (pre-prefill working query from M_fast + M_slow)
        self.state_search_q = nn.Linear(encoder_dim, state_heads * state_key_dim, bias=False)
        self.state_search_out = nn.Linear(state_heads * state_value_dim, key_dim, bias=False)

        # Dual-site static-shape loop readout (e.g., Layer 11 & Layer 17, pass-agnostic for P=1..10)
        self.site_q_proj = nn.ModuleList(
            [nn.Linear(hidden_size, state_heads * state_key_dim, bias=False) for _ in range(num_readout_sites)]
        )
        self.site_pass_mod = nn.ParameterList(
            [
                nn.Parameter(torch.ones(max_pass_embeddings, state_heads, state_key_dim))
                for _ in range(num_readout_sites)
            ]
        )
        self.site_gate = nn.ModuleList(
            [nn.Linear(hidden_size, state_heads, bias=True) for _ in range(num_readout_sites)]
        )
        self.site_out_proj = nn.ModuleList(
            [nn.Linear(state_heads * state_value_dim, hidden_size, bias=False) for _ in range(num_readout_sites)]
        )
        # Shared learnable absence representations: 0=no_external_support, 1=read_declined, 2=searched_empty
        self.absence_table = nn.Parameter(torch.empty(3, state_heads, state_value_dim))

    @torch.no_grad()
    def reset_parameters(self):
        for mod in self.modules():
            if isinstance(mod, nn.Linear):
                nn.init.normal_(mod.weight, std=0.02)
                if mod.bias is not None:
                    nn.init.zeros_(mod.bias)
        # Responsive write gate and log-spaced multi-timescale retention horizons:
        # - fast heads (0..fast_heads-1): bias 3.0..6.8 (gamma ~0.953..0.9989, 15..630 tok half-life)
        # - slow/long heads (fast_heads..state_heads-1): bias 7.2..12.0 (gamma ~0.99925..0.999994, 1K..115K+ tok half-life)
        nn.init.constant_(self.write_beta.bias, -1.5)
        if self.fast_heads > 1:
            fast_init = torch.linspace(3.0, 6.8, self.fast_heads, device=self.write_gamma.bias.device)
        else:
            fast_init = torch.full((self.fast_heads,), 4.5, device=self.write_gamma.bias.device)
        if self.slow_heads > 1:
            slow_init = torch.linspace(7.2, 12.0, self.slow_heads, device=self.write_gamma.bias.device)
        else:
            slow_init = torch.full((self.slow_heads,), 9.0, device=self.write_gamma.bias.device)
        self.write_gamma.bias[: self.fast_heads].copy_(fast_init)
        self.write_gamma.bias[self.fast_heads :].copy_(slow_init)
        if self.stem_v_gate is not None:
            nn.init.zeros_(self.stem_v_gate.weight)
            nn.init.constant_(self.stem_v_gate.bias, -2.0)
        for mod in self.site_pass_mod:
            nn.init.ones_(mod)
        # Zero-init output projections so step-0 V20 is bit-identical to source backbone
        nn.init.zeros_(self.state_search_out.weight)
        for out_proj in self.site_out_proj:
            nn.init.zeros_(out_proj.weight)
        nn.init.normal_(self.absence_table, std=0.02)

    def zero_state(self, batch_size: int | None = None, *, device=None, dtype=torch.float32) -> torch.Tensor:
        shape = (self.state_heads, self.state_key_dim, self.state_value_dim)
        if batch_size is not None:
            shape = (batch_size,) + shape
        return torch.zeros(shape, device=device, dtype=dtype)

    def _project_writes(self, u: torch.Tensor, stem_states: torch.Tensor | None = None):
        dtype = self.write_k.weight.dtype
        dev = self.write_k.weight.device
        h = _rms_norm(u.to(dev)).to(dtype)
        k = F.normalize(
            self.write_k(h).float().view(-1, self.state_heads, self.state_key_dim), dim=-1
        )
        v_raw = self.write_v(h).float().view(-1, self.state_heads, self.state_value_dim)
        if (
            self.use_stem_value_bypass
            and self.stem_v_proj is not None
            and self.stem_v_gate is not None
            and stem_states is not None
            and stem_states.shape[0] == u.shape[0]
        ):
            hs = _rms_norm(stem_states.to(dev)).to(self.stem_v_proj.weight.dtype)
            sv = self.stem_v_proj(hs).float().view(-1, self.state_heads, self.state_value_dim)
            sg = self.stem_v_gate(h).float().sigmoid().unsqueeze(-1)  # [T, H, 1]
            v_raw = v_raw + sg * sv
        # Unit-RMS bounded values (GDN-2 style): avoids tanh saturation while keeping state norm strictly bounded
        v = _rms_norm(v_raw)
        beta = self.write_beta(h).float().sigmoid()  # [T, H]
        gamma = self.write_gamma(h).float().sigmoid().clamp(min=1e-4, max=1.0)  # [T, H]
        return k, v, beta, gamma

    @staticmethod
    def _chunk_gated_delta(
        m: torch.Tensor,
        k: torch.Tensor,
        v: torch.Tensor,
        beta: torch.Tensor,
        gamma: torch.Tensor,
    ) -> torch.Tensor:
        """Exact WY parallel update for one chunk: M_t = gamma_t (I - beta_t k_t k_t^T) M_{t-1} + beta_t k_t v_t^T.

        m: [H, D_k, D_v], k: [H, C, D_k], v: [H, C, D_v], beta: [H, C], gamma: [H, C]
        """
        heads, chunk_len, _ = k.shape
        device = m.device
        log_g = gamma.clamp_min(1e-6).log()  # [H, C] <= 0
        cum_g = log_g.cumsum(dim=-1)  # [H, C] <= 0

        # Strictly lower-triangular decay matrix: diff[t, s] = G_t - G_s <= 0 for t > s
        diff = cum_g.unsqueeze(-1) - cum_g.unsqueeze(-2)  # [H, C, C]
        tril_mask = torch.tril(
            torch.ones(chunk_len, chunk_len, device=device, dtype=torch.bool), diagonal=-1
        )
        decay_pair = torch.where(
            tril_mask, diff.clamp(min=-60.0, max=0.0).exp(), torch.zeros_like(diff)
        )
        gram = torch.bmm(k, k.transpose(1, 2))  # [H, C, C]
        lower = beta.unsqueeze(-1) * decay_pair * gram
        eye = torch.eye(chunk_len, device=device, dtype=torch.float32).unsqueeze(0)

        exp_g = cum_g.clamp(min=-60.0, max=0.0).exp()  # [H, C]
        km0 = torch.bmm(k, m)  # [H, C, D_v]
        rhs = beta.unsqueeze(-1) * v - (beta * exp_g).unsqueeze(-1) * km0  # [H, C, D_v]

        # Exact triangular solve: (I + L) U = RHS
        u = torch.linalg.solve_triangular(eye + lower, rhs, upper=False, unitriangular=True)

        # M_C = exp(G_C) * M_0 + sum_{s=1..C} exp(G_C - G_s) k_s u_s^T
        end_g = cum_g[:, -1:]  # [H, 1]
        tail_decay = (end_g - cum_g).clamp(min=-60.0, max=0.0).exp()  # [H, C]
        scaled_k = k * tail_decay.unsqueeze(-1)  # [H, C, D_k]
        m_next = end_g.clamp(min=-60.0, max=0.0).exp().unsqueeze(-1) * m + torch.bmm(
            scaled_k.transpose(1, 2), u
        )
        return m_next

    def advance_sequence(
        self,
        state: torch.Tensor,
        u: torch.Tensor,
        *,
        stem_states: torch.Tensor | None = None,
        target: str = "both",
        chunk_size: int | None = None,
    ) -> torch.Tensor:
        """Advance two-timescale [H_s, D_k, D_v] state over contextual token sequence u: [T, encoder_dim]."""
        if state.shape != (self.state_heads, self.state_key_dim, self.state_value_dim):
            raise ValueError(
                f"Expected state shape {(self.state_heads, self.state_key_dim, self.state_value_dim)}, got {tuple(state.shape)}"
            )
        if target not in ("fast", "slow", "both"):
            raise ValueError("target must be 'fast', 'slow', or 'both'")
        if u.shape[0] == 0:
            return state

        c_size = self.chunk_size if chunk_size is None else int(chunk_size)
        k_all, v_all, beta_all, gamma_all = self._project_writes(u, stem_states=stem_states)
        m = state.to(device=k_all.device, dtype=torch.float32)

        if target == "fast":
            head_slice = slice(0, self.fast_heads)
        elif target == "slow":
            head_slice = slice(self.fast_heads, self.state_heads)
        else:
            head_slice = slice(0, self.state_heads)

        sub_m = m[head_slice]
        k_sub = k_all[:, head_slice, :].transpose(0, 1).contiguous()  # [H_sub, T, D_k]
        v_sub = v_all[:, head_slice, :].transpose(0, 1).contiguous()  # [H_sub, T, D_v]
        b_sub = beta_all[:, head_slice].transpose(0, 1).contiguous()  # [H_sub, T]
        g_sub = gamma_all[:, head_slice].transpose(0, 1).contiguous()  # [H_sub, T]

        total = k_sub.shape[1]
        for start in range(0, total, c_size):
            stop = min(start + c_size, total)
            sub_m = self._chunk_gated_delta(
                sub_m,
                k_sub[:, start:stop, :],
                v_sub[:, start:stop, :],
                b_sub[:, start:stop],
                g_sub[:, start:stop],
            )

        if target == "fast":
            return torch.cat((sub_m, m[self.fast_heads :]), dim=0)
        if target == "slow":
            return torch.cat((m[: self.fast_heads], sub_m), dim=0)
        return sub_m

    def advance_sequence_sequential(
        self,
        state: torch.Tensor,
        u: torch.Tensor,
        *,
        stem_states: torch.Tensor | None = None,
        target: str = "fast",
    ) -> torch.Tensor:
        """Reference token-by-token Gated Delta-Product recurrence (for exactness tests)."""
        k_all, v_all, beta_all, gamma_all = self._project_writes(u, stem_states=stem_states)
        m = state.to(device=k_all.device, dtype=torch.float32).clone()
        head_slice = (
            slice(0, self.fast_heads)
            if target == "fast"
            else slice(self.fast_heads, self.state_heads)
            if target == "slow"
            else slice(0, self.state_heads)
        )
        sub_m = m[head_slice]
        for t in range(u.shape[0]):
            kt = k_all[t, head_slice]  # [H, D_k]
            vt = v_all[t, head_slice]  # [H, D_v]
            bt = beta_all[t, head_slice][:, None, None]
            gt = gamma_all[t, head_slice][:, None, None]
            proj = torch.einsum("hd,hdv->hv", kt, sub_m)
            sub_m = gt * (sub_m - bt * kt.unsqueeze(-1) * proj.unsqueeze(-2)) + (
                bt * kt.unsqueeze(-1) * vt.unsqueeze(-2)
            )
        if target == "fast":
            return torch.cat((sub_m, m[self.fast_heads :]), dim=0)
        if target == "slow":
            return torch.cat((m[: self.fast_heads], sub_m), dim=0)
        return sub_m

    def query_search(self, q_cls: torch.Tensor, state: torch.Tensor) -> torch.Tensor:
        """Read [H_s, D_k, D_v] state from pre-prefill q_cls to augment semantic search."""
        dtype = self.state_search_q.weight.dtype
        q = F.normalize(
            self.state_search_q(_rms_norm(q_cls.to(self.state_search_q.weight.device)).to(dtype))
            .float()
            .view(self.state_heads, self.state_key_dim),
            dim=-1,
        )
        m = state.to(device=q.device, dtype=torch.float32)
        read = _soft_rms_norm(torch.einsum("hd,hdv->hv", q, m)).reshape(-1)
        return self.state_search_out(F.silu(read).to(self.state_search_out.weight.dtype)).float()

    def readout_state(
        self,
        hidden_states: torch.Tensor,
        state: torch.Tensor,
        *,
        site_idx: int,
        pass_idx: int,
        active_mask: torch.Tensor | None = None,
        absence_codes: torch.Tensor | None = None,
    ) -> torch.Tensor:
        """Static-shape CUDA-graph-safe readout from [B, H_s, D_k, D_v] into loop hidden states [B, L, H]."""
        bsz, seq_len, _ = hidden_states.shape
        q_proj = self.site_q_proj[site_idx]
        out_proj = self.site_out_proj[site_idx]
        gate_proj = self.site_gate[site_idx]
        pass_slot = min(max(int(pass_idx), 0), self.max_pass_embeddings - 1)
        pass_mod = self.site_pass_mod[site_idx][pass_slot]  # [H_s, D_k]

        dev = q_proj.weight.device
        w_dtype = q_proj.weight.dtype
        normed = _rms_norm(hidden_states.to(dev)).to(w_dtype)

        # Static batched query projection + per-pass modulation
        q = q_proj(normed).float().view(bsz, seq_len, self.state_heads, self.state_key_dim)
        q = F.normalize(q * pass_mod.float()[None, None, :, :], dim=-1)

        m = state.to(device=dev, dtype=torch.float32)
        if m.ndim == 3:
            m = m.unsqueeze(0).expand(bsz, -1, -1, -1)
        elif m.shape[0] == 1 and bsz > 1:
            m = m.expand(bsz, -1, -1, -1)
        elif m.shape[0] != bsz and bsz % m.shape[0] == 0:
            m = m.repeat_interleave(bsz // m.shape[0], dim=0)

        # Pure batched matrix multiply (CUDA-graph safe, zero Python branching)
        # q_bmm: [B * H_s, L, D_k] @ m_bmm: [B * H_s, D_k, D_v] -> [B * H_s, L, D_v]
        q_bmm = q.permute(0, 2, 1, 3).reshape(bsz * self.state_heads, seq_len, self.state_key_dim)
        m_bmm = m.reshape(bsz * self.state_heads, self.state_key_dim, self.state_value_dim)
        read = torch.bmm(q_bmm, m_bmm).view(bsz, self.state_heads, seq_len, self.state_value_dim)
        read = read.permute(0, 2, 1, 3)  # [B, L, H_s, D_v]

        # Optional branchless absence substitution (preserves answer-loss gradients on empty retrieval)
        if absence_codes is not None:
            codes = absence_codes.to(device=dev, dtype=torch.long)
            if codes.shape[0] == 1 and bsz > 1:
                codes = codes.expand(bsz)
            elif codes.shape[0] != bsz and bsz % codes.shape[0] == 0:
                codes = codes.repeat_interleave(bsz // codes.shape[0], dim=0)
            is_absent = (codes >= 0).view(bsz, 1, 1, 1)
            safe_codes = codes.clamp(min=0, max=2)
            absent_vec = self.absence_table.float().index_select(0, safe_codes)  # [B, H_s, D_v]
            read = torch.where(is_absent, absent_vec.unsqueeze(1).expand_as(read), read)

        # Scale-invariant soft-RMS readout + per-head bounded tanh gate (fast vs long-horizon heads)
        read_normed = _soft_rms_norm(read)  # [B, L, H_s, D_v]
        head_gate = torch.tanh(gate_proj(normed).float()).unsqueeze(-1)  # [B, L, H_s, 1]
        gated = (F.silu(read_normed) * head_gate).reshape(bsz, seq_len, self.state_heads * self.state_value_dim)
        delta = out_proj(gated.to(out_proj.weight.dtype))

        if active_mask is not None:
            mask = active_mask.to(device=dev, dtype=delta.dtype)
            if mask.ndim == 1:
                mask = mask.view(-1, 1, 1)
            elif mask.ndim == 2:
                mask = mask.unsqueeze(-1)
            if mask.shape[0] == 1 and bsz > 1:
                mask = mask.expand(bsz, -1, -1)
            elif mask.shape[0] != bsz and bsz % mask.shape[0] == 0:
                mask = mask.repeat_interleave(bsz // mask.shape[0], dim=0)
            delta = delta * mask

        return hidden_states + delta.to(device=hidden_states.device, dtype=hidden_states.dtype)


class Inkling2V20MemoryComponents(nn.Module):
    """All V20 trainable memory parameters (external to frozen stem and backbone layers)."""

    def __init__(self, text_config):
        super().__init__()
        hidden_size = int(text_config.hidden_size)
        self.key_dim = int(text_config.v20_key_dim)
        self.region_dim = int(text_config.v20_region_dim)
        self.readout_layer_offsets = tuple(int(x) for x in text_config.v20_readout_layer_offsets)
        self.encoder = MemoryEncoderV20(
            hidden_size,
            encoder_dim=int(text_config.v20_encoder_dim),
            encoder_layers=int(text_config.v20_encoder_layers),
            encoder_heads=int(text_config.v20_encoder_heads),
            conv_kernel=int(text_config.v20_encoder_conv_kernel),
            key_dim=self.key_dim,
            region_dim=self.region_dim,
            text_regions=int(text_config.v20_text_regions),
        )
        self.neural_state = NeuralStateV20(
            hidden_size,
            encoder_dim=int(text_config.v20_encoder_dim),
            key_dim=self.key_dim,
            state_heads=int(text_config.v20_state_heads),
            fast_heads=int(text_config.v20_state_fast_heads),
            state_key_dim=int(text_config.v20_state_key_dim),
            state_value_dim=int(text_config.v20_state_value_dim),
            chunk_size=int(text_config.v20_state_chunk_size),
            num_readout_sites=len(self.readout_layer_offsets),
            max_pass_embeddings=int(text_config.v20_max_pass_embeddings),
            use_stem_value_bypass=bool(getattr(text_config, "v20_use_stem_value_bypass", False)),
        )
        self.reset_memory_parameters()

    @torch.no_grad()
    def reset_memory_parameters(self):
        self.encoder.reset_parameters()
        self.neural_state.reset_parameters()

    def encode_event(self, states: torch.Tensor, spans=None) -> dict:
        return self.encoder.encode_event(states, spans)

    def encode_query(self, states: torch.Tensor, spans=None, *, state: torch.Tensor | None = None) -> dict:
        return self.encoder.encode_query(
            states, spans, state=state, neural_state=self.neural_state
        )

    def reformulate_hop(self, q_cls: torch.Tensor, hop_keys: torch.Tensor) -> dict:
        return self.encoder.reformulate_hop(q_cls, hop_keys)

    def advance_state(
        self,
        state: torch.Tensor,
        contextual_u: torch.Tensor,
        *,
        stem_states: torch.Tensor | None = None,
        target: str = "both",
        chunk_size: int | None = None,
    ) -> torch.Tensor:
        return self.neural_state.advance_sequence(
            state,
            contextual_u,
            stem_states=stem_states,
            target=target,
            chunk_size=chunk_size,
        )

    def readout_state(
        self,
        hidden_states: torch.Tensor,
        state: torch.Tensor,
        *,
        site_idx: int,
        pass_idx: int,
        active_mask: torch.Tensor | None = None,
        absence_codes: torch.Tensor | None = None,
    ) -> torch.Tensor:
        return self.neural_state.readout_state(
            hidden_states,
            state,
            site_idx=site_idx,
            pass_idx=pass_idx,
            active_mask=active_mask,
            absence_codes=absence_codes,
        )

    def encoder_state_dict(self) -> dict[str, torch.Tensor]:
        return {k: v for k, v in self.state_dict().items() if k.startswith("encoder.")}

    def state_writer_state_dict(self) -> dict[str, torch.Tensor]:
        prefixes = (
            "encoder.stem_in.",
            "encoder.modality_embed.",
            "encoder.blocks.",
            "neural_state.write_",
            "neural_state.stem_v_",
        )
        return {
            k: v
            for k, v in self.state_dict().items()
            if any(k.startswith(p) for p in prefixes)
        }

    def train_stage(self, stage: str):
        """Enable only the requested V20 training stage parameters."""
        if stage not in ("encoder", "state", "readout", "joint", "all"):
            raise ValueError("stage must be 'encoder', 'state', 'readout', 'joint', or 'all'")
        self.requires_grad_(False)
        if stage in ("encoder", "joint", "all"):
            self.encoder.requires_grad_(True)
        if stage in ("state", "joint", "all"):
            self.neural_state.requires_grad_(True)
        if stage == "readout":
            for attr in ("site_q_proj", "site_pass_mod", "site_gate", "site_out_proj"):
                getattr(self.neural_state, attr).requires_grad_(True)
            self.neural_state.absence_table.requires_grad_(True)
        return self