File size: 39,579 Bytes
7215e83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

MudraForge Continual Learning — Layer 1: Fast Episodic Correction Memory (M1 & M2)

==================================================================================

Implements similarity-gated non-parametric episodic memory over frozen/slow encoder

representations for instant 1-shot continual learning with mathematically zero

catastrophic forgetting on unrelated statutes:



  - Stage 1 Token Memory (M1):

      Stores L2-normalized 256D contextual token embeddings u_k paired with verified

      BILOU tag targets y_k. At inference, computes cosine similarity against all

      entries; ONLY when max cosine similarity exceeds threshold tau_1 (default 0.88),

      fuses a similarity-weighted logit residual Delta_l BEFORE exact CRF Viterbi

      decoding + hard legal rules (guaranteeing 100% valid BILOU spans and exact

      0.00% perturbation on unrelated statutes).



  - Stage 2 Clause Span Memory (M2):

      Stores L2-normalized 128D candidate span embeddings v_k paired with verified

      clause class targets (including explicit 'O' entries to suppress recurring

      false positives such as duplicate overlapping INLINE_DEFs). Fuses logit

      residuals BEFORE Shannon hard constraints and NMS decoding.



Strictly zero regex (AST-audited). Persists to E:\\mudraforge_parser\\memory\\.

"""

from __future__ import annotations
import os

import ast
from datetime import datetime, timezone
import json
from pathlib import Path
from typing import Any

import torch
import torch.nn.functional as F

ROOT_DIR = Path(os.environ.get("MUDRAFORGE_ROOT", str(Path(__file__).resolve().parent.parent)))
MEM_DIR = ROOT_DIR / "memory"
MEM_DIR.mkdir(parents=True, exist_ok=True)


def audit_zero_regex(file_path: str | Path) -> None:
    tree = ast.parse(Path(file_path).read_text(encoding="utf-8"))
    for node in ast.walk(tree):
        if isinstance(node, ast.Import) and any(a.name == "re" for a in node.names):
            raise RuntimeError(f"Regex import forbidden in {file_path}")
        if isinstance(node, ast.ImportFrom) and node.module == "re":
            raise RuntimeError(f"Regex import forbidden in {file_path}")


def _build_3tok_window_keys(h: torch.Tensor) -> torch.Tensor:
    """Builds L2-normalized 3-token local window vectors [h_{t-1} || h_t || h_{t+1}] of shape [T, 3*D]."""
    T, D = h.shape
    h_f = h.detach().float()
    if T == 0:
        return torch.zeros(0, 3 * D, dtype=torch.float32, device=h.device)
    z = torch.zeros(1, D, dtype=torch.float32, device=h.device)
    h_prev = torch.cat([z, h_f[:-1]], dim=0)
    h_next = torch.cat([h_f[1:], z], dim=0)
    win = torch.cat([h_prev, h_f, h_next], dim=-1)  # [T, 3*D]
    return F.normalize(win, p=2, dim=-1)


class EpisodicMemoryBank:
    """Dual-stage fast episodic correction memory (M1 Stage 1 tokens + M2 Stage 2 spans)."""

    def __init__(

        self,

        mem_dir: Path = MEM_DIR,

        s1_tau: float = 0.94,

        s1_temp: float = 0.05,

        s1_beta: float = 12.0,

        s1_topk: int = 5,

        s15_tau: float = 0.94,

        s15_neg_tau: float = 0.965,

        s15_temp: float = 0.05,

        s15_beta: float = 22.0,

        s15_topk: int = 5,

        s15_span_tau: float = 0.945,

        s2_tau: float = 0.975,

        s2_temp: float = 0.05,

        s2_beta: float = 8.0,

        s2_topk: int = 5,

    ):
        self.mem_dir = Path(mem_dir)
        self.mem_dir.mkdir(parents=True, exist_ok=True)
        self.s1_pt_path = self.mem_dir / "stage1_episodic_m1.pt"
        self.s15_pt_path = self.mem_dir / "stage1_5_episodic_m15.pt"
        self.s15_span_pt_path = self.mem_dir / "stage1_5_episodic_m15_span.pt"
        self.s2_pt_path = self.mem_dir / "stage2_episodic_m2.pt"
        self.s1_log_path = self.mem_dir / "stage1_corrections.json"
        self.s15_log_path = self.mem_dir / "stage1_5_corrections.json"
        self.s15_span_log_path = self.mem_dir / "stage1_5_open_leaves.json"
        self.s2_log_path = self.mem_dir / "stage2_corrections.json"

        self.s1_tau = float(s1_tau)
        self.s1_temp = float(s1_temp)
        self.s1_beta = float(s1_beta)
        self.s1_topk = int(s1_topk)

        self.s15_tau = float(s15_tau)
        self.s15_neg_tau = float(s15_neg_tau)
        self.s15_temp = float(s15_temp)
        self.s15_beta = float(s15_beta)
        self.s15_topk = int(s15_topk)
        self.s15_span_tau = float(s15_span_tau)

        self.s2_tau = float(s2_tau)
        self.s2_temp = float(s2_temp)
        self.s2_beta = float(s2_beta)
        self.s2_topk = int(s2_topk)

        # In-memory CPU tensors (moved lazily to device at query time)
        self.m1_keys: torch.Tensor = torch.zeros(0, 256, dtype=torch.float32)
        self.m1_vals: torch.Tensor = torch.zeros(0, dtype=torch.long)
        self.m1_weights: torch.Tensor = torch.zeros(0, dtype=torch.float32)
        self.m1_meta: list[dict[str, Any]] = []

        self.m15_keys: torch.Tensor = torch.zeros(0, 256, dtype=torch.float32)
        self.m15_vals: torch.Tensor = torch.zeros(0, dtype=torch.long)
        self.m15_weights: torch.Tensor = torch.zeros(0, dtype=torch.float32)
        self.m15_meta: list[dict[str, Any]] = []

        # Negative 'O' suppression bank keyed on normalized 3-token local window [h_{t-1} || h_t || h_{t+1}] (768D)
        # Prevents suppressing a shared adjective (e.g. 'separate maintenance') from bleeding onto 'separate return'.
        self.m15_neg_keys: torch.Tensor = torch.zeros(0, 768, dtype=torch.float32)
        self.m15_neg_weights: torch.Tensor = torch.zeros(0, dtype=torch.float32)
        self.m15_neg_meta: list[dict[str, Any]] = []

        # Tier 2 Stage 1.5 Pooled-Span Open-Set Dynamic Leaf Bank:
        #   m15_span_keys     : [N, 256] normalized contextual span vector v_span / ||v_span||_2
        #   m15_span_lex_keys : [N, 368] normalized mean lexical/subword vector v_lex / ||v_lex||_2
        self.m15_span_keys: torch.Tensor = torch.zeros(0, 256, dtype=torch.float32)
        self.m15_span_lex_keys: torch.Tensor = torch.zeros(0, 368, dtype=torch.float32)
        self.m15_span_meta: list[dict[str, Any]] = []

        self.m2_keys: torch.Tensor = torch.zeros(0, 128, dtype=torch.float32)
        self.m2_vals: torch.Tensor = torch.zeros(0, dtype=torch.long)
        self.m2_weights: torch.Tensor = torch.zeros(0, dtype=torch.float32)
        self.m2_meta: list[dict[str, Any]] = []

        self.s1_corrections: list[dict[str, Any]] = []
        self.s15_corrections: list[dict[str, Any]] = []
        self.s15_open_leaves: list[dict[str, Any]] = []
        self.s2_corrections: list[dict[str, Any]] = []

        self.load()

    def load(self) -> None:
        if self.s1_pt_path.exists():
            d1 = torch.load(self.s1_pt_path, map_location="cpu", weights_only=False)
            self.m1_keys = d1["keys"].float()
            self.m1_vals = d1["vals"].long()
            self.m1_weights = d1["weights"].float()
            self.m1_meta = d1.get("meta", [])
        if self.s15_pt_path.exists():
            d15 = torch.load(self.s15_pt_path, map_location="cpu", weights_only=False)
            self.m15_keys = d15["keys"].float()
            self.m15_vals = d15["vals"].long()
            self.m15_weights = d15["weights"].float()
            self.m15_meta = d15.get("meta", [])
            self.m15_neg_keys = d15.get("neg_keys", torch.zeros(0, 768, dtype=torch.float32)).float()
            self.m15_neg_weights = d15.get("neg_weights", torch.zeros(0, dtype=torch.float32)).float()
            self.m15_neg_meta = d15.get("neg_meta", [])
        if self.s15_span_pt_path.exists():
            d15s = torch.load(self.s15_span_pt_path, map_location="cpu", weights_only=False)
            self.m15_span_keys = d15s["keys"].float()
            self.m15_span_lex_keys = d15s.get("lex_keys", torch.zeros(self.m15_span_keys.size(0), 368, dtype=torch.float32)).float()
            self.m15_span_meta = d15s.get("meta", [])
        if self.s2_pt_path.exists():
            d2 = torch.load(self.s2_pt_path, map_location="cpu", weights_only=False)
            self.m2_keys = d2["keys"].float()
            self.m2_vals = d2["vals"].long()
            self.m2_weights = d2["weights"].float()
            self.m2_meta = d2.get("meta", [])
        if self.s1_log_path.exists():
            self.s1_corrections = json.loads(self.s1_log_path.read_text(encoding="utf-8"))
        if self.s15_log_path.exists():
            self.s15_corrections = json.loads(self.s15_log_path.read_text(encoding="utf-8"))
        if self.s15_span_log_path.exists():
            self.s15_open_leaves = json.loads(self.s15_span_log_path.read_text(encoding="utf-8"))
        if self.s2_log_path.exists():
            self.s2_corrections = json.loads(self.s2_log_path.read_text(encoding="utf-8"))

    def save(self) -> None:
        torch.save(
            {
                "keys": self.m1_keys.cpu(),
                "vals": self.m1_vals.cpu(),
                "weights": self.m1_weights.cpu(),
                "meta": self.m1_meta,
            },
            self.s1_pt_path,
        )
        torch.save(
            {
                "keys": self.m15_keys.cpu(),
                "vals": self.m15_vals.cpu(),
                "weights": self.m15_weights.cpu(),
                "meta": self.m15_meta,
                "neg_keys": self.m15_neg_keys.cpu(),
                "neg_weights": self.m15_neg_weights.cpu(),
                "neg_meta": self.m15_neg_meta,
            },
            self.s15_pt_path,
        )
        torch.save(
            {
                "keys": self.m15_span_keys.cpu(),
                "lex_keys": self.m15_span_lex_keys.cpu(),
                "meta": self.m15_span_meta,
            },
            self.s15_span_pt_path,
        )
        torch.save(
            {
                "keys": self.m2_keys.cpu(),
                "vals": self.m2_vals.cpu(),
                "weights": self.m2_weights.cpu(),
                "meta": self.m2_meta,
            },
            self.s2_pt_path,
        )
        self.s1_log_path.write_text(json.dumps(self.s1_corrections, indent=2, ensure_ascii=False), encoding="utf-8")
        self.s15_log_path.write_text(json.dumps(self.s15_corrections, indent=2, ensure_ascii=False), encoding="utf-8")
        self.s15_span_log_path.write_text(json.dumps(self.s15_open_leaves, indent=2, ensure_ascii=False), encoding="utf-8")
        self.s2_log_path.write_text(json.dumps(self.s2_corrections, indent=2, ensure_ascii=False), encoding="utf-8")

    def clear_fast_vectors(self, stage: str = "all") -> None:
        """Clear fast episodic vectors after successful slow-weight consolidation (keeps verified replay log)."""
        if stage in ("stage1", "both", "all"):
            self.m1_keys = torch.zeros(0, 256, dtype=torch.float32)
            self.m1_vals = torch.zeros(0, dtype=torch.long)
            self.m1_weights = torch.zeros(0, dtype=torch.float32)
            self.m1_meta = []
        if stage in ("stage1_5", "stage1_5_tok", "all"):
            self.m15_keys = torch.zeros(0, 256, dtype=torch.float32)
            self.m15_vals = torch.zeros(0, dtype=torch.long)
            self.m15_weights = torch.zeros(0, dtype=torch.float32)
            self.m15_meta = []
            self.m15_neg_keys = torch.zeros(0, 768, dtype=torch.float32)
            self.m15_neg_weights = torch.zeros(0, dtype=torch.float32)
            self.m15_neg_meta = []
        if stage in ("stage1_5_span", "all"):
            self.m15_span_keys = torch.zeros(0, 256, dtype=torch.float32)
            self.m15_span_lex_keys = torch.zeros(0, 368, dtype=torch.float32)
            self.m15_span_meta = []
        if stage in ("stage2", "both", "all"):
            self.m2_keys = torch.zeros(0, 128, dtype=torch.float32)
            self.m2_vals = torch.zeros(0, dtype=torch.long)
            self.m2_weights = torch.zeros(0, dtype=torch.float32)
            self.m2_meta = []
        self.save()

    def add_stage1_correction(

        self,

        doc_record: dict[str, Any],

        token_hidden: torch.Tensor,

        gold_tag_ids: list[int],

        pred_tag_ids: list[int] | None = None,

        store_only_errors: bool = True,

        neighbor_radius: int = 0,

    ) -> int:
        """

        Store corrected Stage 1 token embeddings into Fast Memory M1 and append the full

        verified document to stage1_corrections.json for Layer 2 EWC consolidation.

        Returns number of token vectors added to M1.

        """
        h_cpu = token_hidden.detach().float().cpu()
        if h_cpu.ndim == 3:
            h_cpu = h_cpu[0]
        T = min(h_cpu.size(0), len(gold_tag_ids))
        h_norm = F.normalize(h_cpu[:T], p=2, dim=-1)

        if store_only_errors and pred_tag_ids is not None:
            err_idxs = {i for i in range(T) if pred_tag_ids[i] != gold_tag_ids[i]}
            target_idxs: set[int] = set()
            for ei in err_idxs:
                for off in range(-neighbor_radius, neighbor_radius + 1):
                    j = ei + off
                    if 0 <= j < T:
                        target_idxs.add(j)
            chosen = sorted(target_idxs)
        else:
            chosen = list(range(T))

        ts_now = datetime.now(timezone.utc).isoformat()
        doc_id = doc_record["id"]

        # Deduplicate existing M1 vectors for this doc_id on upsert
        if self.m1_keys.size(0) > 0 and self.m1_meta:
            keep = [i for i, m in enumerate(self.m1_meta) if m.get("doc_id") != doc_id]
            if len(keep) < len(self.m1_meta):
                if keep:
                    idx_t = torch.tensor(keep, dtype=torch.long)
                    self.m1_keys = self.m1_keys[idx_t]
                    self.m1_vals = self.m1_vals[idx_t]
                    self.m1_weights = self.m1_weights[idx_t]
                    self.m1_meta = [self.m1_meta[i] for i in keep]
                else:
                    self.m1_keys = torch.zeros(0, 256, dtype=torch.float32)
                    self.m1_vals = torch.zeros(0, dtype=torch.long)
                    self.m1_weights = torch.zeros(0, dtype=torch.float32)
                    self.m1_meta = []

        new_keys = []
        new_vals = []
        new_w = []
        for idx in chosen:
            is_err = (pred_tag_ids is None) or (pred_tag_ids[idx] != gold_tag_ids[idx])
            new_keys.append(h_norm[idx])
            new_vals.append(int(gold_tag_ids[idx]))
            new_w.append(1.0 if is_err else 0.45)
            self.m1_meta.append({
                "doc_id": doc_id,
                "tok_idx": idx,
                "token": doc_record["tokens"][idx],
                "tag_id": int(gold_tag_ids[idx]),
                "is_direct_error": is_err,
                "timestamp": ts_now,
            })

        if new_keys:
            nk = torch.stack(new_keys, dim=0)
            nv = torch.tensor(new_vals, dtype=torch.long)
            nw = torch.tensor(new_w, dtype=torch.float32)
            if self.m1_keys.size(0) == 0:
                self.m1_keys, self.m1_vals, self.m1_weights = nk, nv, nw
            else:
                self.m1_keys = torch.cat([self.m1_keys, nk], dim=0)
                self.m1_vals = torch.cat([self.m1_vals, nv], dim=0)
                self.m1_weights = torch.cat([self.m1_weights, nw], dim=0)

        # Upsert full verified doc in replay log (dedup by doc_id)
        entry = dict(doc_record)
        entry["consolidated"] = False
        entry["added_at"] = ts_now
        self.s1_corrections = [c for c in self.s1_corrections if c.get("id") != entry["id"]]
        self.s1_corrections.append(entry)
        self.save()
        return len(new_keys)

    def query_stage1_delta(

        self,

        token_hidden: torch.Tensor,

        num_tags: int,

    ) -> tuple[torch.Tensor, int]:
        """

        Compute similarity-gated Stage 1 logit residual Delta_l [1, T, num_tags].

        Returns (delta_logits, num_activated_tokens).

        When cosine similarity <= s1_tau, Delta_l is EXACTLY 0.0 (zero forgetting).

        """
        device = token_hidden.device
        h = token_hidden[0] if token_hidden.ndim == 3 else token_hidden
        T = h.size(0)
        delta = torch.zeros(T, num_tags, dtype=torch.float32, device=device)

        if self.m1_keys.size(0) == 0:
            return delta.unsqueeze(0), 0

        q = F.normalize(h.detach().float(), p=2, dim=-1)  # [T, 256]
        keys = self.m1_keys.to(device)                    # [M, 256]
        vals = self.m1_vals.to(device)                    # [M]
        wts = self.m1_weights.to(device)                  # [M]

        sims = torch.matmul(q, keys.t())                  # [T, M]
        k_eff = min(self.s1_topk, keys.size(0))
        top_sims, top_idx = torch.topk(sims, k=k_eff, dim=-1)  # [T, k_eff]
        max_sim = top_sims[:, 0]                          # [T]

        active_mask = max_sim > self.s1_tau
        n_act = int(active_mask.sum().item())
        if n_act == 0:
            return delta.unsqueeze(0), 0

        # Smooth gate alpha_t in (0, 1] strictly above tau
        alpha = ((max_sim - self.s1_tau) / max(1e-6, 1.0 - self.s1_tau)).clamp(0.0, 1.0)
        # Zero out neighbors below tau so low-sim entries never pollute top-K average
        nbr_mask = top_sims > self.s1_tau
        masked_sims = top_sims.masked_fill(~nbr_mask, -1e9)
        attn = F.softmax(masked_sims / self.s1_temp, dim=-1) * nbr_mask.float()  # [T, k_eff]
        attn = attn * wts[top_idx]
        attn = attn / attn.sum(dim=-1, keepdim=True).clamp(min=1e-6)

        act_rows = torch.nonzero(active_mask, as_tuple=False).squeeze(-1)
        for t in act_rows.tolist():
            a_t = float(alpha[t].item()) * self.s1_beta
            for j in range(k_eff):
                w_j = float(attn[t, j].item())
                if w_j > 0.0:
                    tag_id = int(vals[top_idx[t, j]].item())
                    delta[t, tag_id] += a_t * w_j

        return delta.unsqueeze(0), n_act

    def add_stage2_correction(

        self,

        doc_record: dict[str, Any],

        span_embs: torch.Tensor,

        span_targets: list[int],

        span_coords: list[tuple[int, int]],

        pred_cls_ids: list[int] | None = None,

    ) -> int:
        """

        Store corrected Stage 2 candidate span embeddings (128D) into Fast Memory M2

        (including explicit 'O' = 0 suppressions for false positives) and append the full

        verified document to stage2_corrections.json for Layer 2 EWC consolidation.

        """
        z_cpu = span_embs.detach().float().cpu()
        K = min(z_cpu.size(0), len(span_targets))
        z_norm = F.normalize(z_cpu[:K], p=2, dim=-1)

        ts_now = datetime.now(timezone.utc).isoformat()
        doc_id = doc_record["id"]

        # Deduplicate existing M2 vectors for this doc_id on upsert
        if self.m2_keys.size(0) > 0 and self.m2_meta:
            keep = [i for i, m in enumerate(self.m2_meta) if m.get("doc_id") != doc_id]
            if len(keep) < len(self.m2_meta):
                if keep:
                    idx_t = torch.tensor(keep, dtype=torch.long)
                    self.m2_keys = self.m2_keys[idx_t]
                    self.m2_vals = self.m2_vals[idx_t]
                    self.m2_weights = self.m2_weights[idx_t]
                    self.m2_meta = [self.m2_meta[i] for i in keep]
                else:
                    self.m2_keys = torch.zeros(0, 128, dtype=torch.float32)
                    self.m2_vals = torch.zeros(0, dtype=torch.long)
                    self.m2_weights = torch.zeros(0, dtype=torch.float32)
                    self.m2_meta = []

        new_keys = []
        new_vals = []
        new_w = []
        for idx in range(K):
            if pred_cls_ids is not None and pred_cls_ids[idx] == span_targets[idx]:
                continue
            new_keys.append(z_norm[idx])
            new_vals.append(int(span_targets[idx]))
            new_w.append(1.0)
            self.m2_meta.append({
                "doc_id": doc_id,
                "span": list(span_coords[idx]),
                "cls_id": int(span_targets[idx]),
                "timestamp": ts_now,
            })

        if new_keys:
            nk = torch.stack(new_keys, dim=0)
            nv = torch.tensor(new_vals, dtype=torch.long)
            nw = torch.tensor(new_w, dtype=torch.float32)
            if self.m2_keys.size(0) == 0:
                self.m2_keys, self.m2_vals, self.m2_weights = nk, nv, nw
            else:
                self.m2_keys = torch.cat([self.m2_keys, nk], dim=0)
                self.m2_vals = torch.cat([self.m2_vals, nv], dim=0)
                self.m2_weights = torch.cat([self.m2_weights, nw], dim=0)

        entry = dict(doc_record)
        entry["consolidated"] = False
        entry["added_at"] = ts_now
        self.s2_corrections = [c for c in self.s2_corrections if c.get("id") != entry["id"]]
        self.s2_corrections.append(entry)
        self.save()
        return len(new_keys)

    def query_stage2_delta(

        self,

        span_embs: torch.Tensor,

        num_classes: int,

    ) -> tuple[torch.Tensor, int]:
        """

        Compute similarity-gated Stage 2 span logit residual Delta_l [K, num_classes].

        Returns (delta_logits, num_activated_spans).

        """
        device = span_embs.device
        K = span_embs.size(0)
        delta = torch.zeros(K, num_classes, dtype=torch.float32, device=device)
        if K == 0 or self.m2_keys.size(0) == 0:
            return delta, 0

        q = F.normalize(span_embs.detach().float(), p=2, dim=-1)  # [K, 128]
        keys = self.m2_keys.to(device)
        vals = self.m2_vals.to(device)
        wts = self.m2_weights.to(device)

        sims = torch.matmul(q, keys.t())
        k_eff = min(self.s2_topk, keys.size(0))
        top_sims, top_idx = torch.topk(sims, k=k_eff, dim=-1)
        max_sim = top_sims[:, 0]

        active_mask = max_sim > self.s2_tau
        n_act = int(active_mask.sum().item())
        if n_act == 0:
            return delta, 0

        alpha = ((max_sim - self.s2_tau) / max(1e-6, 1.0 - self.s2_tau)).clamp(0.0, 1.0)
        nbr_mask = top_sims > self.s2_tau
        masked_sims = top_sims.masked_fill(~nbr_mask, -1e9)
        attn = F.softmax(masked_sims / self.s2_temp, dim=-1) * nbr_mask.float()
        attn = attn * wts[top_idx]
        attn = attn / attn.sum(dim=-1, keepdim=True).clamp(min=1e-6)

        act_rows = torch.nonzero(active_mask, as_tuple=False).squeeze(-1)
        for r in act_rows.tolist():
            a_r = float(alpha[r].item()) * self.s2_beta
            for j in range(k_eff):
                w_j = float(attn[r, j].item())
                if w_j > 0.0:
                    cls_id = int(vals[top_idx[r, j]].item())
                    delta[r, cls_id] += a_r * w_j

        return delta, n_act

    def add_stage1_5_correction(

        self,

        doc_record: dict[str, Any],

        token_hidden: torch.Tensor,

        gold_tag_ids: list[int],

        pred_tag_ids: list[int] | None = None,

        store_only_errors: bool = True,

    ) -> int:
        """

        Store corrected Stage 1.5 operand token embeddings (256D conditioned) into Fast Memory M1.5

        (with doc_id deduplication on upsert) and append the full verified document to

        stage1_5_corrections.json for Layer 2 EWC consolidation.

        """
        h_cpu = token_hidden.detach().float().cpu()
        if h_cpu.ndim == 3:
            h_cpu = h_cpu[0]
        T = min(h_cpu.size(0), len(gold_tag_ids))
        h_norm = F.normalize(h_cpu[:T], p=2, dim=-1)
        h_win = _build_3tok_window_keys(h_cpu[:T])  # [T, 768] for negative 'O' suppressions

        if store_only_errors and pred_tag_ids is not None:
            chosen = sorted(i for i in range(T) if pred_tag_ids[i] != gold_tag_ids[i])
        else:
            chosen = list(range(T))

        ts_now = datetime.now(timezone.utc).isoformat()
        doc_id = doc_record["id"]

        if self.m15_keys.size(0) > 0 and self.m15_meta:
            keep = [i for i, m in enumerate(self.m15_meta) if m.get("doc_id") != doc_id]
            if len(keep) < len(self.m15_meta):
                if keep:
                    idx_t = torch.tensor(keep, dtype=torch.long)
                    self.m15_keys = self.m15_keys[idx_t]
                    self.m15_vals = self.m15_vals[idx_t]
                    self.m15_weights = self.m15_weights[idx_t]
                    self.m15_meta = [self.m15_meta[i] for i in keep]
                else:
                    self.m15_keys = torch.zeros(0, 256, dtype=torch.float32)
                    self.m15_vals = torch.zeros(0, dtype=torch.long)
                    self.m15_weights = torch.zeros(0, dtype=torch.float32)
                    self.m15_meta = []

        if self.m15_neg_keys.size(0) > 0 and self.m15_neg_meta:
            keep_n = [i for i, m in enumerate(self.m15_neg_meta) if m.get("doc_id") != doc_id]
            if len(keep_n) < len(self.m15_neg_meta):
                if keep_n:
                    idx_n = torch.tensor(keep_n, dtype=torch.long)
                    self.m15_neg_keys = self.m15_neg_keys[idx_n]
                    self.m15_neg_weights = self.m15_neg_weights[idx_n]
                    self.m15_neg_meta = [self.m15_neg_meta[i] for i in keep_n]
                else:
                    self.m15_neg_keys = torch.zeros(0, 768, dtype=torch.float32)
                    self.m15_neg_weights = torch.zeros(0, dtype=torch.float32)
                    self.m15_neg_meta = []

        new_keys, new_vals, new_w = [], [], []
        new_neg_keys, new_neg_w = [], []
        for idx in chosen:
            is_err = (pred_tag_ids is None) or (pred_tag_ids[idx] != gold_tag_ids[idx])
            g_id = int(gold_tag_ids[idx])
            w_val = 1.0 if is_err else 0.45
            meta_row = {
                "doc_id": doc_id,
                "tok_idx": idx,
                "token": doc_record["tokens"][idx],
                "tag_id": g_id,
                "is_direct_error": is_err,
                "timestamp": ts_now,
            }
            if g_id == 0:
                # Negative 'O' suppression -> 3-token local window key [h_{t-1} || h_t || h_{t+1}] (768D)
                new_neg_keys.append(h_win[idx])
                new_neg_w.append(w_val)
                self.m15_neg_meta.append(meta_row)
            else:
                new_keys.append(h_norm[idx])
                new_vals.append(g_id)
                new_w.append(w_val)
                self.m15_meta.append(meta_row)

        if new_keys:
            nk = torch.stack(new_keys, dim=0)
            nv = torch.tensor(new_vals, dtype=torch.long)
            nw = torch.tensor(new_w, dtype=torch.float32)
            if self.m15_keys.size(0) == 0:
                self.m15_keys, self.m15_vals, self.m15_weights = nk, nv, nw
            else:
                self.m15_keys = torch.cat([self.m15_keys, nk], dim=0)
                self.m15_vals = torch.cat([self.m15_vals, nv], dim=0)
                self.m15_weights = torch.cat([self.m15_weights, nw], dim=0)

        if new_neg_keys:
            nnk = torch.stack(new_neg_keys, dim=0)
            nnw = torch.tensor(new_neg_w, dtype=torch.float32)
            if self.m15_neg_keys.size(0) == 0:
                self.m15_neg_keys, self.m15_neg_weights = nnk, nnw
            else:
                self.m15_neg_keys = torch.cat([self.m15_neg_keys, nnk], dim=0)
                self.m15_neg_weights = torch.cat([self.m15_neg_weights, nnw], dim=0)

        entry = dict(doc_record)
        entry["consolidated"] = False
        entry["added_at"] = ts_now
        self.s15_corrections = [c for c in self.s15_corrections if c.get("id") != entry["id"]]
        self.s15_corrections.append(entry)
        self.save()
        return len(new_keys) + len(new_neg_keys)

    def query_stage1_5_delta(

        self,

        token_hidden: torch.Tensor,

        num_tags: int = 17,

    ) -> tuple[torch.Tensor, int]:
        """

        Compute similarity-gated Stage 1.5 logit residual Delta_m15 [T, num_tags]:

          - Positive operand additions (tag_id > 0): single-token key q_256 > s15_tau (0.94)

          - Negative 'O' suppressions (tag_id == 0): 3-token window key [h_{t-1}||h_t||h_{t+1}]

            q_768 > s15_neg_tau (0.965), preventing shared adjectives from bleeding across phrases.

        Returns (delta_logits, num_activated_tokens).

        """
        device = token_hidden.device
        h = token_hidden[0] if token_hidden.ndim == 3 else token_hidden
        T = h.size(0)
        delta = torch.zeros(T, num_tags, dtype=torch.float32, device=device)
        if T == 0 or (self.m15_keys.size(0) == 0 and self.m15_neg_keys.size(0) == 0):
            return delta, 0

        activated_positions: set[int] = set()

        # 1. Positive operand additions (256D token key, tau = s15_tau)
        if self.m15_keys.size(0) > 0:
            q = F.normalize(h.detach().float(), p=2, dim=-1)  # [T, 256]
            keys = self.m15_keys.to(device)
            vals = self.m15_vals.to(device)
            wts = self.m15_weights.to(device)

            sims = torch.matmul(q, keys.t())
            k_eff = min(self.s15_topk, keys.size(0))
            top_sims, top_idx = torch.topk(sims, k=k_eff, dim=-1)
            max_sim = top_sims[:, 0]

            active_mask = max_sim > self.s15_tau
            if int(active_mask.sum().item()) > 0:
                alpha = ((max_sim - self.s15_tau) / max(1e-6, 1.0 - self.s15_tau)).clamp(0.0, 1.0)
                nbr_mask = top_sims > self.s15_tau
                masked_sims = top_sims.masked_fill(~nbr_mask, -1e9)
                attn = F.softmax(masked_sims / self.s15_temp, dim=-1) * nbr_mask.float()
                attn = attn * wts[top_idx]
                attn = attn / attn.sum(dim=-1, keepdim=True).clamp(min=1e-6)

                act_rows = torch.nonzero(active_mask, as_tuple=False).squeeze(-1)
                for t in act_rows.tolist():
                    activated_positions.add(t)
                    a_t = float(alpha[t].item()) * self.s15_beta
                    for j in range(k_eff):
                        w_j = float(attn[t, j].item())
                        if w_j > 0.0:
                            tag_id = int(vals[top_idx[t, j]].item())
                            delta[t, tag_id] += a_t * w_j

        # 2. Negative 'O' suppressions (768D 3-token local window key, tau = s15_neg_tau)
        if self.m15_neg_keys.size(0) > 0:
            q_win = _build_3tok_window_keys(h)  # [T, 768]
            nkeys = self.m15_neg_keys.to(device)
            nwts = self.m15_neg_weights.to(device)

            nsims = torch.matmul(q_win, nkeys.t())
            nk_eff = min(self.s15_topk, nkeys.size(0))
            ntop_sims, ntop_idx = torch.topk(nsims, k=nk_eff, dim=-1)
            nmax_sim = ntop_sims[:, 0]

            nactive_mask = nmax_sim > self.s15_neg_tau
            if int(nactive_mask.sum().item()) > 0:
                nalpha = ((nmax_sim - self.s15_neg_tau) / max(1e-6, 1.0 - self.s15_neg_tau)).clamp(0.0, 1.0)
                nact_rows = torch.nonzero(nactive_mask, as_tuple=False).squeeze(-1)
                for t in nact_rows.tolist():
                    activated_positions.add(t)
                    delta[t, 0] += float(nalpha[t].item()) * self.s15_beta

        return delta, len(activated_positions)

    def add_stage1_5_span_leaf(

        self,

        doc_id: str,

        text: str,

        span_text: str,

        tok_start: int,

        tok_end: int,

        span_vec: torch.Tensor,

        root_branch: str,

        catala_leaf: str,

        lex_vec: torch.Tensor | None = None,

        catala_variable: str | None = None,

        catala_declaration: str | None = None,

        usvm_key: str | None = None,

    ) -> dict[str, Any]:
        """

        Tier 2 Stage 1.5 Pooled-Span Open-Set Dynamic Leaf Registration:

        Stores L2-normalized contextual span vector u_k = v_span / ||v_span||_2 in R^256

        paired with L2-normalized mean lexical vector l_k = v_lex / ||v_lex||_2 in R^368

        to prevent cross-span collisions ('value of supply' vs 'value of benefit') while

        preserving open-set leaf recall across clause contexts.

        """
        v_cpu = span_vec.detach().float().cpu()
        if v_cpu.ndim == 2:
            v_cpu = v_cpu[0]
        v_norm = F.normalize(v_cpu, p=2, dim=-1).unsqueeze(0)  # [1, 256]

        if lex_vec is not None:
            l_cpu = lex_vec.detach().float().cpu()
            if l_cpu.ndim == 2:
                l_cpu = l_cpu[0]
            l_norm = F.normalize(l_cpu, p=2, dim=-1).unsqueeze(0)  # [1, 368]
        else:
            l_norm = torch.zeros(1, 368, dtype=torch.float32)

        ts_now = datetime.now(timezone.utc).isoformat()
        span_key = span_text.strip().lower()

        if self.m15_span_keys.size(0) > 0 and self.m15_span_meta:
            keep = [
                i for i, m in enumerate(self.m15_span_meta)
                if not (m.get("doc_id") == doc_id and m.get("span_text", "").strip().lower() == span_key)
            ]
            if len(keep) < len(self.m15_span_meta):
                if keep:
                    idx_t = torch.tensor(keep, dtype=torch.long)
                    self.m15_span_keys = self.m15_span_keys[idx_t]
                    self.m15_span_lex_keys = self.m15_span_lex_keys[idx_t]
                    self.m15_span_meta = [self.m15_span_meta[i] for i in keep]
                else:
                    self.m15_span_keys = torch.zeros(0, 256, dtype=torch.float32)
                    self.m15_span_lex_keys = torch.zeros(0, 368, dtype=torch.float32)
                    self.m15_span_meta = []

        var_name = catala_variable or catala_leaf.lower()
        meta_entry = {
            "doc_id": doc_id,
            "span_text": span_text,
            "root_branch": root_branch,
            "catala_leaf": catala_leaf,
            "catala_variable": var_name,
            "catala_declaration": catala_declaration or f"input {var_name} content money",
            "usvm_key": usvm_key or f"custom.{catala_leaf.lower()}",
            "timestamp": ts_now,
        }
        if self.m15_span_keys.size(0) == 0:
            self.m15_span_keys = v_norm
            self.m15_span_lex_keys = l_norm
        else:
            self.m15_span_keys = torch.cat([self.m15_span_keys, v_norm], dim=0)
            self.m15_span_lex_keys = torch.cat([self.m15_span_lex_keys, l_norm], dim=0)
        self.m15_span_meta.append(meta_entry)

        open_rec = {
            "doc_id": doc_id,
            "text": text,
            "span_text": span_text,
            "tokStart": int(tok_start),
            "tokEnd": int(tok_end),
            "root_branch": root_branch,
            "catala_leaf": catala_leaf,
            "catala_variable": meta_entry["catala_variable"],
            "catala_declaration": meta_entry["catala_declaration"],
            "usvm_key": meta_entry["usvm_key"],
            "timestamp": ts_now,
        }
        self.s15_open_leaves = [
            r for r in self.s15_open_leaves
            if not (r.get("doc_id") == doc_id and r.get("span_text", "").strip().lower() == span_key)
        ]
        self.s15_open_leaves.append(open_rec)
        self.save()
        return meta_entry

    def query_stage1_5_span_leaf(

        self,

        v_spans: torch.Tensor,              # [K, 256]

        v_lex_spans: torch.Tensor | None = None,  # [K, 368]

    ) -> list[tuple[dict[str, Any] | None, float]]:
        """

        Dual-Gate Pooled-Span Open-Set Leaf Matcher:

          - Gate 1 (Contextual + Lexical Combined): 0.5 * (cos_span + cos_lex) >= s15_span_tau (0.945)

          - Gate 2 (Exact Lexical Concept across Different Clause Roles):

            cos_lex >= 0.995 AND cos_span >= 0.70

        Prevents cross-span collisions ('value of supply' vs 'value of benefit': comb=0.913, lex=0.895)

        while matching the same novel concept across clauses.

        """
        K = v_spans.size(0) if v_spans.ndim == 2 else 1
        if K == 0 or self.m15_span_keys.size(0) == 0:
            return [(None, 0.0) for _ in range(K)]

        q_sp = F.normalize(v_spans.detach().float(), p=2, dim=-1)
        if q_sp.ndim == 1:
            q_sp = q_sp.unsqueeze(0)
        keys_sp = self.m15_span_keys.to(q_sp.device)
        sims_sp = torch.matmul(q_sp, keys_sp.t())  # [K, M]

        if v_lex_spans is not None and self.m15_span_lex_keys.size(0) == self.m15_span_keys.size(0):
            q_lx = F.normalize(v_lex_spans.detach().float(), p=2, dim=-1)
            if q_lx.ndim == 1:
                q_lx = q_lx.unsqueeze(0)
            keys_lx = self.m15_span_lex_keys.to(q_sp.device)
            sims_lx = torch.matmul(q_lx, keys_lx.t())  # [K, M]
            sims_comb = 0.5 * (sims_sp + sims_lx)
            has_lex = True
        else:
            sims_lx = sims_sp
            sims_comb = sims_sp
            has_lex = False

        out: list[tuple[dict[str, Any] | None, float]] = []
        for i in range(q_sp.size(0)):
            best_j = int(torch.argmax(sims_comb[i]).item())
            c_comb = float(sims_comb[i, best_j].item())
            c_sp = float(sims_sp[i, best_j].item())
            c_lx = float(sims_lx[i, best_j].item())
            gate1 = c_comb >= self.s15_span_tau
            gate2 = has_lex and (c_lx >= 0.995) and (c_sp >= 0.70)
            if gate1 or gate2:
                out.append((self.m15_span_meta[best_j], max(c_comb, c_lx if gate2 else c_comb)))
            else:
                out.append((None, c_comb))
        return out

    def summary(self) -> dict[str, Any]:
        return {
            "stage1_fast_vectors": int(self.m1_keys.size(0)),
            "stage1_verified_docs": len(self.s1_corrections),
            "stage1_unconsolidated_docs": sum(1 for c in self.s1_corrections if not c.get("consolidated", False)),
            "stage1_5_tok_vectors": int(self.m15_keys.size(0)),
            "stage1_5_neg_window_vectors": int(self.m15_neg_keys.size(0)),
            "stage1_5_span_leaf_vectors": int(self.m15_span_keys.size(0)),
            "stage1_5_verified_docs": len(self.s15_corrections),
            "stage1_5_unconsolidated_docs": sum(1 for c in self.s15_corrections if not c.get("consolidated", False)),
            "stage1_5_open_set_leaves": len(self.s15_open_leaves),
            "stage2_fast_vectors": int(self.m2_keys.size(0)),
            "stage2_verified_docs": len(self.s2_corrections),
            "stage2_unconsolidated_docs": sum(1 for c in self.s2_corrections if not c.get("consolidated", False)),
            "s1_tau": self.s1_tau,
            "s15_tau": self.s15_tau,
            "s15_neg_tau": self.s15_neg_tau,
            "s15_span_tau": self.s15_span_tau,
            "s2_tau": self.s2_tau,
        }


audit_zero_regex(__file__)