File size: 52,236 Bytes
cd8b29e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99d2982
cd8b29e
 
 
99d2982
cd8b29e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99d2982
 
cd8b29e
99d2982
cd8b29e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99d2982
 
cd8b29e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99d2982
cd8b29e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99d2982
 
 
 
cd8b29e
 
 
 
99d2982
cd8b29e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99d2982
cd8b29e
 
99d2982
 
 
 
 
cd8b29e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99d2982
cd8b29e
99d2982
 
cd8b29e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99d2982
 
cd8b29e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99d2982
cd8b29e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99d2982
 
cd8b29e
 
 
 
 
 
 
 
 
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
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
"""Open-Source Nullspace-Protected Self-Learning LoRA Engine for Fintan-9B (Windows & Linux, 12 GB VRAM).

Implements:
  1. Pure-PyTorch symmetric Int4Linear (group=64) & Int8Linear (row-wise) with cached HF streaming
     (zero bitsandbytes/peft dependencies, ~4.5-6.0 GB peak training VRAM on RTX 4070 Ti).
  2. Layer-10 activation precomputation (H_10) so epochs train only layers [11..31] + checkpointing.
  3. Online exact Woodbury right-nullspace regularization against `X_preserve_base` (general/tools)
     plus optional prior-night receptor keys `--protect-keys` for orthogonal continual learning.
  4. Native `enable_thinking` + `enable_thinking=False` mixed Qwen3.5 template supervision
     (closing `<think>\\n` -> `</think>\\n\\n` natively in 25% of training examples).
  5. Entity-disambiguating study Q&A synthesizer (`synthesize-qa`), hard-fact study evaluator
     (`eval-study`), and exact reduced-SVD multi-night LoRA merger (`merge`).

Strictly separates training/mining (`facts.json`) from held-out evaluations (`check_questions.json`, Suite B/C/D).
"""

from __future__ import annotations

import argparse
import gc
import json
import math
import random
import re
import subprocess
import sys
import time
import urllib.request
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple

import gguf
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from huggingface_hub import snapshot_download
from torch.utils.checkpoint import checkpoint
from transformers import AutoConfig, AutoTokenizer
from transformers.models.qwen3_5 import modeling_qwen3_5 as qm

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8", line_buffering=True)

ROOT = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\fintan-9b-wsp")
UPSTREAM = ROOT / "upstream"
ADAPTERS = ROOT / "adapters"
CACHE_DIR = ROOT / "_cache"
QUANT_CACHE = CACHE_DIR / "qwen35_9b_int4_train.pt"
HOOK_CACHE = ROOT / "fintan_hook_cache.pt"
PIPELINE_DIR = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\wsp-5model-pipeline")
BASE_GGUF = PIPELINE_DIR / "models" / "qwen35_9b" / "Qwen3.5-9B-Q4_K_M.gguf"
LLAMA_SERVER = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\inkling2-mini-wsp\llama.cpp\llama-server.exe")

sys.path.insert(0, str(PIPELINE_DIR))
from build_9subspaces_all import TensorSource  # noqa: E402
from build_qwen35_9b_full_hooks import fetch_layer_state_dict, fetch_raw_bf16  # noqa: E402
from model_registry import MODEL_SPECS  # noqa: E402

FINTAN_LAYERS = [11, 14, 16, 18, 21, 23, 25, 27]
HF_REPO = "Qwen/Qwen3.5-9B"
_TEMPLATE_CACHE: Optional[str] = None


def get_qwen_chat_template() -> str:
    global _TEMPLATE_CACHE
    if _TEMPLATE_CACHE is not None:
        return _TEMPLATE_CACHE
    r = gguf.GGUFReader(str(BASE_GGUF))
    for f in r.fields.values():
        if "chat_template" in f.name:
            _TEMPLATE_CACHE = bytes(f.parts[f.data[0]]).decode("utf-8", errors="replace")
            return _TEMPLATE_CACHE
    raise RuntimeError(f"tokenizer.chat_template missing in {BASE_GGUF}")


def load_tokenizer_and_tcfg() -> Tuple[Any, Any]:
    local_qwen = PIPELINE_DIR / "models" / "qwen35_9b"
    if (local_qwen / "tokenizer.json").exists() and (local_qwen / "config.json").exists():
        tok_dir = str(local_qwen)
    else:
        tok_dir = snapshot_download(HF_REPO, allow_patterns=["config.json", "tokenizer*"])
    tok = AutoTokenizer.from_pretrained(tok_dir)
    if not getattr(tok, "chat_template", None):
        tok.chat_template = get_qwen_chat_template()
    cfg = AutoConfig.from_pretrained(tok_dir)
    tcfg = getattr(cfg, "text_config", cfg)
    tcfg._attn_implementation = "sdpa"
    return tok, tcfg


# ---------------------------------------------------------------------------
# Pure-PyTorch Quantized Layers (Zero bitsandbytes / peft dependencies)
# ---------------------------------------------------------------------------

def pack_int4_weight(w: torch.Tensor, group_size: int = 64) -> Tuple[torch.Tensor, torch.Tensor]:
    """Symmetric signed int4 [-7..7] packed 2 values per uint8 byte + bf16 group scales."""
    o, i = w.shape
    assert i % group_size == 0, f"in_features={i} must be divisible by {group_size}"
    w_g = w.float().view(o, i // group_size, group_size)
    scales = (w_g.abs().amax(dim=-1) / 7.0).clamp(min=1e-8)
    q = torch.clamp(torch.round(w_g / scales.unsqueeze(-1)), -7, 7).to(torch.int8).add(7).to(torch.uint8)
    q_flat = q.view(o, i)
    packed = q_flat[:, 0::2] | (q_flat[:, 1::2] << 4)
    return packed.contiguous(), scales.to(torch.bfloat16).contiguous()


def pack_int8_rowwise(w: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
    w_f = w.float()
    scales = (w_f.abs().amax(dim=-1, keepdim=True) / 127.0).clamp(min=1e-8)
    q = torch.clamp(torch.round(w_f / scales), -127, 127).to(torch.int8)
    return q.contiguous(), scales.to(torch.bfloat16).contiguous()


class Int4Linear(nn.Module):
    """Frozen packed-Int4 Linear layer with optional frozen base LoRA and trainable FP32 LoRA."""

    def __init__(self, qweight: torch.Tensor, scales: torch.Tensor, group_size: int = 64):
        super().__init__()
        self.register_buffer("qweight", qweight)
        self.register_buffer("scales", scales)
        self.in_features = qweight.shape[1] * 2
        self.out_features = qweight.shape[0]
        self.group_size = group_size
        self.register_buffer("base_lora_A", None)
        self.register_buffer("base_lora_B", None)
        self.lora_A: Optional[nn.Parameter] = None
        self.lora_B: Optional[nn.Parameter] = None

    def attach_frozen_base_lora(self, A: torch.Tensor, B: torch.Tensor, device: str = "cuda") -> None:
        self.base_lora_A = A.to(device=device, dtype=torch.bfloat16).contiguous()
        self.base_lora_B = B.to(device=device, dtype=torch.bfloat16).contiguous()

    def attach_lora(
        self,
        rank: int,
        init_ab: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
        device: str = "cuda",
    ) -> None:
        if init_ab is not None:
            a_init, b_init = init_ab
            self.lora_A = nn.Parameter(a_init.to(device=device, dtype=torch.float32).clone())
            self.lora_B = nn.Parameter(b_init.to(device=device, dtype=torch.float32).clone())
        else:
            a = torch.empty((rank, self.in_features), device=device, dtype=torch.float32)
            nn.init.kaiming_uniform_(a, a=math.sqrt(5))
            a.mul_(0.5)
            b = torch.zeros((self.out_features, rank), device=device, dtype=torch.float32)
            self.lora_A = nn.Parameter(a)
            self.lora_B = nn.Parameter(b)

    def dequant_weight(self) -> torch.Tensor:
        q_lo = (self.qweight & 0x0F).to(torch.int8) - 7
        q_hi = ((self.qweight >> 4) & 0x0F).to(torch.int8) - 7
        w = torch.stack((q_lo, q_hi), dim=-1).view(self.out_features, -1, self.group_size).to(torch.bfloat16)
        return (w * self.scales.unsqueeze(-1)).view(self.out_features, self.in_features)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        w = self.dequant_weight()
        out = F.linear(x, w)
        if self.base_lora_A is not None and self.base_lora_B is not None:
            hb = F.linear(x.to(self.base_lora_A.dtype), self.base_lora_A)
            out = out + F.linear(hb, self.base_lora_B).to(x.dtype)
        if self.lora_A is not None and self.lora_B is not None:
            h_a = F.linear(x.float(), self.lora_A)
            out = out + F.linear(h_a, self.lora_B).to(x.dtype)
        return out


class Int8Linear(nn.Module):
    """Row-wise quantized Int8 Linear layer (used for frozen lm_head)."""

    def __init__(self, qweight: torch.Tensor, scales: torch.Tensor):
        super().__init__()
        self.register_buffer("qweight", qweight)
        self.register_buffer("scales", scales)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        w = self.qweight.to(torch.bfloat16) * self.scales
        return F.linear(x.to(torch.bfloat16), w)


def quantize_decoder_sd(sd: Dict[str, torch.Tensor]) -> Dict[str, Any]:
    packed_sd: Dict[str, Any] = {}
    for k, v in sd.items():
        if k.endswith(".weight") and v.ndim == 2 and v.shape[1] % 64 == 0:
            qw, sc = pack_int4_weight(v, 64)
            packed_sd[k] = ("int4", qw.cpu(), sc.cpu())
        else:
            packed_sd[k] = ("raw", v.to(torch.bfloat16 if v.dtype == torch.float32 else v.dtype).cpu())
    return packed_sd


def build_quant_decoder_layer(
    tcfg: Any,
    layer_idx: int,
    packed_sd: Dict[str, Any],
    device: str = "cuda",
) -> nn.Module:
    with torch.device("meta"):
        block = qm.Qwen3_5DecoderLayer(tcfg, layer_idx=layer_idx)

    # Replace leaf modules in attention & mlp with packed Int4Linear or materialize buffers
    def _set_attr(root_mod: nn.Module, path: str, val: nn.Module) -> None:
        parts = path.split(".")
        cur = root_mod
        for p in parts[:-1]:
            cur = getattr(cur, p)
        setattr(cur, parts[-1], val)

    raw_sd: Dict[str, torch.Tensor] = {}
    for k, item in packed_sd.items():
        if item[0] == "int4":
            _, qw, sc = item
            mod_name = k[: -len(".weight")]
            _set_attr(block, mod_name, Int4Linear(qw.to(device), sc.to(device)))
        else:
            raw_sd[k] = item[1]

    # Materialize remaining non-Int4 parameters/buffers (norms, conv1d, A_log, dt_bias)
    for name, _ in list(block.named_parameters(recurse=True)):
        if name in raw_sd:
            parts = name.split(".")
            cur = block
            for p in parts[:-1]:
                cur = getattr(cur, p)
            setattr(cur, parts[-1], nn.Parameter(raw_sd[name].to(device), requires_grad=False))
    for name, _ in list(block.named_buffers(recurse=True)):
        if name in raw_sd:
            parts = name.split(".")
            cur = block
            for p in parts[:-1]:
                cur = getattr(cur, p)
            cur.register_buffer(parts[-1], raw_sd[name].to(device))
    block.eval()
    return block


def ensure_quantized_model_cache() -> Path:
    if QUANT_CACHE.exists():
        return QUANT_CACHE
    CACHE_DIR.mkdir(parents=True, exist_ok=True)
    print(f"[Cache Build] One-time streaming of {HF_REPO} into compact Int4/Int8 training cache...", flush=True)
    t0 = time.time()
    spec = [s for s in MODEL_SPECS if s.slug == "qwen35_9b"][0]
    ts = TensorSource(spec)

    print("  Fetching embed_tokens...", flush=True)
    emb_w = ts.fetch_tensor(spec.embed_key)
    emb_q, emb_s = pack_int8_rowwise(emb_w)
    del emb_w

    print("  Fetching lm_head...", flush=True)
    lm_w = ts.fetch_tensor(spec.lm_head_key)
    lm_q, lm_s = pack_int8_rowwise(lm_w)
    del lm_w

    norm_f_w = fetch_raw_bf16(ts, spec.norm_f_key).cpu()

    layers_packed: List[Dict[str, Any]] = []
    pool = ThreadPoolExecutor(max_workers=1)
    fut = pool.submit(fetch_layer_state_dict, ts, 0)
    try:
        for l in range(32):
            tl = time.time()
            sd = fut.result()
            if l + 1 < 32:
                fut = pool.submit(fetch_layer_state_dict, ts, l + 1)
            layers_packed.append(quantize_decoder_sd(sd))
            del sd
            if (l + 1) % 8 == 0 or l == 31:
                print(f"  Quantized layer {l+1:2d}/32 in {time.time()-tl:.1f}s (total {time.time()-t0:.1f}s)", flush=True)
    finally:
        pool.shutdown()

    tmp = QUANT_CACHE.with_suffix(".tmp")
    torch.save(
        {
            "embed_q": emb_q,
            "embed_s": emb_s,
            "lm_q": lm_q,
            "lm_s": lm_s,
            "norm_f_w": norm_f_w,
            "layers": layers_packed,
        },
        str(tmp),
    )
    tmp.replace(QUANT_CACHE)
    sz_gb = QUANT_CACHE.stat().st_size / (1024 ** 3)
    print(f"[Cache Build] Saved {QUANT_CACHE} ({sz_gb:.2f} GiB) in {time.time()-t0:.1f}s", flush=True)
    return QUANT_CACHE


# ---------------------------------------------------------------------------
# GGUF LoRA I/O + Reduced SVD Merge
# ---------------------------------------------------------------------------

def read_gguf_lora_pairs(path: Path) -> Dict[int, Tuple[torch.Tensor, torch.Tensor, float]]:
    reader = gguf.GGUFReader(str(path))
    raw: Dict[str, Tuple[np.ndarray, float]] = {}
    for t in reader.tensors:
        raw[t.name] = (np.array(t.data, copy=True), 1.0)
    alpha = 0.0
    for fld in reader.fields.values():
        if "lora.alpha" in fld.name:
            alpha = float(fld.parts[fld.data[0]][0])
    out: Dict[int, Tuple[torch.Tensor, torch.Tensor]] = {}
    for L in FINTAN_LAYERS:
        ka = f"blk.{L}.ffn_down.weight.lora_a"
        kb = f"blk.{L}.ffn_down.weight.lora_b"
        if ka not in raw or kb not in raw:
            continue
        A = torch.from_numpy(raw[ka][0]).float()
        B = torch.from_numpy(raw[kb][0]).float()
        if A.shape[0] > A.shape[1]:
            A = A.T
        if B.shape[0] < B.shape[1]:
            B = B.T
        r = A.shape[0]
        eff_alpha = alpha if alpha > 0 else float(r)
        scale = eff_alpha / float(r)
        if abs(scale - 1.0) > 1e-6:
            A = A * math.sqrt(scale)
            B = B * math.sqrt(scale)
        out[L] = (A.contiguous(), B.contiguous())
    return out


def export_lora_gguf(pairs_by_layer: Dict[int, Tuple[torch.Tensor, torch.Tensor]], out_path: Path) -> None:
    out_path.parent.mkdir(parents=True, exist_ok=True)
    first_A = next(iter(pairs_by_layer.values()))[0]
    rank = int(first_A.shape[0])
    w = gguf.GGUFWriter(str(out_path), "qwen35")
    w.add_type("adapter")
    w.add_string("adapter.type", "lora")
    w.add_float32("adapter.lora.alpha", float(rank))
    for L in sorted(pairs_by_layer.keys()):
        A, B = pairs_by_layer[L]
        # llama.cpp GGUF LoRA expects transposed shapes vs torch (in, r) for lora_a and (r, out) for lora_b?
        # Check exact shape convention in stage_and_analyze_fintan.py -> numpy F16 stored matching PEFT/gguf!
        a_np = A.detach().cpu().numpy().astype(np.float16)
        b_np = B.detach().cpu().numpy().astype(np.float16)
        w.add_tensor(f"blk.{L}.ffn_down.weight.lora_a", a_np, raw_dtype=gguf.GGMLQuantizationType.F16)
        w.add_tensor(f"blk.{L}.ffn_down.weight.lora_b", b_np, raw_dtype=gguf.GGMLQuantizationType.F16)
    w.write_header_to_file()
    w.write_kv_data_to_file()
    w.write_tensors_to_file()
    w.close()


def reduced_svd_recompress(dW: torch.Tensor, target_rank: int) -> Tuple[torch.Tensor, torch.Tensor]:
    """Exact rank-k SVD factorization dW [4096, 12288] -> (A [r, 12288], B [4096, r])."""
    U, S, Vh = torch.linalg.svd(dW.float(), full_matrices=False)
    r = min(target_rank, int(S.numel()))
    s_root = torch.sqrt(S[:r])
    B = U[:, :r] * s_root.unsqueeze(0)
    A = s_root.unsqueeze(1) * Vh[:r, :]
    return A.contiguous(), B.contiguous()


def cmd_merge(adapter_paths: List[Path], out_path: Path, target_rank: int) -> None:
    print(f"[Merge] Merging {len(adapter_paths)} adapters -> {out_path} (rank={target_rank})...", flush=True)
    loaded = [read_gguf_lora_pairs(p) for p in adapter_paths]
    dev = "cuda" if torch.cuda.is_available() else "cpu"
    merged: Dict[int, Tuple[torch.Tensor, torch.Tensor]] = {}
    for L in FINTAN_LAYERS:
        dW = torch.zeros((4096, 12288), device=dev, dtype=torch.float32)
        for ld in loaded:
            if L in ld:
                Ai, Bi = ld[L]
                dW.add_(Bi.to(dev) @ Ai.to(dev))
        A, B = reduced_svd_recompress(dW, target_rank)
        frob = float(torch.linalg.norm(B @ A).item())
        merged[L] = (A.cpu(), B.cpu())
        print(f"  L{L:2d}: merged ||dW||_F={frob:.3f} (rank={A.shape[0]})", flush=True)
    export_lora_gguf(merged, out_path)
    print(f"[Merge] Saved {out_path} ({out_path.stat().st_size / (1024**2):.2f} MiB)", flush=True)


# ---------------------------------------------------------------------------
# Entity-Disambiguated Study Q&A Synthesizer (Strictly from facts.json)
# ---------------------------------------------------------------------------

def _start_base_llama_server(port: int) -> subprocess.Popen:
    cmd = [
        str(LLAMA_SERVER),
        "-m", str(BASE_GGUF),
        "-c", "4096",
        "-ctk", "q8_0",
        "-ctv", "q8_0",
        "-np", "1",
        "-ngl", "99",
        "--fit", "off",
        "--jinja",
        "--port", str(port),
        "--host", "127.0.0.1",
    ]
    log_fp = (ROOT / f"synth_server_p{port}.log").open("w", encoding="utf-8")
    proc = subprocess.Popen(cmd, stdout=log_fp, stderr=subprocess.STDOUT)
    proc._log_fp = log_fp  # type: ignore[attr-defined]
    for _ in range(180):
        if proc.poll() is not None:
            raise RuntimeError(f"llama-server exited early with {proc.returncode}")
        try:
            with urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=2.0) as resp:
                if json.loads(resp.read().decode()).get("status") == "ok":
                    return proc
        except Exception:
            pass
        time.sleep(0.5)
    raise TimeoutError("Timed out waiting for base llama-server")


def _stop_server(proc: subprocess.Popen) -> None:
    proc.terminate()
    try:
        proc.wait(timeout=10)
    except subprocess.TimeoutExpired:
        proc.kill()
    try:
        proc._log_fp.close()  # type: ignore[attr-defined]
    except Exception:
        pass
    time.sleep(0.6)


def _deterministic_questions_for_fact(f: Dict[str, Any], siblings: List[Dict[str, Any]]) -> List[str]:
    subj = str(f.get("subject", "")).strip()
    rel = str(f.get("relation", "")).strip()
    val = str(f.get("value", "")).strip()
    dt = str(f.get("date", "")).strip()
    sib_hint = ""
    if len(siblings) > 1:
        sib_hint = f" ({rel})"
    q1 = f"Regarding {subj}{sib_hint} as of {dt}: what is {subj} {rel}?"
    q2 = f"What happened with {subj} ({rel}) as of {dt}?"
    # Simple subject-relation direct query without paren if unambiguous or concise
    if any(ord(c) > 127 for c in (subj + rel + val)):
        q2 = f"As of {dt}, regarding {subj}: {rel}?"
    return [q1, q2]


def cmd_synthesize_qa(facts_path: Path, out_path: Path, port: int = 8160, n_llm_per_fact: int = 6) -> Path:
    if out_path.exists():
        print(f"[Synthesize-QA] Using cached study Q&A at {out_path}", flush=True)
        return out_path
    facts = json.loads(facts_path.read_text(encoding="utf-8"))
    by_subj: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
    for idx, f in enumerate(facts):
        f_copy = dict(f)
        f_copy["_fact_id"] = idx
        by_subj[str(f.get("subject", "")).strip().lower()].append(f_copy)

    print(f"[Synthesize-QA] Synthesizing ~{n_llm_per_fact + 2} disambiguated Q&A pairs for {len(facts)} facts...", flush=True)
    proc = _start_base_llama_server(port)
    t0 = time.time()
    records: List[Dict[str, Any]] = []
    try:
        v1 = f"http://127.0.0.1:{port}/v1/chat/completions"
        for idx, f in enumerate(facts):
            subj = str(f.get("subject", "")).strip()
            rel = str(f.get("relation", "")).strip()
            val = str(f.get("value", "")).strip()
            dt = str(f.get("date", "")).strip()
            sibs = by_subj[subj.lower()]
            sib_notes = ""
            if len(sibs) > 1:
                others = [f"- ({s['relation']}) -> {s['value']}" for s in sibs if s["_fact_id"] != idx][:5]
                sib_notes = (
                    "\nSibling facts on the same subject (differentiate THIS fact's relation, NEVER mention any sibling answer value in your questions):\n"
                    + "\n".join(others)
                )

            prompt = (
                f"Fact to study:\n"
                f"  subject: {subj}\n"
                f"  relation/aspect: {rel}\n"
                f"  exact answer: {val}\n"
                f"  date: {dt}\n"
                f"{sib_notes}\n\n"
                f"Write exactly {n_llm_per_fact} diverse, natural questions (ONLY a JSON array of strings) "
                f"whose exact answer is `{val}`.\n"
                f"Rules:\n"
                f"1) NEVER copy schema words like 'subject', 'object', or 'method' into the questions.\n"
                f"2) Vary question openers cleanly (Who/What/Where/When/Why/How/Which/By how much), "
                f"include both dated (`as of {dt}`, `in November 2026`, `in 2026`) and undated variants, and active/passive phrasing.\n"
                f"3) Preserve exact language (English, German, French, or Spanish).\n"
                f"4) Never include `{val}` or any sibling answer values inside a question.\n"
                f"5) Output ONLY a valid JSON array of {n_llm_per_fact} strings."
            )
            body = {
                "model": "qwen3.5-9b",
                "messages": [{"role": "user", "content": prompt}],
                "max_tokens": 560,
                "temperature": 0.55,
                "seed": 42 + idx,
                "chat_template_kwargs": {"enable_thinking": False},
            }
            llm_qs: List[str] = []
            try:
                req = urllib.request.Request(v1, data=json.dumps(body).encode("utf-8"), headers={"Content-Type": "application/json"})
                with urllib.request.urlopen(req, timeout=60.0) as resp:
                    txt = json.loads(resp.read().decode("utf-8"))["choices"][0]["message"]["content"].strip()
                m = re.search(r"\[.*\]", txt, re.S)
                if m:
                    arr = json.loads(m.group(0))
                    if isinstance(arr, list):
                        for q in arr:
                            if isinstance(q, str) and len(q.strip()) >= 8 and val.lower() not in q.lower():
                                llm_qs.append(q.strip())
            except Exception:
                pass

            all_qs = []
            seen = set()
            for q in llm_qs:
                ql = q.lower()
                if ql not in seen:
                    seen.add(ql)
                    all_qs.append(q)
                if len(all_qs) >= n_llm_per_fact:
                    break
            if len(all_qs) < 6:
                for q in _deterministic_questions_for_fact(f, sibs):
                    ql = q.lower()
                    if ql not in seen:
                        seen.add(ql)
                        all_qs.append(q)
                    if len(all_qs) >= max(4, n_llm_per_fact):
                        break

            records.append({
                "fact_id": idx,
                "subject": subj,
                "relation": rel,
                "value": val,
                "date": dt,
                "questions": all_qs,
            })
            if (idx + 1) % 43 == 0 or idx + 1 == len(facts):
                el = time.time() - t0
                eta = (el / (idx + 1)) * (len(facts) - idx - 1)
                print(
                    f"  [Synth {idx+1:3d}/{len(facts)}] total_qs={sum(len(r['questions']) for r in records)} | elapsed={el:.1f}s ETA={eta:.1f}s",
                    flush=True,
                )
    finally:
        _stop_server(proc)

    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(json.dumps(records, indent=2, ensure_ascii=False), encoding="utf-8")
    print(f"[Synthesize-QA] Wrote {sum(len(r['questions']) for r in records)} study pairs -> {out_path}", flush=True)
    return out_path


# ---------------------------------------------------------------------------
# Tokenization, Layer-10 Activation Precompute & Nullspace-Protected Training
# ---------------------------------------------------------------------------

def build_training_examples(
    qa_records: List[Dict[str, Any]],
    tok: Any,
    think_frac: float = 0.25,
    only_fact_ids: Optional[set] = None,
    seed: int = 42,
) -> List[Dict[str, Any]]:
    rng = random.Random(seed)
    examples: List[Dict[str, Any]] = []
    eos_suffix = "<|im_end|>\n"
    for rec in qa_records:
        if only_fact_ids is not None and rec["fact_id"] not in only_fact_ids:
            continue
        ans = str(rec["value"]).strip()
        for q_idx, q in enumerate(rec["questions"]):
            use_think = (rng.random() < think_frac)
            if use_think:
                prompt_str = tok.apply_chat_template(
                    [{"role": "user", "content": q}],
                    tokenize=False,
                    add_generation_prompt=True,
                    enable_thinking=True,
                )
                target_str = "\n</think>\n\n" + ans + eos_suffix
            else:
                prompt_str = tok.apply_chat_template(
                    [{"role": "user", "content": q}],
                    tokenize=False,
                    add_generation_prompt=True,
                    enable_thinking=False,
                )
                target_str = ans + eos_suffix
            p_ids = tok.encode(prompt_str, add_special_tokens=False)
            t_ids = tok.encode(target_str, add_special_tokens=False)
            examples.append({
                "fact_id": rec["fact_id"],
                "full_ids": p_ids + t_ids,
                "prompt_len": len(p_ids),
                "is_think": use_think,
            })
    return examples


def make_masks_and_pos(
    lengths: List[int],
    max_len: int,
    rotary: nn.Module,
    hidden_size: int,
    dev: str,
) -> Tuple[torch.Tensor, torch.Tensor, Tuple[torch.Tensor, torch.Tensor], torch.Tensor]:
    bsz = len(lengths)
    mask_2d = torch.zeros((bsz, max_len), device=dev, dtype=torch.bfloat16)
    for b, L in enumerate(lengths):
        mask_2d[b, :L] = 1.0

    # 4D causal + valid-key additive mask with diagonal always unmasked to prevent NaN on padded rows
    causal = torch.triu(torch.ones((max_len, max_len), device=dev, dtype=torch.bool), diagonal=1)
    mask_4d = torch.zeros((bsz, 1, max_len, max_len), device=dev, dtype=torch.bfloat16)
    neg_val = -1e4
    for b, L in enumerate(lengths):
        invalid = causal.clone()
        if L < max_len:
            invalid[:, L:] = True
            invalid[torch.arange(L, max_len, device=dev), torch.arange(L, max_len, device=dev)] = False
        mask_4d[b, 0].masked_fill_(invalid, neg_val)

    p4 = torch.arange(max_len, device=dev).view(1, 1, -1).expand(4, bsz, max_len)
    with torch.no_grad():
        dummy = torch.empty((bsz, max_len, hidden_size), device=dev, dtype=torch.bfloat16)
        p_emb = rotary(dummy, p4[1:])
    return mask_2d, mask_4d, p_emb, p4[0]


def precompute_h10_cache(
    examples: List[Dict[str, Any]],
    cache: Dict[str, Any],
    tcfg: Any,
    dev: str = "cuda",
) -> List[torch.Tensor]:
    """Stream layers 0..10 once to precompute bf16 H_10 [L_i, 4096] for every example."""
    t0 = time.time()
    n = len(examples)
    max_all = max(len(x["full_ids"]) for x in examples)
    pad_id = 0

    emb_q = cache["embed_q"]
    emb_s = cache["embed_s"]
    # Gather per-example token embeddings [T_i, 4096] on CPU cleanly
    h_list: List[torch.Tensor] = []
    for ex in examples:
        ids = torch.tensor(ex["full_ids"], dtype=torch.long)
        w_sel = emb_q[ids].to(torch.bfloat16) * emb_s[ids]
        h_list.append(w_sel.cpu())

    with torch.device(dev):
        rotary = qm.Qwen3_5TextRotaryEmbedding(tcfg).to(dev)

    batch_size = 16
    order = sorted(range(n), key=lambda i: len(examples[i]["full_ids"]))

    for l in range(11):
        block = build_quant_decoder_layer(tcfg, l, cache["layers"][l], device=dev)
        is_linear = (block.block_type == "linear_attention")
        out_list: List[Optional[torch.Tensor]] = [None] * n
        with torch.no_grad():
            for s in range(0, n, batch_size):
                idxs = order[s : s + batch_size]
                lens = [h_list[i].shape[0] for i in idxs]
                tmax = max(lens)
                xb = torch.zeros((len(idxs), tmax, tcfg.hidden_size), device=dev, dtype=torch.bfloat16)
                for bi, orig_i in enumerate(idxs):
                    xb[bi, : lens[bi]] = h_list[orig_i].to(dev)
                m2, m4, p_emb, pos_ids = make_masks_and_pos(lens, tmax, rotary, tcfg.hidden_size, dev)
                yb = block(
                    xb,
                    position_embeddings=p_emb,
                    attention_mask=(m2 if is_linear else m4),
                    position_ids=pos_ids,
                )
                for bi, orig_i in enumerate(idxs):
                    out_list[orig_i] = yb[bi, : lens[bi]].cpu()
        h_list = out_list  # type: ignore[assignment]
        del block
        gc.collect()
        torch.cuda.empty_cache()

    print(f"[H10 Precompute] Streamed L0..10 on {n} examples (max_len={max_all}) in {time.time()-t0:.1f}s", flush=True)
    return h_list


def build_nullspace_basis(
    protect_layers: List[Dict[int, Any]],
    dev: str,
    target_layers: Optional[List[int]] = None,
) -> Dict[int, torch.Tensor]:
    """Compute weighted right-singular preserve basis P_basis[L] = (S/sqrt(N))[:, None]*Vh per layer."""
    basis: Dict[int, torch.Tensor] = {}
    for L in (target_layers or FINTAN_LAYERS):
        mats: List[torch.Tensor] = []
        for m in protect_layers:
            if L not in m:
                continue
            val = torch.cat(m[L], dim=0) if isinstance(m[L], list) else m[L]
            if hasattr(val, "numel") and val.numel() > 0:
                mats.append(val.float())
        if not mats:
            continue
        X = torch.cat(mats, dim=0).to(dev)  # [N, 12288]
        # Reduce via SVD for clean, compact penalty evaluation each step
        _, S, Vh = torch.linalg.svd(X, full_matrices=False)
        keep = S > 1e-4
        w = (S[keep] / math.sqrt(max(X.shape[0], 1))).unsqueeze(1)
        P = (w * Vh[keep]).contiguous()  # [K, 12288]
        basis[L] = P
    return basis


class _LoRALinearLayerWrapper(nn.Module):
    """Wraps RMSNorm(1+w) cleanly at final hidden states."""

    def __init__(self, norm_w: torch.Tensor, eps: float = 1e-6):
        super().__init__()
        self.register_buffer("weight", (1.0 + norm_w.float()).to(torch.bfloat16))
        self.eps = eps

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        xf = x.float()
        v = xf.pow(2).mean(dim=-1, keepdim=True)
        out = xf * torch.rsqrt(v + self.eps)
        return (out * self.weight.float()).to(x.dtype)


def cmd_train(
    facts_path: Path,
    qa_cache_path: Path,
    out_gguf: Path,
    save_keys_path: Optional[Path] = None,
    protect_key_paths: Optional[List[Path]] = None,
    base_adapter_path: Optional[Path] = None,
    init_adapter_path: Optional[Path] = None,
    only_fact_ids: Optional[set] = None,
    replay_qa_path: Optional[Path] = None,
    replay_per_fact: int = 1,
    rank: int = 64,
    epochs: int = 6,
    lr: float = 4e-4,
    batch_size: int = 16,
    micro_batch: int = 4,
    lambda_null: float = 0.08,
    think_frac: float = 0.25,
    n_llm_per_fact: int = 4,
    smoke_test: bool = False,
    target_layers: Optional[List[int]] = None,
    max_per_fact: int = 0,
) -> Dict[str, Any]:
    t_layers = sorted(target_layers) if target_layers else list(FINTAN_LAYERS)
    t_all = time.time()
    dev = "cuda"
    tok, tcfg = load_tokenizer_and_tcfg()
    cache_path = ensure_quantized_model_cache()
    print(f"[Train] Loading quantized weights cache from {cache_path}...", flush=True)
    qcache = torch.load(str(cache_path), map_location="cpu", weights_only=False)

    if smoke_test:
        dummy_recs = [
            {
                "fact_id": i,
                "subject": f"Entity{i}",
                "relation": "won",
                "value": f"Value_{i}_Token",
                "date": "2026-11-26",
                "questions": [f"What did Entity{i} win as of 2026-11-26?", f"Which award went to Entity{i}?"],
            }
            for i in range(8)
        ]
        examples = build_training_examples(dummy_recs, tok, think_frac=think_frac)
        epochs = 1
        batch_size = 8
        micro_batch = 4
    else:
        qa_cache_path = cmd_synthesize_qa(facts_path, qa_cache_path, n_llm_per_fact=n_llm_per_fact)
        qa_records = json.loads(qa_cache_path.read_text(encoding="utf-8"))
        if max_per_fact > 0:
            qa_records = [{**rr, "questions": list(rr["questions"][:max_per_fact])} for rr in qa_records]
        examples = build_training_examples(qa_records, tok, think_frac=think_frac, only_fact_ids=only_fact_ids)
        if replay_qa_path is not None and replay_qa_path.exists():
            rep_raw = json.loads(replay_qa_path.read_text(encoding="utf-8"))
            rep_recs = []
            for rr in rep_raw:
                if only_fact_ids is not None and rr["fact_id"] in only_fact_ids:
                    continue
                rc = dict(rr)
                rc["questions"] = list(rr["questions"][: max(1, int(replay_per_fact))])
                rep_recs.append(rc)
            rep_ex = build_training_examples(rep_recs, tok, think_frac=think_frac, seed=99)
            print(f"[Train] Added {len(rep_ex)} study-QA replay examples from {replay_qa_path.name}", flush=True)
            examples.extend(rep_ex)

    print(
        f"[Train] Examples={len(examples)} (think={sum(1 for e in examples if e['is_think'])}) | "
        f"rank={rank} | epochs={epochs} | lr={lr} | lambda_null={lambda_null}",
        flush=True,
    )

    h10_list = precompute_h10_cache(examples, qcache, tcfg, dev=dev)

    # Load preservation receptors (X_preserve_base + any prior night keys + optional extra protect keys)
    hk = torch.load(str(HOOK_CACHE), map_location="cpu", weights_only=False)
    protect_mats: List[Dict[int, torch.Tensor]] = [hk["X_preserve_base"]]
    if protect_key_paths:
        for kp in protect_key_paths:
            if kp.exists():
                kd = torch.load(str(kp), map_location="cpu", weights_only=False)
                protect_mats.append(kd["X_night"])
                print(f"[Train] Loaded orthogonal night keys from {kp.name}", flush=True)
    del hk
    null_basis = build_nullspace_basis(protect_mats, dev=dev, target_layers=t_layers)

    base_pairs = read_gguf_lora_pairs(base_adapter_path) if (base_adapter_path and base_adapter_path.exists()) else None
    if base_pairs is not None:
        print(f"[Train] Attaching frozen base LoRA from {base_adapter_path.name}", flush=True)

    init_pairs = read_gguf_lora_pairs(init_adapter_path) if (init_adapter_path and init_adapter_path.exists()) else None
    if init_pairs is not None:
        r_init = next(iter(init_pairs.values()))[0].shape[0]
        if r_init != rank:
            print(f"[Train] Adjusting rank from {rank} -> {r_init} to match --init-adapter", flush=True)
            rank = r_init

    # Build Layers 11..31 on GPU + norm_f + Int8 lm_head
    layers_hi: List[nn.Module] = []
    lora_params: List[nn.Parameter] = []
    lora_modules: Dict[int, Int4Linear] = {}
    for l in range(11, 32):
        blk = build_quant_decoder_layer(tcfg, l, qcache["layers"][l], device=dev)
        dp: Int4Linear = blk.mlp.down_proj  # type: ignore[assignment]
        if base_pairs is not None and l in base_pairs:
            dp.attach_frozen_base_lora(base_pairs[l][0], base_pairs[l][1], device=dev)
        if l in t_layers:
            dp.attach_lora(rank=rank, init_ab=(init_pairs[l] if init_pairs and l in init_pairs else None), device=dev)
            lora_params.extend([dp.lora_A, dp.lora_B])  # type: ignore[list-item]
            lora_modules[l] = dp
        layers_hi.append(blk)
    print(f"[Train] Trainable layers={t_layers} ({len(lora_modules)} modules)", flush=True)

    norm_f = _LoRALinearLayerWrapper(qcache["norm_f_w"]).to(dev)
    lm_head = Int8Linear(qcache["lm_q"].to(dev), qcache["lm_s"].to(dev))
    with torch.device(dev):
        rotary = qm.Qwen3_5TextRotaryEmbedding(tcfg).to(dev)
    del qcache
    gc.collect()
    torch.cuda.empty_cache()

    torch.cuda.reset_peak_memory_stats()
    vram_loaded_mb = torch.cuda.memory_allocated() / (1024 ** 2)
    print(f"[Train] GPU allocated before training (L11..31 + Int8 lm_head + LoRA): {vram_loaded_mb:.0f} MiB", flush=True)

    # Capture night input receptors at FINTAN_LAYERS if --save-keys requested (on direct answers)
    opt = torch.optim.AdamW(lora_params, lr=lr, betas=(0.9, 0.999), weight_decay=0.0)
    steps_per_epoch = math.ceil(len(examples) / batch_size)
    total_steps = epochs * steps_per_epoch
    warmup_steps = max(2, int(0.06 * total_steps))

    def get_lr_mult(step: int) -> float:
        if step < warmup_steps:
            return float(step + 1) / float(warmup_steps)
        prog = float(step - warmup_steps) / float(max(total_steps - warmup_steps, 1))
        return 0.05 + 0.95 * 0.5 * (1.0 + math.cos(math.pi * prog))

    sched = torch.optim.lr_scheduler.LambdaLR(opt, get_lr_mult)
    rng = random.Random(1234)
    global_step = 0
    ce_history: List[float] = []

    for ep in range(1, epochs + 1):
        # Bucketed length sorting with local jitter for tiny padding overhead
        idxs = list(range(len(examples)))
        rng.shuffle(idxs)
        # Sort within chunks of 64 by length so microbatches of 4 have minimal padding
        chunks = [sorted(idxs[k : k + 64], key=lambda i: h10_list[i].shape[0]) for k in range(0, len(idxs), 64)]
        ordered = [i for ch in chunks for i in ch]

        ep_ce = 0.0
        ep_null = 0.0
        ep_tok = 0
        opt.zero_grad(set_to_none=True)
        accum_steps = max(1, batch_size // micro_batch)
        micro_count = 0

        for s in range(0, len(ordered), micro_batch):
            mb_idxs = ordered[s : s + micro_batch]
            lens = [h10_list[i].shape[0] for i in mb_idxs]
            tmax = max(lens)
            xb = torch.zeros((len(mb_idxs), tmax, tcfg.hidden_size), device=dev, dtype=torch.bfloat16)
            label_pos_seqs: List[torch.Tensor] = []
            label_tgt_vals: List[torch.Tensor] = []

            for bi, oi in enumerate(mb_idxs):
                L_i = lens[bi]
                xb[bi, :L_i] = h10_list[oi].to(dev)
                p_len = examples[oi]["prompt_len"]
                ids = examples[oi]["full_ids"]
                # Target predicts ids[t+1] from hidden[t] for t in [p_len - 1 .. L_i - 2]
                pred_pos = torch.arange(p_len - 1, L_i - 1, device=dev, dtype=torch.long)
                tgt = torch.tensor(ids[p_len:], device=dev, dtype=torch.long)
                label_pos_seqs.append(pred_pos)
                label_tgt_vals.append(tgt)

            m2, m4, p_emb, pos_ids = make_masks_and_pos(lens, tmax, rotary, tcfg.hidden_size, dev)

            h = xb
            first_grad_idx = max(0, min(t_layers) - 11)
            for idx_blk, blk in enumerate(layers_hi):
                attn_m = m2 if blk.block_type == "linear_attention" else m4
                if idx_blk < first_grad_idx:
                    with torch.no_grad():
                        h = blk(h, position_embeddings=p_emb, attention_mask=attn_m, position_ids=pos_ids)
                    continue
                if idx_blk == first_grad_idx:
                    # Ensure input requires_grad so gradient checkpointing backpropagates cleanly
                    h = h.detach().requires_grad_(True)
                h = checkpoint(
                    lambda _h, _blk=blk, _pe=p_emb, _am=attn_m, _pi=pos_ids: _blk(
                        _h, position_embeddings=_pe, attention_mask=_am, position_ids=_pi
                    ),
                    h,
                    use_reentrant=False,
                )

            # Gather ONLY target token positions across microbatch before norm_f & Int8 lm_head
            h_sel = torch.cat([h[bi, label_pos_seqs[bi]] for bi in range(len(mb_idxs))], dim=0)
            targets = torch.cat(label_tgt_vals, dim=0)
            logits = lm_head(norm_f(h_sel)).float()
            loss_ce = F.cross_entropy(logits, targets, label_smoothing=0.03)

            loss_null = torch.zeros((), device=dev, dtype=torch.float32)
            for L, dp in lora_modules.items():
                if L in null_basis:
                    proj = dp.lora_B @ (dp.lora_A @ null_basis[L].T)
                    loss_null = loss_null + proj.pow(2).sum()

            n_mb_tok = int(targets.numel())
            loss_total = (loss_ce + lambda_null * loss_null) / float(accum_steps)
            loss_total.backward()

            ep_ce += float(loss_ce.item()) * n_mb_tok
            ep_null += float(loss_null.item())
            ep_tok += n_mb_tok
            micro_count += 1

            is_last_mb = (s + micro_batch >= len(ordered))
            if micro_count % accum_steps == 0 or is_last_mb:
                torch.nn.utils.clip_grad_norm_(lora_params, 1.0)
                opt.step()
                sched.step()
                opt.zero_grad(set_to_none=True)
                global_step += 1

        mean_ce = ep_ce / max(ep_tok, 1)
        mean_null = ep_null / max(micro_count, 1)
        ce_history.append(round(mean_ce, 4))
        norms = [float(torch.linalg.norm(dp.lora_B @ dp.lora_A).item()) for dp in lora_modules.values()]
        mean_frob = sum(norms) / len(norms)
        el = time.time() - t_all
        eta = (el / ep) * (epochs - ep)
        print(
            f"  [Epoch {ep}/{epochs}] loss_ce={mean_ce:.4f} | loss_null={mean_null:.4f} | "
            f"mean_||dW||_F={mean_frob:.3f} | elapsed={el:.1f}s | ETA={eta:.1f}s",
            flush=True,
        )

    peak_vram_mb = torch.cuda.max_memory_allocated() / (1024 ** 2)

    if smoke_test:
        print(f"[Smoke Test] Peak CUDA VRAM={peak_vram_mb:.0f} MiB (< 7500 OK!) | CE={ce_history}", flush=True)
        out_gguf.parent.mkdir(parents=True, exist_ok=True)
        export_lora_gguf({L: (dp.lora_A.detach().cpu(), dp.lora_B.detach().cpu()) for L, dp in lora_modules.items()}, out_gguf)
        print(f"[Smoke Test] Exported test GGUF -> {out_gguf} ({out_gguf.stat().st_size / 1024:.1f} KB)", flush=True)
        return {"smoke_test": True, "peak_vram_mb": round(peak_vram_mb, 1), "ce": ce_history}

    # Export GGUF LoRA
    pairs = {L: (dp.lora_A.detach().cpu(), dp.lora_B.detach().cpu()) for L, dp in lora_modules.items()}
    export_lora_gguf(pairs, out_gguf)
    print(f"[Train] Exported {out_gguf} ({out_gguf.stat().st_size / (1024**2):.2f} MiB) | peak_VRAM={peak_vram_mb:.0f} MiB", flush=True)

    # Optionally capture top-128 SVD input receptors at t_layers across trained examples for future --protect-keys
    if save_keys_path is not None:
        print(f"[Save-Keys] Capturing top-128 SVD receptors at {t_layers} -> {save_keys_path}...", flush=True)
        cap_rows: Dict[int, List[torch.Tensor]] = {L: [] for L in t_layers}
        handles = []
        cur_spans: List[Tuple[int, int]] = []

        def make_hook(layer_id: int):
            def _hk(_m, inp):
                x_in = inp[0].detach()
                for bi, (p0, l0) in enumerate(cur_spans):
                    cap_rows[layer_id].append(x_in[bi, p0 - 1 : l0 - 1].to(torch.float16).cpu())
            return _hk

        for L, dp in lora_modules.items():
            handles.append(dp.register_forward_pre_hook(make_hook(L)))

        # Use direct examples slice (up to 384 diverse target spans)
        direct_idxs = [i for i, e in enumerate(examples) if not e["is_think"]][:384]
        with torch.no_grad():
            for s in range(0, len(direct_idxs), 8):
                mb = direct_idxs[s : s + 8]
                lens = [h10_list[i].shape[0] for i in mb]
                tmax = max(lens)
                xb = torch.zeros((len(mb), tmax, tcfg.hidden_size), device=dev, dtype=torch.bfloat16)
                cur_spans = [(examples[i]["prompt_len"], lens[bi]) for bi, i in enumerate(mb)]
                for bi, oi in enumerate(mb):
                    xb[bi, : lens[bi]] = h10_list[oi].to(dev)
                m2, m4, p_emb, pos_ids = make_masks_and_pos(lens, tmax, rotary, tcfg.hidden_size, dev)
                h = xb
                for blk in layers_hi:
                    h = blk(h, position_embeddings=p_emb, attention_mask=(m2 if blk.block_type == "linear_attention" else m4), position_ids=pos_ids)
        for hd in handles:
            hd.remove()

        x_night: Dict[int, torch.Tensor] = {}
        for L in FINTAN_LAYERS:
            if not cap_rows[L]:
                continue
            mat = torch.cat(cap_rows[L], dim=0).float()
            _, S_n, Vh_n = torch.linalg.svd(mat.to(dev), full_matrices=False)
            k = min(128, int(S_n.numel()))
            # Store energy-weighted receptor basis [k, 12288] so build_nullspace_basis works directly
            x_night[L] = ((S_n[:k] / math.sqrt(max(mat.shape[0], 1))).unsqueeze(1) * Vh_n[:k]).to(torch.float16).cpu()
        save_keys_path.parent.mkdir(parents=True, exist_ok=True)
        torch.save({"X_night": x_night}, str(save_keys_path))
        print(f"[Save-Keys] Saved {save_keys_path} ({save_keys_path.stat().st_size / (1024**2):.2f} MiB)", flush=True)

    # Free all CUDA state cleanly before caller launches llama-server
    del layers_hi, norm_f, lm_head, lora_params, lora_modules, null_basis
    gc.collect()
    torch.cuda.empty_cache()
    return {
        "out_gguf": str(out_gguf),
        "size_mb": round(out_gguf.stat().st_size / (1024 ** 2), 2),
        "peak_vram_mb": round(peak_vram_mb, 1),
        "ce_history": ce_history,
        "elapsed_s": round(time.time() - t_all, 1),
    }


def cmd_eval_study(adapter_path: Path, qa_cache_path: Path, out_path: Path, port: int = 8161) -> Path:
    """Evaluate an adapter purely on 1 study question per fact (zero check_questions access) to find hard facts."""
    sys.path.insert(0, str(UPSTREAM / "scripts"))
    from run_transformers import right as fintan_right  # noqa: E402

    qa = json.loads(qa_cache_path.read_text(encoding="utf-8"))
    cmd = [
        str(LLAMA_SERVER),
        "-m", str(BASE_GGUF),
        "--lora", str(adapter_path),
        "-c", "4096", "-ctk", "q8_0", "-ctv", "q8_0", "-np", "1", "-ngl", "99",
        "--fit", "off", "--jinja", "--port", str(port), "--host", "127.0.0.1",
    ]
    log_fp = (ROOT / f"eval_study_p{port}.log").open("w", encoding="utf-8")
    proc = subprocess.Popen(cmd, stdout=log_fp, stderr=subprocess.STDOUT)
    proc._log_fp = log_fp  # type: ignore[attr-defined]
    misses: List[int] = []
    passed = 0
    try:
        for _ in range(180):
            if proc.poll() is not None:
                raise RuntimeError(f"llama-server exited early with {proc.returncode}")
            try:
                with urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=2.0) as resp:
                    if json.loads(resp.read().decode()).get("status") == "ok":
                        break
            except Exception:
                pass
            time.sleep(0.5)

        v1 = f"http://127.0.0.1:{port}/v1/chat/completions"
        for idx, rec in enumerate(qa):
            q = rec["questions"][0]
            gold = rec["value"]
            body = {
                "model": "qwen3.5-9b",
                "messages": [{"role": "user", "content": q}],
                "max_tokens": 64,
                "temperature": 0.0,
                "seed": 42,
                "cache_prompt": False,
                "chat_template_kwargs": {"enable_thinking": False},
            }
            req = urllib.request.Request(v1, data=json.dumps(body).encode("utf-8"), headers={"Content-Type": "application/json"})
            with urllib.request.urlopen(req, timeout=60.0) as resp:
                ans = json.loads(resp.read().decode("utf-8"))["choices"][0]["message"].get("content") or ""
            ok = bool(fintan_right(ans, gold, q))
            passed += int(ok)
            if not ok:
                misses.append(rec["fact_id"])
    finally:
        _stop_server(proc)

    res = {"adapter": str(adapter_path), "study_pass": passed, "total": len(qa), "missed_fact_ids": misses}
    out_path.write_text(json.dumps(res, indent=2), encoding="utf-8")
    print(f"[Eval-Study] {adapter_path.name}: {passed}/{len(qa)} study questions right | {len(misses)} hard fact_ids -> {out_path}", flush=True)
    return out_path


def main() -> None:
    ap = argparse.ArgumentParser(description="Nullspace-Protected Self-Learning LoRA Engine for Fintan-9B")
    sub = ap.add_subparsers(dest="cmd", required=True)

    p_syn = sub.add_parser("synthesize-qa")
    p_syn.add_argument("--facts", type=Path, required=True)
    p_syn.add_argument("--out", type=Path, required=True)
    p_syn.add_argument("--port", type=int, default=8160)
    p_syn.add_argument("--n-llm", type=int, default=4)

    p_tr = sub.add_parser("train")
    p_tr.add_argument("--facts", type=Path, default=UPSTREAM / "updates" / "2026-11-23" / "facts.json")
    p_tr.add_argument("--qa-cache", type=Path, default=ROOT / "study_qa_cache.json")
    p_tr.add_argument("--out", type=Path, default=ADAPTERS / "fintan_wsp_v2_test.gguf")
    p_tr.add_argument("--save-keys", type=Path, default=None)
    p_tr.add_argument("--protect-keys", type=Path, nargs="*", default=None)
    p_tr.add_argument("--base-adapter", type=Path, default=None)
    p_tr.add_argument("--init-adapter", type=Path, default=None)
    p_tr.add_argument("--only-fact-ids", type=Path, default=None)
    p_tr.add_argument("--replay-qa", type=Path, default=None)
    p_tr.add_argument("--replay-per-fact", type=int, default=1)
    p_tr.add_argument("--n-llm", type=int, default=4)
    p_tr.add_argument("--rank", type=int, default=64)
    p_tr.add_argument("--epochs", type=int, default=6)
    p_tr.add_argument("--lr", type=float, default=4e-4)
    p_tr.add_argument("--batch-size", type=int, default=16)
    p_tr.add_argument("--micro-batch", type=int, default=4)
    p_tr.add_argument("--lambda-null", type=float, default=0.08)
    p_tr.add_argument("--think-frac", type=float, default=0.25)
    p_tr.add_argument("--target-layers", type=str, default="")
    p_tr.add_argument("--max-per-fact", type=int, default=0)
    p_tr.add_argument("--smoke-test", action="store_true")

    p_mg = sub.add_parser("merge")
    p_mg.add_argument("--adapters", type=Path, nargs="+", required=True)
    p_mg.add_argument("--out", type=Path, required=True)
    p_mg.add_argument("--rank", type=int, default=96)

    p_es = sub.add_parser("eval-study")
    p_es.add_argument("--adapter", type=Path, required=True)
    p_es.add_argument("--qa-cache", type=Path, required=True)
    p_es.add_argument("--out", type=Path, required=True)
    p_es.add_argument("--port", type=int, default=8161)

    args = ap.parse_args()
    if args.cmd == "synthesize-qa":
        cmd_synthesize_qa(args.facts, args.out, port=args.port, n_llm_per_fact=args.n_llm)
    elif args.cmd == "train":
        only_ids = None
        if args.only_fact_ids is not None:
            data = json.loads(args.only_fact_ids.read_text(encoding="utf-8"))
            only_ids = set(data["missed_fact_ids"] if isinstance(data, dict) else data)
        t_layers = [int(x.strip()) for x in args.target_layers.split(",") if x.strip()] if args.target_layers else None
        cmd_train(
            facts_path=args.facts,
            qa_cache_path=args.qa_cache,
            out_gguf=args.out,
            save_keys_path=args.save_keys,
            protect_key_paths=args.protect_keys,
            base_adapter_path=args.base_adapter,
            init_adapter_path=args.init_adapter,
            only_fact_ids=only_ids,
            replay_qa_path=args.replay_qa,
            replay_per_fact=args.replay_per_fact,
            rank=args.rank,
            epochs=args.epochs,
            lr=args.lr,
            batch_size=args.batch_size,
            micro_batch=args.micro_batch,
            lambda_null=args.lambda_null,
            think_frac=args.think_frac,
            n_llm_per_fact=args.n_llm,
            smoke_test=args.smoke_test,
            target_layers=t_layers,
            max_per_fact=args.max_per_fact,
        )
    elif args.cmd == "merge":
        cmd_merge(args.adapters, args.out, target_rank=args.rank)
    elif args.cmd == "eval-study":
        cmd_eval_study(args.adapter, args.qa_cache, args.out, port=args.port)


if __name__ == "__main__":
    main()