File size: 46,984 Bytes
b312080
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
"""
DocSEAM: Document Selective Enrichment via Anchored Masking.

A small, injectable module placed after a pretrained VLM's vision encoder
(post-merger) and before the language model. It fuses each page with both
neighbors through asymmetric, salience-gated cross-page attention.

Key design:
- Joint masked self-attention over concatenated [Z_prev; Z_curr; Z_next]
- Asymmetric mask: curr <->{prev,next}, prev/next self-attend + read curr,
  prev <-> next blocked
- Directional salience gate: learned content-conditioned gates decide which
  boundary tokens send to and receive from each neighbor
- Zero-init output projections -> exact no-op at initialization
- Clone QKV/FFN from host vision block for stable injection
"""

import math
from typing import Optional

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


_ACT_FACTORIES = {
    "gelu_tanh": lambda: nn.GELU(approximate="tanh"),
    "gelu_pytorch_tanh": lambda: nn.GELU(approximate="tanh"),
    "gelu": lambda: nn.GELU(),
    "silu": lambda: nn.SiLU(),
    "relu": lambda: nn.ReLU(),
}


def _make_activation(name: str) -> nn.Module:
    if name not in _ACT_FACTORIES:
        raise ValueError(f"Unknown activation {name!r}. Known: {sorted(_ACT_FACTORIES)}")
    return _ACT_FACTORIES[name]()


def _make_norm(hidden_size: int, eps: float = 1e-6) -> nn.LayerNorm:
    return nn.LayerNorm(hidden_size, eps=eps)


# ---------------------------------------------------------------------------
# Positional feature for salience gate
# ---------------------------------------------------------------------------

def cross_page_pos_feature(dist_frac: torch.Tensor, num_freqs: int = 4) -> torch.Tensor:
    """Continuous sinusoidal positional feature for distance-from-edge.

    Args:
        dist_frac: [...] float in [0, 1], capped fractional distance.
        num_freqs: number of frequency bands.

    Returns:
        [..., 1 + 2*num_freqs] tensor (no learnable params).
    """
    freqs = (2.0 ** torch.arange(num_freqs, device=dist_frac.device, dtype=dist_frac.dtype)) * math.pi
    angles = dist_frac.unsqueeze(-1) * freqs  # [..., num_freqs]
    return torch.cat([dist_frac.unsqueeze(-1), torch.sin(angles), torch.cos(angles)], dim=-1)


def compute_pos_features(
    h: int, w: int, cap_frac: float, device: torch.device, dtype: torch.dtype,
) -> torch.Tensor:
    """Compute per-token positional features for a page grid.

    Args:
        h: grid height (post-merger rows).
        w: grid width (post-merger cols).
        cap_frac: CAP_FRAC — fraction of page height for capping distance.
        device, dtype: tensor placement.

    Returns:
        [h*w, 18] tensor of positional features.
    """
    num_freqs = 4
    n_tokens = h * w

    # Row index for each token (tokens are stored row-major)
    row_idx = torch.arange(h, device=device, dtype=dtype).unsqueeze(1).expand(h, w).reshape(n_tokens)
    h_real = float(h)
    cap_p = cap_frac * h_real

    # Distance from top edge, capped
    dist_top = torch.clamp(row_idx, max=cap_p) / h_real
    # Distance from bottom edge, capped
    dist_bot = torch.clamp(h_real - 1.0 - row_idx, max=cap_p) / h_real

    # Sinusoidal expansion (9 dims each, 18 total)
    feat_top = cross_page_pos_feature(dist_top, num_freqs)  # [n_tokens, 9]
    feat_bot = cross_page_pos_feature(dist_bot, num_freqs)  # [n_tokens, 9]

    return torch.cat([feat_top, feat_bot], dim=-1)  # [n_tokens, 18]


@torch.no_grad()
def _find_content_frontiers(
    content_mask: torch.Tensor,
    h: int,
    w: int,
) -> Optional[tuple[torch.Tensor, torch.Tensor]]:
    """Find first/last ink rows from a per-token content mask."""
    content = content_mask.reshape(h, w).float()
    row_score = content.amax(dim=1)
    if row_score.numel() == 0:
        return None

    max_score = row_score.max()
    threshold = torch.maximum(max_score * 0.25, row_score.new_tensor(0.03))
    active_rows = torch.nonzero(row_score >= threshold, as_tuple=False).flatten()
    if active_rows.numel() == 0:
        active_rows = torch.nonzero(row_score > 0, as_tuple=False).flatten()
    if active_rows.numel() == 0:
        return None

    return active_rows[0].to(device=content.device), active_rows[-1].to(device=content.device)


def compute_frontier_pos_features(
    h: int,
    w: int,
    cap_frac: float,
    device: torch.device,
    dtype: torch.dtype,
    content_mask: Optional[torch.Tensor],
) -> torch.Tensor:
    """Compute positional gate features relative to first/last ink rows.

    Blank page margins outside the detected content band are treated as far
    from the frontier, so the gate cannot use physical whitespace as the easy
    shortcut for "near a boundary".
    """
    if content_mask is None:
        return compute_pos_features(h, w, cap_frac, device, dtype)

    content_mask = content_mask.to(device=device)
    frontiers = _find_content_frontiers(content_mask, h, w)
    if frontiers is None:
        return compute_pos_features(h, w, cap_frac, device, dtype)

    top_frontier, bottom_frontier = frontiers
    num_freqs = 4
    n_tokens = h * w
    row_idx = torch.arange(h, device=device, dtype=dtype).unsqueeze(1).expand(h, w).reshape(n_tokens)
    h_real = float(h)
    cap_p = cap_frac * h_real
    far = row_idx.new_full(row_idx.shape, cap_p)

    top_frontier = top_frontier.to(device=device, dtype=dtype)
    bottom_frontier = bottom_frontier.to(device=device, dtype=dtype)
    dist_top_raw = row_idx - top_frontier
    dist_bottom_raw = bottom_frontier - row_idx

    dist_top = torch.where(dist_top_raw >= 0, torch.clamp(dist_top_raw, max=cap_p), far) / h_real
    dist_bot = torch.where(dist_bottom_raw >= 0, torch.clamp(dist_bottom_raw, max=cap_p), far) / h_real

    feat_top = cross_page_pos_feature(dist_top, num_freqs)
    feat_bot = cross_page_pos_feature(dist_bot, num_freqs)
    return torch.cat([feat_top, feat_bot], dim=-1)


def compute_edge_targets(
    h: int,
    w: int,
    tau_frac: float,
    device: torch.device,
    dtype: torch.dtype,
) -> tuple[torch.Tensor, torch.Tensor]:
    """Soft top/bottom edge targets for directional gate regularization."""
    n_tokens = h * w
    row_idx = torch.arange(h, device=device, dtype=dtype).unsqueeze(1).expand(h, w).reshape(n_tokens)
    denom = max(float(h - 1), 1.0)
    tau = max(float(tau_frac), 1e-4)
    dist_top = row_idx / denom
    dist_bottom = (float(h - 1) - row_idx) / denom
    target_top = torch.exp(-dist_top / tau)
    target_bottom = torch.exp(-dist_bottom / tau)
    return target_top, target_bottom


def compute_ink_edge_targets(
    target_top: torch.Tensor,
    target_bottom: torch.Tensor,
    content_mask: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
    """Apply a detached per-token ink/content mask to edge targets."""
    content_mask = content_mask.to(device=target_top.device, dtype=target_top.dtype)
    return target_top * content_mask, target_bottom * content_mask


@torch.no_grad()
def compute_ink_frontier_targets(
    content_mask: torch.Tensor,
    h: int,
    w: int,
    tau_frac: float,
) -> tuple[torch.Tensor, torch.Tensor]:
    """Soft targets around the first/last ink rows, not the physical page edge."""
    content = content_mask.reshape(h, w).float()
    row_score = content.amax(dim=1)
    if row_score.numel() == 0:
        zeros = content.reshape(-1).to(dtype=content_mask.dtype)
        return zeros, zeros

    max_score = row_score.max()
    threshold = torch.maximum(max_score * 0.25, row_score.new_tensor(0.03))
    active_rows = torch.nonzero(row_score >= threshold, as_tuple=False).flatten()
    if active_rows.numel() == 0:
        active_rows = torch.nonzero(row_score > 0, as_tuple=False).flatten()
    if active_rows.numel() == 0:
        zeros = content.reshape(-1).to(dtype=content_mask.dtype)
        return zeros, zeros

    top_frontier = active_rows[0].to(device=content.device, dtype=content.dtype)
    bottom_frontier = active_rows[-1].to(device=content.device, dtype=content.dtype)
    row_idx = torch.arange(h, device=content.device, dtype=content.dtype).unsqueeze(1)
    denom = max(float(h - 1), 1.0)
    tau = max(float(tau_frac), 1e-4)

    top_band = torch.exp(-torch.abs(row_idx - top_frontier) / (denom * tau))
    bottom_band = torch.exp(-torch.abs(row_idx - bottom_frontier) / (denom * tau))
    target_top = (top_band * content).reshape(-1).to(dtype=content_mask.dtype)
    target_bottom = (bottom_band * content).reshape(-1).to(dtype=content_mask.dtype)
    return target_top, target_bottom


# ---------------------------------------------------------------------------
# Asymmetric attention mask builder
# ---------------------------------------------------------------------------

def build_asymmetric_mask(
    n_prev: int, n_curr: int, n_next: int, device: torch.device, dtype: torch.dtype,
) -> torch.Tensor:
    """Build the [3N, 3N] additive mask for the triplet attention.

    Allowed flows:
        prev -> {prev, curr}         (self-attend + read center)
        curr -> {prev, curr, next}   (reads both neighbors — BIDIRECTIONAL)
        next -> {curr, next}         (self-attend + read center)
        BLOCKED: prev <-> next       (two pages apart, no direct link)

    Returns:
        [total, total] additive float mask. 0 = allowed, -inf = blocked.
    """
    total = n_prev + n_curr + n_next
    min_val = torch.finfo(dtype).min
    mask = torch.full((total, total), min_val, device=device, dtype=dtype)

    # Ranges
    p_s, p_e = 0, n_prev
    c_s, c_e = n_prev, n_prev + n_curr
    n_s, n_e = n_prev + n_curr, total

    # prev -> prev (self-attend)
    mask[p_s:p_e, p_s:p_e] = 0.0
    # prev -> curr (read center)
    mask[p_s:p_e, c_s:c_e] = 0.0
    # curr -> prev (read prev neighbor)
    mask[c_s:c_e, p_s:p_e] = 0.0
    # curr -> curr (self-attend)
    mask[c_s:c_e, c_s:c_e] = 0.0
    # curr -> next (read next neighbor)
    mask[c_s:c_e, n_s:n_e] = 0.0
    # next -> curr (read center)
    mask[n_s:n_e, c_s:c_e] = 0.0
    # next -> next (self-attend)
    mask[n_s:n_e, n_s:n_e] = 0.0
    # prev <-> next: BLOCKED (stays at min_val)

    return mask


# ---------------------------------------------------------------------------
# DocSEAM Block (single transformer layer over the triplet)
# ---------------------------------------------------------------------------

class DocSEAMBlock(nn.Module):
    """Single DocSEAM transformer layer: salience-gated, asymmetric-masked
    self-attention over [Z_prev; Z_curr; Z_next] + FFN.

    Args:
        hidden_size: token dimension (post-merger, = LLM hidden_size).
        num_heads: attention heads.
        intermediate_size: FFN inner dimension.
        cap_frac: CAP_FRAC for salience gate positional features.
        proj_init_std: if > 0, init output projections with normal(0, std);
            otherwise zero-init (default for exact no-op).
        activation: activation function name for FFN.
    """

    POS_FEAT_DIM = 18  # 2 * (1 + 2*4)

    def __init__(
        self,
        hidden_size: int,
        num_heads: int,
        intermediate_size: int = 4096,
        cap_frac: float = 0.20,
        proj_init_std: float = 0.0,
        activation: str = "gelu_pytorch_tanh",
    ):
        super().__init__()
        self.hidden_size = hidden_size
        self.num_heads = num_heads
        self.head_dim = hidden_size // num_heads
        self.cap_frac = cap_frac

        # --- Norms ---
        self.norm1 = _make_norm(hidden_size)
        self.norm2 = _make_norm(hidden_size)

        # --- Attention QKV (fused) + output projection ---
        self.qkv = nn.Linear(hidden_size, hidden_size * 3, bias=True)
        self.proj = nn.Linear(hidden_size, hidden_size, bias=True)

        # --- FFN (2-linear GELU, mirroring Qwen3.5 vision block) ---
        self.act = _make_activation(activation)
        self.fc1 = nn.Linear(hidden_size, intermediate_size, bias=True)
        self.fc2 = nn.Linear(intermediate_size, hidden_size, bias=True)

        # --- Directional salience gate MLPs (D+18 -> D/4 -> 1) ---
        gate_input_dim = hidden_size + self.POS_FEAT_DIM
        gate_hidden_dim = hidden_size // 4
        self.mlp_send_to_next = nn.Sequential(
            nn.Linear(gate_input_dim, gate_hidden_dim),
            nn.GELU(),
            nn.Linear(gate_hidden_dim, 1),
        )
        self.mlp_recv_from_prev = nn.Sequential(
            nn.Linear(gate_input_dim, gate_hidden_dim),
            nn.GELU(),
            nn.Linear(gate_hidden_dim, 1),
        )
        self.mlp_send_to_prev = nn.Sequential(
            nn.Linear(gate_input_dim, gate_hidden_dim),
            nn.GELU(),
            nn.Linear(gate_hidden_dim, 1),
        )
        self.mlp_recv_from_next = nn.Sequential(
            nn.Linear(gate_input_dim, gate_hidden_dim),
            nn.GELU(),
            nn.Linear(gate_hidden_dim, 1),
        )

        # --- Init ---
        self._init_weights(proj_init_std)

    def _init_weights(self, proj_init_std: float):
        """Zero-init output projections and salience gate final layers."""
        # Output projection: zero or tiny-normal
        if proj_init_std > 0:
            nn.init.normal_(self.proj.weight, std=proj_init_std)
            nn.init.zeros_(self.proj.bias)
            nn.init.normal_(self.fc2.weight, std=proj_init_std)
            nn.init.zeros_(self.fc2.bias)
        else:
            nn.init.zeros_(self.proj.weight)
            nn.init.zeros_(self.proj.bias)
            nn.init.zeros_(self.fc2.weight)
            nn.init.zeros_(self.fc2.bias)

        # Salience gate final layers: zero-init so gates start neutral.
        for mlp in (
            self.mlp_send_to_next,
            self.mlp_recv_from_prev,
            self.mlp_send_to_prev,
            self.mlp_recv_from_next,
        ):
            nn.init.zeros_(mlp[-1].weight)
            nn.init.zeros_(mlp[-1].bias)

    def _compute_salience_bias(
        self,
        tokens: torch.Tensor,
        pos_feats: torch.Tensor,
        n_prev: int,
        n_curr: int,
        n_next: int,
    ) -> torch.Tensor:
        """Compute additive salience bias for cross-page attention cells.

        Args:
            tokens: [total, D] the normalized concatenated tokens.
            pos_feats: [total, 18] positional features for all tokens.
            n_prev, n_curr, n_next: token counts per page.

        Returns:
            [total, total] additive bias (0 for same-page cells, gate values
            for cross-page cells).
        """
        total = n_prev + n_curr + n_next

        # Concatenate features for gate input
        gate_input = torch.cat([tokens, pos_feats], dim=-1)  # [total, D+18]

        # Compute per-token directional scores.
        s_send_to_next = self.mlp_send_to_next(gate_input).squeeze(-1)  # [total]
        s_recv_from_prev = self.mlp_recv_from_prev(gate_input).squeeze(-1)  # [total]
        s_send_to_prev = self.mlp_send_to_prev(gate_input).squeeze(-1)  # [total]
        s_recv_from_next = self.mlp_recv_from_next(gate_input).squeeze(-1)  # [total]

        # Cache for visualization.
        self._last_salience = {
            "s_send_to_next": s_send_to_next.detach(),
            "s_recv_from_prev": s_recv_from_prev.detach(),
            "s_send_to_prev": s_send_to_prev.detach(),
            "s_recv_from_next": s_recv_from_next.detach(),
        }

        # log_sigmoid for numerical stability.
        log_send_to_next = F.logsigmoid(s_send_to_next)  # [total]
        log_recv_from_prev = F.logsigmoid(s_recv_from_prev)  # [total]
        log_send_to_prev = F.logsigmoid(s_send_to_prev)  # [total]
        log_recv_from_next = F.logsigmoid(s_recv_from_next)  # [total]

        # Build bias: only apply to cross-page cells
        bias = torch.zeros(total, total, device=tokens.device, dtype=tokens.dtype)

        # Ranges
        p_s, p_e = 0, n_prev
        c_s, c_e = n_prev, n_prev + n_curr
        n_s, n_e = n_prev + n_curr, total

        # curr query reads prev key: current receives from previous; previous sends to next.
        bias[c_s:c_e, p_s:p_e] = (
            log_recv_from_prev[c_s:c_e].unsqueeze(1) + log_send_to_next[p_s:p_e].unsqueeze(0)
        )
        # curr query reads next key: current receives from next; next sends to previous.
        bias[c_s:c_e, n_s:n_e] = (
            log_recv_from_next[c_s:c_e].unsqueeze(1) + log_send_to_prev[n_s:n_e].unsqueeze(0)
        )
        # prev query reads curr key: previous receives from next; current sends to previous.
        bias[p_s:p_e, c_s:c_e] = (
            log_recv_from_next[p_s:p_e].unsqueeze(1) + log_send_to_prev[c_s:c_e].unsqueeze(0)
        )
        # next query reads curr key: next receives from previous; current sends to next.
        bias[n_s:n_e, c_s:c_e] = (
            log_recv_from_prev[n_s:n_e].unsqueeze(1) + log_send_to_next[c_s:c_e].unsqueeze(0)
        )

        return bias

    def _compute_gate_scores(self, tokens: torch.Tensor, pos_feats: torch.Tensor) -> dict[str, torch.Tensor]:
        gate_input = torch.cat([tokens, pos_feats], dim=-1)
        return {
            "s_send_to_next": self.mlp_send_to_next(gate_input).squeeze(-1),
            "s_recv_from_prev": self.mlp_recv_from_prev(gate_input).squeeze(-1),
            "s_send_to_prev": self.mlp_send_to_prev(gate_input).squeeze(-1),
            "s_recv_from_next": self.mlp_recv_from_next(gate_input).squeeze(-1),
        }

    def compute_gate_aux_loss(
        self,
        triplet_tokens: torch.Tensor,
        pos_feats: torch.Tensor,
        target_top: Optional[torch.Tensor],
        target_bottom: Optional[torch.Tensor],
        target_content: Optional[torch.Tensor],
        frontier_top: Optional[torch.Tensor],
        frontier_bottom: Optional[torch.Tensor],
        edge_prior_weight: float,
        ink_prior_weight: float,
        frontier_prior_weight: float,
        gate_l1_weight: float,
        gate_budget_weight: float,
        gate_budget_target: float,
        margin_penalty_weight: float = 0.0,
    ) -> torch.Tensor:

        normed = self.norm1(triplet_tokens)
        scores = self._compute_gate_scores(normed, pos_feats)
        loss = normed.new_zeros(())

        def weighted_open_loss(score: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
            open_loss = F.binary_cross_entropy_with_logits(
                score,
                torch.ones_like(score),
                reduction="none",
            )
            weight = weight.detach()
            return (open_loss * weight).sum() / weight.sum().clamp_min(1.0)

        if edge_prior_weight > 0 and target_top is not None and target_bottom is not None:
            edge_loss = (
                F.binary_cross_entropy_with_logits(scores["s_send_to_next"], target_bottom)
                + F.binary_cross_entropy_with_logits(scores["s_recv_from_prev"], target_top)
                + F.binary_cross_entropy_with_logits(scores["s_send_to_prev"], target_top)
                + F.binary_cross_entropy_with_logits(scores["s_recv_from_next"], target_bottom)
            ) / 4.0
            loss = loss + float(edge_prior_weight) * edge_loss

        if ink_prior_weight > 0 and target_top is not None and target_bottom is not None and target_content is not None:
            ink_top, ink_bottom = compute_ink_edge_targets(target_top, target_bottom, target_content)

            ink_loss = (
                weighted_open_loss(scores["s_send_to_next"], ink_bottom)
                + weighted_open_loss(scores["s_recv_from_prev"], ink_top)
                + weighted_open_loss(scores["s_send_to_prev"], ink_top)
                + weighted_open_loss(scores["s_recv_from_next"], ink_bottom)
            ) / 4.0
            loss = loss + float(ink_prior_weight) * ink_loss

        if frontier_prior_weight > 0 and frontier_top is not None and frontier_bottom is not None:
            frontier_loss = (
                weighted_open_loss(scores["s_send_to_next"], frontier_bottom)
                + weighted_open_loss(scores["s_recv_from_prev"], frontier_top)
                + weighted_open_loss(scores["s_send_to_prev"], frontier_top)
                + weighted_open_loss(scores["s_recv_from_next"], frontier_bottom)
            ) / 4.0
            loss = loss + float(frontier_prior_weight) * frontier_loss

        if (
            margin_penalty_weight > 0
            and target_top is not None
            and target_bottom is not None
            and target_content is not None
        ):
            blank = (1.0 - target_content.detach()).clamp(0.0, 1.0)
            margin_top = target_top.detach() * blank
            margin_bottom = target_bottom.detach() * blank

            def weighted_close_loss(score: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
                close_loss = F.binary_cross_entropy_with_logits(
                    score,
                    torch.zeros_like(score),
                    reduction="none",
                )
                return (close_loss * weight).sum() / weight.sum().clamp_min(1.0)

            margin_loss = (
                weighted_close_loss(scores["s_send_to_next"], margin_bottom)
                + weighted_close_loss(scores["s_recv_from_prev"], margin_top)
                + weighted_close_loss(scores["s_send_to_prev"], margin_top)
                + weighted_close_loss(scores["s_recv_from_next"], margin_bottom)
            ) / 4.0
            loss = loss + float(margin_penalty_weight) * margin_loss

        if gate_l1_weight > 0:
            gate_l1 = torch.stack([torch.sigmoid(score).mean() for score in scores.values()]).mean()
            loss = loss + float(gate_l1_weight) * gate_l1

        if gate_budget_weight > 0:
            gate_means = torch.stack([torch.sigmoid(score).mean() for score in scores.values()])
            target = gate_means.new_tensor(float(gate_budget_target))
            gate_budget = F.relu(gate_means - target).square().mean()
            loss = loss + float(gate_budget_weight) * gate_budget

        return loss

    def forward(
        self,
        triplet_tokens: torch.Tensor,
        attn_mask: torch.Tensor,
        pos_feats: torch.Tensor,
        n_prev: int,
        n_curr: int,
        n_next: int,
    ) -> torch.Tensor:
        """Forward pass through one DocSEAM layer.

        Args:
            triplet_tokens: [total, D] concatenated [Z_prev; Z_curr; Z_next].
            attn_mask: [total, total] additive mask (0=allowed, -inf=blocked).
            pos_feats: [total, 18] positional features for all tokens.
            n_prev, n_curr, n_next: token counts per page.

        Returns:
            [total, D] updated tokens (all 3 pages updated).
        """
        total = triplet_tokens.shape[0]

        # --- Attention ---
        normed = self.norm1(triplet_tokens)

        # QKV projection
        qkv = self.qkv(normed)  # [total, 3*D]
        q = qkv[:, :self.hidden_size]
        k = qkv[:, self.hidden_size:2 * self.hidden_size]
        v = qkv[:, 2 * self.hidden_size:]

        # Reshape for multi-head attention: [1, num_heads, total, head_dim]
        q = q.view(total, self.num_heads, self.head_dim).transpose(0, 1).unsqueeze(0)
        k = k.view(total, self.num_heads, self.head_dim).transpose(0, 1).unsqueeze(0)
        v = v.view(total, self.num_heads, self.head_dim).transpose(0, 1).unsqueeze(0)

        # Compute salience bias
        salience_bias = self._compute_salience_bias(normed, pos_feats, n_prev, n_curr, n_next)

        # Combine asymmetric mask + salience bias
        # attn_mask: [total, total], salience_bias: [total, total]
        combined_mask = attn_mask + salience_bias  # [total, total]
        # Expand for SDPA: [1, 1, total, total] (broadcast over batch and heads)
        combined_mask = combined_mask.unsqueeze(0).unsqueeze(0)

        # SDPA attention
        attn_out = F.scaled_dot_product_attention(q, k, v, attn_mask=combined_mask)
        # [1, num_heads, total, head_dim] -> [total, D]
        attn_out = attn_out.squeeze(0).transpose(0, 1).contiguous().view(total, -1)

        # Residual + projection
        triplet_tokens = triplet_tokens + self.proj(attn_out)

        # --- FFN ---
        triplet_tokens = triplet_tokens + self.fc2(self.act(self.fc1(self.norm2(triplet_tokens))))

        return triplet_tokens


# ---------------------------------------------------------------------------
# DocSEAM module (stack of DocSEAMBlock layers)
# ---------------------------------------------------------------------------

class DocSEAM(nn.Module):
    """Triplet-Context Encoder with salience-gated cross-page Attention.

    Operates on post-merger vision tokens. For each page, builds a triplet
    [Z_{p-1}, Z_p, Z_{p+1}], runs stacked DocSEAMBlock layers, and returns
    only the enriched center page tokens E_p.

    Args:
        hidden_size: token dimension (post-merger = LLM hidden_size).
        num_heads: attention heads.
        intermediate_size: FFN inner dimension.
        num_layers: number of stacked DocSEAM layers (default 2).
        cap_frac: CAP_FRAC for salience gate (default 0.20).
        proj_init_std: init std for output projections (0 = zero-init).
        activation: FFN activation name.
    """

    def __init__(
        self,
        hidden_size: int = 2560,
        num_heads: int = 16,
        intermediate_size: int = 4096,
        num_layers: int = 2,
        cap_frac: float = 0.20,
        proj_init_std: float = 0.0,
        activation: str = "gelu_pytorch_tanh",
    ):
        super().__init__()
        self.hidden_size = hidden_size
        self.num_heads = num_heads
        self.num_layers = num_layers
        self.cap_frac = cap_frac
        self.edge_prior_weight = 0.0
        self.ink_prior_weight = 0.0
        self.frontier_prior_weight = 0.0
        self.gate_l1_weight = 0.0
        self.gate_budget_weight = 0.0
        self.gate_budget_target = 0.20
        self.edge_prior_tau = 0.08
        self.pos_feature_mode = "physical"
        self.margin_penalty_weight = 0.0
        self.use_checkpoint = True
        self.use_reentrant_checkpoint = True

        self.layers = nn.ModuleList([
            DocSEAMBlock(
                hidden_size=hidden_size,
                num_heads=num_heads,
                intermediate_size=intermediate_size,
                cap_frac=cap_frac,
                proj_init_std=proj_init_std,
                activation=activation,
            )
            for _ in range(num_layers)
        ])

    @staticmethod
    def _row_band_indices(
        h: int,
        w: int,
        start_row: int,
        end_row: int,
        offset: int,
        device: torch.device,
    ) -> torch.Tensor:
        rows = torch.arange(start_row, end_row, device=device)
        cols = torch.arange(w, device=device)
        return offset + (rows[:, None] * w + cols[None, :]).reshape(-1)

    @torch.no_grad()
    def _compute_attention_flow(
        self,
        layer: DocSEAMBlock,
        triplet_tokens: torch.Tensor,
        attn_mask: torch.Tensor,
        pos_feats: torch.Tensor,
        n_prev: int,
        n_curr: int,
        n_next: int,
        h_prev: int,
        w_prev: int,
        h_curr: int,
        w_curr: int,
        h_next: int,
        w_next: int,
    ) -> dict[str, torch.Tensor | float | int]:
        """Compute selected cross-page attention-flow slices for diagnostics.

        This avoids materializing the full [heads, total, total] attention matrix.
        Probabilities are still normalized against all allowed keys, matching SDPA.
        """
        band_frac = float(getattr(self, "attention_flow_band_frac", self.cap_frac))
        chunk_size = int(getattr(self, "attention_flow_chunk_size", 64))
        chunk_size = max(1, chunk_size)

        prev_band_rows = max(1, int(math.ceil(h_prev * band_frac)))
        curr_band_rows = max(1, int(math.ceil(h_curr * band_frac)))
        next_band_rows = max(1, int(math.ceil(h_next * band_frac)))

        prev_bottom = self._row_band_indices(
            h_prev, w_prev, h_prev - prev_band_rows, h_prev, 0, triplet_tokens.device
        )
        center_top = self._row_band_indices(
            h_curr, w_curr, 0, curr_band_rows, n_prev, triplet_tokens.device
        )
        center_bottom = self._row_band_indices(
            h_curr, w_curr, h_curr - curr_band_rows, h_curr, n_prev, triplet_tokens.device
        )
        next_top = self._row_band_indices(
            h_next, w_next, 0, next_band_rows, n_prev + n_curr, triplet_tokens.device
        )

        normed = layer.norm1(triplet_tokens)
        qkv = layer.qkv(normed)
        q = qkv[:, : layer.hidden_size]
        k = qkv[:, layer.hidden_size : 2 * layer.hidden_size]
        q = q.view(-1, layer.num_heads, layer.head_dim).transpose(0, 1).float()
        k = k.view(-1, layer.num_heads, layer.head_dim).transpose(0, 1).float()

        salience_bias = layer._compute_salience_bias(normed, pos_feats, n_prev, n_curr, n_next)
        combined_mask = (attn_mask + salience_bias).float()
        scale = 1.0 / math.sqrt(layer.head_dim)

        def summarize(query_idx: torch.Tensor, source_start: int, source_len: int, focus_idx: torch.Tensor):
            source_sum = torch.zeros(source_len, device="cpu", dtype=torch.float64)
            query_mass = torch.zeros(query_idx.numel(), device="cpu", dtype=torch.float64)
            denom = 0

            source_slice = slice(source_start, source_start + source_len)
            local_focus = (focus_idx - source_start).detach().cpu()

            for start in range(0, query_idx.numel(), chunk_size):
                q_chunk_idx = query_idx[start : start + chunk_size]
                q_chunk = q[:, q_chunk_idx, :]
                logits = torch.einsum("hqd,hkd->hqk", q_chunk, k) * scale
                logits = logits + combined_mask[q_chunk_idx].unsqueeze(0)
                probs = torch.softmax(logits, dim=-1)
                source_probs = probs[:, :, source_slice]

                source_sum += source_probs.sum(dim=(0, 1)).detach().cpu().double()
                query_mass[start : start + q_chunk_idx.numel()] = (
                    source_probs.sum(dim=-1).mean(dim=0).detach().cpu().double()
                )
                denom += source_probs.shape[0] * source_probs.shape[1]

            source_avg = source_sum / max(denom, 1)
            source_mass = float(source_avg.sum().item())
            focus_mass = float(source_avg[local_focus].sum().item())
            return source_avg.float(), query_mass.float(), source_mass, focus_mass / max(source_mass, 1e-12)

        prev_source, center_top_mass, top_to_prev_mass, prev_bottom_frac = summarize(
            center_top, 0, n_prev, prev_bottom
        )
        next_source, center_bottom_mass, bottom_to_next_mass, next_top_frac = summarize(
            center_bottom, n_prev + n_curr, n_next, next_top
        )

        center_top_map = torch.zeros(n_curr, dtype=torch.float32)
        center_bottom_map = torch.zeros(n_curr, dtype=torch.float32)
        center_top_local = (center_top - n_prev).detach().cpu()
        center_bottom_local = (center_bottom - n_prev).detach().cpu()
        center_top_map[center_top_local] = center_top_mass
        center_bottom_map[center_bottom_local] = center_bottom_mass

        return {
            "prev_source_from_center_top": prev_source,
            "center_top_to_prev": center_top_map,
            "center_bottom_to_next": center_bottom_map,
            "next_source_from_center_bottom": next_source,
            "top_to_prev_mass": top_to_prev_mass,
            "bottom_to_next_mass": bottom_to_next_mass,
            "prev_mass_bottom_band_frac": prev_bottom_frac,
            "next_mass_top_band_frac": next_top_frac,
            "band_frac": band_frac,
            "prev_band_rows": prev_band_rows,
            "curr_band_rows": curr_band_rows,
            "next_band_rows": next_band_rows,
        }

    def _process_triplet(
        self,
        z_prev: torch.Tensor,
        z_curr: torch.Tensor,
        z_next: torch.Tensor,
        h_prev: int, w_prev: int,
        h_curr: int, w_curr: int,
        h_next: int, w_next: int,
        detach_neighbors: bool = False,
        record_meta: Optional[dict] = None,
        ink_prev: Optional[torch.Tensor] = None,
        ink_curr: Optional[torch.Tensor] = None,
        ink_next: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        """Process a single triplet and return enriched center page tokens.

        Args:
            z_prev: [M_prev, D] previous page tokens (or self-fallback copy).
            z_curr: [M_curr, D] center page tokens.
            z_next: [M_next, D] next page tokens (or self-fallback copy).
            h_prev, w_prev: grid dims of previous page.
            h_curr, w_curr: grid dims of center page.
            h_next, w_next: grid dims of next page.
            detach_neighbors: if True, detach prev/next features (Stage A).

        Returns:
            [M_curr, D] enriched center page tokens.
        """
        if detach_neighbors:
            z_prev = z_prev.detach()
            z_next = z_next.detach()

        n_prev, n_curr, n_next = z_prev.shape[0], z_curr.shape[0], z_next.shape[0]

        # Concatenate triplet
        triplet = torch.cat([z_prev, z_curr, z_next], dim=0)  # [total, D]

        # Build asymmetric mask (can be cached if sizes repeat)
        attn_mask = build_asymmetric_mask(n_prev, n_curr, n_next, triplet.device, triplet.dtype)

        # Compute positional features for each page.
        pos_feature_mode = str(getattr(self, "pos_feature_mode", "physical") or "physical").lower()
        if pos_feature_mode == "frontier":
            pf_prev = compute_frontier_pos_features(
                h_prev, w_prev, self.cap_frac, triplet.device, triplet.dtype, ink_prev
            )
            pf_curr = compute_frontier_pos_features(
                h_curr, w_curr, self.cap_frac, triplet.device, triplet.dtype, ink_curr
            )
            pf_next = compute_frontier_pos_features(
                h_next, w_next, self.cap_frac, triplet.device, triplet.dtype, ink_next
            )
        else:
            pf_prev = compute_pos_features(h_prev, w_prev, self.cap_frac, triplet.device, triplet.dtype)
            pf_curr = compute_pos_features(h_curr, w_curr, self.cap_frac, triplet.device, triplet.dtype)
            pf_next = compute_pos_features(h_next, w_next, self.cap_frac, triplet.device, triplet.dtype)
        pos_feats = torch.cat([pf_prev, pf_curr, pf_next], dim=0)  # [total, 18]

        edge_prior_weight = float(getattr(self, "edge_prior_weight", 0.0) or 0.0)
        ink_prior_weight = float(getattr(self, "ink_prior_weight", 0.0) or 0.0)
        frontier_prior_weight = float(getattr(self, "frontier_prior_weight", 0.0) or 0.0)
        gate_l1_weight = float(getattr(self, "gate_l1_weight", 0.0) or 0.0)
        gate_budget_weight = float(getattr(self, "gate_budget_weight", 0.0) or 0.0)
        gate_budget_target = float(getattr(self, "gate_budget_target", 0.20) or 0.20)
        margin_penalty_weight = float(getattr(self, "margin_penalty_weight", 0.0) or 0.0)
        use_aux_loss = self.training and torch.is_grad_enabled() and (
            edge_prior_weight > 0
            or ink_prior_weight > 0
            or frontier_prior_weight > 0
            or gate_l1_weight > 0
            or gate_budget_weight > 0
            or margin_penalty_weight > 0
        )
        if use_aux_loss:
            tau = float(getattr(self, "edge_prior_tau", 0.08) or 0.08)
            prev_top, prev_bottom = compute_edge_targets(h_prev, w_prev, tau, triplet.device, triplet.dtype)
            curr_top, curr_bottom = compute_edge_targets(h_curr, w_curr, tau, triplet.device, triplet.dtype)
            next_top, next_bottom = compute_edge_targets(h_next, w_next, tau, triplet.device, triplet.dtype)
            target_top = torch.cat([prev_top, curr_top, next_top], dim=0)
            target_bottom = torch.cat([prev_bottom, curr_bottom, next_bottom], dim=0)
            if ink_prev is not None and ink_curr is not None and ink_next is not None:
                target_content = torch.cat(
                    [
                        ink_prev.reshape(-1).detach(),
                        ink_curr.reshape(-1).detach(),
                        ink_next.reshape(-1).detach(),
                    ],
                    dim=0,
                ).to(device=triplet.device, dtype=triplet.dtype)
            else:
                target_content = None

            if frontier_prior_weight > 0 and ink_prev is not None and ink_curr is not None and ink_next is not None:
                prev_frontier_top, prev_frontier_bottom = compute_ink_frontier_targets(
                    ink_prev.detach().to(device=triplet.device),
                    h_prev,
                    w_prev,
                    tau,
                )
                curr_frontier_top, curr_frontier_bottom = compute_ink_frontier_targets(
                    ink_curr.detach().to(device=triplet.device),
                    h_curr,
                    w_curr,
                    tau,
                )
                next_frontier_top, next_frontier_bottom = compute_ink_frontier_targets(
                    ink_next.detach().to(device=triplet.device),
                    h_next,
                    w_next,
                    tau,
                )
                frontier_top = torch.cat(
                    [prev_frontier_top, curr_frontier_top, next_frontier_top],
                    dim=0,
                ).to(device=triplet.device, dtype=triplet.dtype)
                frontier_bottom = torch.cat(
                    [prev_frontier_bottom, curr_frontier_bottom, next_frontier_bottom],
                    dim=0,
                ).to(device=triplet.device, dtype=triplet.dtype)
            else:
                frontier_top = None
                frontier_bottom = None
        else:
            target_top = None
            target_bottom = None
            target_content = None
            frontier_top = None
            frontier_bottom = None

        # Run through DocSEAM layers
        for layer_idx, layer in enumerate(self.layers):
            if use_aux_loss:
                aux_loss = layer.compute_gate_aux_loss(
                    triplet,
                    pos_feats,
                    target_top,
                    target_bottom,
                    target_content,
                    frontier_top,
                    frontier_bottom,
                    edge_prior_weight=edge_prior_weight,
                    ink_prior_weight=ink_prior_weight,
                    frontier_prior_weight=frontier_prior_weight,
                    gate_l1_weight=gate_l1_weight,
                    gate_budget_weight=gate_budget_weight,
                    gate_budget_target=gate_budget_target,
                    margin_penalty_weight=margin_penalty_weight,
                )
                self._aux_loss = aux_loss if self._aux_loss is None else self._aux_loss + aux_loss
                self._aux_loss_terms += 1

            if getattr(self, "record_attention_flow", False):
                flow = self._compute_attention_flow(
                    layer,
                    triplet,
                    attn_mask,
                    pos_feats,
                    n_prev,
                    n_curr,
                    n_next,
                    h_prev,
                    w_prev,
                    h_curr,
                    w_curr,
                    h_next,
                    w_next,
                )
                meta = {} if record_meta is None else dict(record_meta)
                meta.update({
                    "layer": layer_idx,
                    "n_prev": n_prev,
                    "n_curr": n_curr,
                    "n_next": n_next,
                    "prev_grid": (h_prev, w_prev),
                    "curr_grid": (h_curr, w_curr),
                    "next_grid": (h_next, w_next),
                })
                meta.update(flow)
                self._last_attention_flow_records.append(meta)

            if self.training and torch.is_grad_enabled() and bool(getattr(self, "use_checkpoint", True)):
                from torch.utils.checkpoint import checkpoint

                if not triplet.requires_grad:
                    triplet.requires_grad_(True)

                triplet = checkpoint(
                    layer,
                    triplet,
                    attn_mask,
                    pos_feats,
                    n_prev,
                    n_curr,
                    n_next,
                    use_reentrant=bool(getattr(self, "use_reentrant_checkpoint", True)),
                )
            else:
                triplet = layer(triplet, attn_mask, pos_feats, n_prev, n_curr, n_next)

            if getattr(self, "record_salience", False):
                salience = layer._last_salience
                meta = {} if record_meta is None else dict(record_meta)
                meta.update({
                    "layer": layer_idx,
                    "n_prev": n_prev,
                    "n_curr": n_curr,
                    "n_next": n_next,
                    "prev_grid": (h_prev, w_prev),
                    "curr_grid": (h_curr, w_curr),
                    "next_grid": (h_next, w_next),
                })
                meta.update({key: value.detach().cpu() for key, value in salience.items()})
                self._last_salience_records.append(meta)

        # Extract center page tokens only
        return triplet[n_prev:n_prev + n_curr]

    def forward(
        self,
        page_tokens: list[torch.Tensor],
        page_grid_dims: list[tuple[int, int]],
        pages_per_document: list[int],
        detach_neighbors: bool = False,
        page_ink_masks: Optional[list[torch.Tensor]] = None,
    ) -> list[torch.Tensor]:
        """Process all pages across all documents in the batch.

        Args:
            page_tokens: list of [M_p, D] tensors, one per page (all docs).
            page_grid_dims: list of (h_p, w_p) tuples, one per page.
            pages_per_document: list of page counts per document.
            detach_neighbors: if True, detach neighbor features (Stage A).

        Returns:
            list of [M_p, D] enriched page tokens (same order/shapes as input).
        """
        if getattr(self, "record_salience", False):
            self._last_salience_records = []
        if getattr(self, "record_attention_flow", False):
            self._last_attention_flow_records = []
        self._aux_loss = None
        self._aux_loss_terms = 0

        enriched = []
        page_idx = 0

        for doc_num_pages in pages_per_document:
            doc_start = page_idx
            doc_end = page_idx + doc_num_pages

            for p in range(doc_start, doc_end):
                # Get current page
                z_curr = page_tokens[p]
                h_curr, w_curr = page_grid_dims[p]
                ink_curr = page_ink_masks[p] if page_ink_masks is not None else None

                # Get previous page (self-fallback if first page of document)
                if p == doc_start:
                    z_prev = z_curr  # self-fallback
                    h_prev, w_prev = h_curr, w_curr
                    ink_prev = ink_curr
                else:
                    z_prev = page_tokens[p - 1]
                    h_prev, w_prev = page_grid_dims[p - 1]
                    ink_prev = page_ink_masks[p - 1] if page_ink_masks is not None else None

                # Get next page (self-fallback if last page of document)
                if p == doc_end - 1:
                    z_next = z_curr  # self-fallback
                    h_next, w_next = h_curr, w_curr
                    ink_next = ink_curr
                else:
                    z_next = page_tokens[p + 1]
                    h_next, w_next = page_grid_dims[p + 1]
                    ink_next = page_ink_masks[p + 1] if page_ink_masks is not None else None

                e_p = self._process_triplet(
                    z_prev, z_curr, z_next,
                    h_prev, w_prev,
                    h_curr, w_curr,
                    h_next, w_next,
                    detach_neighbors=detach_neighbors,
                    ink_prev=ink_prev,
                    ink_curr=ink_curr,
                    ink_next=ink_next,
                    record_meta={
                        "doc_start": doc_start,
                        "doc_end": doc_end,
                        "curr_page_index": p,
                        "prev_page_index": p if p == doc_start else p - 1,
                        "next_page_index": p if p == doc_end - 1 else p + 1,
                        "prev_is_self_fallback": p == doc_start,
                        "next_is_self_fallback": p == doc_end - 1,
                    },
                )
                enriched.append(e_p)

            page_idx = doc_end

        return enriched

    def get_aux_loss(self) -> Optional[torch.Tensor]:
        """Return the mean auxiliary gate loss accumulated during the last forward."""
        if self._aux_loss is None or self._aux_loss_terms <= 0:
            return None

        return self._aux_loss / float(self._aux_loss_terms)

    @torch.no_grad()
    def clone_init_from_vision_block(self, vision_block: nn.Module):
        """Clone QKV and FFN first-linear weights from a Qwen3.5 vision block.

        This ensures DocSEAM starts from a good feature space. The output
        projections remain at zero-init so the module is an exact no-op.

        Args:
            vision_block: a Qwen3_5VisionBlock with .attn.qkv, .mlp.linear_fc1,
                .norm1, .norm2.
        """
        def _copy(dst, src):
            dst.data.copy_(src.data.to(dst.dtype))

        def _copy_norm(dst_norm, src_norm):
            if hasattr(src_norm, "weight") and src_norm.weight is not None:
                _copy(dst_norm.weight, src_norm.weight)
            if hasattr(dst_norm, "bias") and dst_norm.bias is not None:
                if hasattr(src_norm, "bias") and src_norm.bias is not None:
                    _copy(dst_norm.bias, src_norm.bias)
                else:
                    dst_norm.bias.data.zero_()

        for layer in self.layers:
            # Clone QKV from vision block's fused qkv
            _copy(layer.qkv.weight, vision_block.attn.qkv.weight)
            if vision_block.attn.qkv.bias is not None:
                _copy(layer.qkv.bias, vision_block.attn.qkv.bias)
            else:
                layer.qkv.bias.data.zero_()

            # Clone FFN first linear
            _copy(layer.fc1.weight, vision_block.mlp.linear_fc1.weight)
            if vision_block.mlp.linear_fc1.bias is not None:
                _copy(layer.fc1.bias, vision_block.mlp.linear_fc1.bias)
            else:
                layer.fc1.bias.data.zero_()

            # Clone norms
            _copy_norm(layer.norm1, vision_block.norm1)
            _copy_norm(layer.norm2, vision_block.norm2)