-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAgentMemorySystem.py
More file actions
2772 lines (2632 loc) · 153 KB
/
AgentMemorySystem.py
File metadata and controls
2772 lines (2632 loc) · 153 KB
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
#!/usr/bin/env python3
"""
嵌入级方案B · v3.12
════════════════════════════════════════════════════════════════════════
v3.12 变更摘要 (相对 v3.11)
─────────────────────────
[P0-RETRIEVE] 扩展词汇重叠门控 (expanded overlap gating)
新引入双层硬过滤:
第一层: expanded_overlap = |query_expanded_ids ∩ mem.content_token_ids|
- overlap > 0 → 直接通过 (有词汇连接)
- overlap = 0 → 进入第二层
第二层: forward_maxsim >= max(absolute, top_fwd * relative_ratio)
- 通过 → 保留; 否则拒绝
理由: forward_maxsim 在 query 和 memory 没有精确词汇重叠时, 只靠 wte 余弦
相似度区分域, 区分度不够 (GPT-2 wte 噪声地板 ~0.15-0.25).
expanded overlap 利用 wte 邻居扩展 (threshold=0.5) 在同域内建立词汇桥梁
(piano→pianist, practice→practiced), 同时跨域无桥 (piano → telescope 无扩展重叠).
query 侧用扩展 IDs (提高召回), memory 侧用精确 IDs (避免双重扩展的跨域桥接).
[P0-RETRIEVE] 每记忆 forward_maxsim 传播到 content_bias 权重
RetrievalDiag 新增 per_memory_forward_maxsim: Dict[int, float]
_build_content_bias 和 _compute_content_wte_mean 中, 每条记忆的权重乘以其
forward_maxsim 值. 即使有跨域记忆逃过硬过滤, 其 forward_maxsim 低, 对
content_bias 的贡献也被压低.
[P1-PREFIX] 提高前缀内容信号强度 (逻辑层面修复)
prefix_init_scale: -1.0 → -0.2 (sigmoid 从 0.27 提到 0.45)
content_inject_scale: 0.5 → 0.65
prefix_inject_last_multiplier: 3.0 → 4.0
prefix_inject_other_multiplier: 0.5 → 0.8
这使 prefix 在 LLM 注意力空间中的影响力提升约 67%.
注意: 这是逻辑层面的优化. GPT-2 soft prompt 的有效性上限受限于
GPT-2 未经 prompt tuning 训练, 此处不做过度补偿.
[P1-RETRIEVE] 合并域守卫更严
consol_maxsim_min: 0.30 → 0.40
防止 base 距离偶然靠近导致跨域合并
要求: pip install torch transformers
"""
import torch, torch.nn as nn, torch.nn.functional as F
import math, time, warnings
from typing import Dict, List, Tuple, Optional, NamedTuple, Set, FrozenSet
from dataclasses import dataclass, field
# ═══════════════════════════════════════════════════════════════════
# 配置
# ═══════════════════════════════════════════════════════════════════
@dataclass
class Cfg:
d_LLM: int = 768; d_M: int = 8; d_F: int = 32
L_mem: int = 8; n_heads_fiber: int = 4
bridge_heads: int = 4; bridge_layers: int = 2
n_geo_pts: int = 8; geo_max_steps: int = 80
geo_tol: float = 1e-5; geo_lr: float = 0.02
tree_K: int = 8; tree_max_leaf: int = 20
tau: float = 0.07
write_gate_threshold: float = 0.4
retention_gc_threshold: float = 0.15
consol_dist: float = 0.3; consol_conflict_ratio: float = 0.5
retrieval_topk: int = 8; retrieval_beam: int = 5
retrieval_interval: int = 8
retrieval_recall_factor: float = 2.0
flat_scan_threshold_factor: int = 3
gen_top_p: float = 0.9; gen_temp: float = 0.8
norm_correction_interval: int = 4
write_update_alpha: float = 0.3
dir_diversity_tau: float = 0.5
bypass_init_gate_bias: float = -0.5
degen_min_tokens: int = 5; degen_repeat_penalty: float = 1.4
degen_max_consec_punct: int = 2
probe_contrastive_tau: float = 0.1
contrast_tau: float = 0.5
# ── v3.12 prefix ──
prefix_init_scale: float = -0.2
# ── decode ──
degen_early_punct_penalty: float = 80.0
degen_early_newline_penalty: float = 80.0
early_content_steps: int = 5
universal_content_boost: float = 2.0
universal_content_boost_steps: int = 5
content_bias_scale: float = 12.0
content_bias_decay: float = 0.02
content_bias_floor: float = 0.4
generated_token_decay: float = 0.15
structural_rhythm_threshold: int = 2
structural_boost: float = 3.0
content_repeat_penalty: float = 5.0
first_step_content_multiplier: float = 3.5
first_step_penalty_multiplier: float = 3.0
domain_anchor_k: int = 8
domain_anchor_boost: float = 8.0
domain_anchor_start_step: int = 1
domain_anchor_coverage_threshold: float = 0.10
# ── v3.12 retrieval ──
ret_forward_maxsim_weight: float = 0.40
ret_backward_maxsim_weight: float = 0.15
ret_overlap_weight: float = 0.25
ret_sem_weight: float = 0.10
ret_dir_weight: float = 0.10
reranker_clip: float = 0.2
forward_maxsim_hard_threshold: float = 0.15
forward_maxsim_relative_ratio: float = 0.65
score_keep_ratio: float = 0.55
retrieval_weight_temperature: float = 0.15
consol_maxsim_min: float = 0.40
# ── v3.12 prefix injection ──
content_inject_scale: float = 0.65
prefix_inject_last_ratio: float = 0.25
prefix_inject_last_multiplier: float = 4.0
prefix_inject_other_multiplier: float = 0.8
# ── preserved ──
semantic_boost_scale: float = 0.5
semantic_boost_decay: float = 0.06
semantic_boost_floor: float = 0.2
semantic_align_temp: float = 0.3
vocab_size: int = 50257
wte_neighbor_k: int = 5
wte_neighbor_threshold: float = 0.5
loss_weights: Dict[str, float] = field(default_factory=lambda: {
'recon': 1.0, 'semantic_alignment': 3.0,
'encoder_throughput': 1.5, 'contrast': 0.02,
'holonomy': 0.005, 'write_policy': 0.1,
'semantic_probe': 0.3, 'dir_diversity': 0.1,
'reranker_ranking': 0.2, 'vocab_anchor': 0.2})
warmup_steps_probe: int = 5; warmup_steps_dd: int = 5
warmup_steps_rr: int = 5; warmup_steps_va: int = 5
warmup_steps_sa: int = 0
uw_clamp_lo: float = -4.0; uw_clamp_hi: float = 4.0
vocab_anchor_topk: int = 5; content_min_len: int = 3
refresh_memories_every: int = 1
def __post_init__(self):
assert self.d_F % self.n_heads_fiber == 0
assert self.n_geo_pts >= 2 and 0 < self.tau < 1
def _dev(ref: torch.Tensor):
return dict(device=ref.device, dtype=ref.dtype)
# ═══════════════════════════════════════════════════════════════════
# 第1部分 · 黎曼度量
# ═══════════════════════════════════════════════════════════════════
class RiemannianMetric(nn.Module):
def __init__(self, d):
super().__init__(); self.d = d
n_tri = d*(d+1)//2
self.net = nn.Sequential(
nn.Linear(d,4*d), nn.SiLU(),
nn.Linear(4*d,4*d), nn.SiLU(),
nn.Linear(4*d, n_tri))
for m in self.net.modules():
if isinstance(m, nn.Linear):
nn.init.xavier_normal_(m.weight)
if m.bias is not None: nn.init.zeros_(m.bias)
nn.init.normal_(self.net[-1].weight, std=0.02)
nn.init.zeros_(self.net[-1].bias)
r,c=[],[]
for i in range(d):
for j in range(i+1): r.append(i); c.append(j)
self.register_buffer('_r', torch.tensor(r))
self.register_buffer('_c', torch.tensor(c))
def forward(self, x):
B=x.shape[0]; d=self.d; v=self.net(x)
L=x.new_zeros(B,d,d); L[:,self._r,self._c]=v
di=torch.arange(d,device=x.device)
L[:,di,di]=F.softplus(L[:,di,di])+1e-3
return L@L.transpose(1,2)
def christoffel(self, x):
d=self.d; B=x.shape[0]
xv=x.detach().clone().requires_grad_(True)
g=self.forward(xv); g_inv=torch.linalg.inv(g.detach())
dg=x.new_zeros(B,d,d,d)
for i in range(d):
for j in range(i,d):
gr=torch.autograd.grad(g[:,i,j].sum(),xv,retain_graph=True)[0]
dg[:,i,j,:]=gr
if i!=j: dg[:,j,i,:]=gr
term=dg.permute(0,3,1,2)+dg.permute(0,1,3,2)-dg
return (0.5*torch.einsum('bkl,bijl->bkij',g_inv,term)).detach()
def midpoint_approx_distance(self, x, y):
diff=x-y; mid=(x+y)/2
with torch.no_grad(): g=self.forward(mid)
return torch.einsum('bi,bij,bj->b',diff,g,diff).clamp(min=0).sqrt()
# ═══════════════════════════════════════════════════════════════════
# 第2部分 · 测地线求解器
# ═══════════════════════════════════════════════════════════════════
class GeodesicResult(NamedTuple):
path: torch.Tensor; energy: float; converged: bool; iterations: int
class GeodesicSolver:
def __init__(self, metric, cfg):
self.metric=metric; self.cfg=cfg
def solve(self, xs, xe):
B,d=xs.shape; N=self.cfg.n_geo_pts; dev=xs.device
t=torch.linspace(0,1,N+2,device=dev)[1:-1]
ps={n:p.requires_grad for n,p in self.metric.named_parameters()}
for p in self.metric.parameters(): p.requires_grad_(False)
with torch.enable_grad():
interior=(xs.detach().unsqueeze(1)*(1-t[None,:,None])
+xe.detach().unsqueeze(1)*t[None,:,None]).detach().clone().requires_grad_(True)
opt=torch.optim.Adam([interior],lr=self.cfg.geo_lr)
prev=float('inf'); converged=False; iters=0
for it in range(self.cfg.geo_max_steps):
opt.zero_grad()
path=torch.cat([xs.detach().unsqueeze(1),interior,xe.detach().unsqueeze(1)],1)
dx=path[:,1:]-path[:,:-1]; mid=(path[:,1:]+path[:,:-1])/2
g=self.metric(mid.reshape(-1,d)).reshape(B,N+1,d,d)
energy=torch.einsum('bni,bnij,bnj->',dx,g,dx)
if energy.item()!=energy.item():
warnings.warn("GeodesicSolver: NaN energy")
t_full=torch.linspace(0,1,N+2,device=dev).view(1,-1,1)
lin=xs.unsqueeze(1)*(1-t_full)+xe.unsqueeze(1)*t_full
for n,p in self.metric.named_parameters(): p.requires_grad_(ps[n])
return GeodesicResult(lin,float('inf'),False,it)
energy.backward(); opt.step(); iters=it+1; cur=energy.item()
if abs(prev-cur)/(abs(prev)+1e-10)<self.cfg.geo_tol:
converged=True; break
prev=cur
for n,p in self.metric.named_parameters(): p.requires_grad_(ps[n])
final=torch.cat([xs.unsqueeze(1),interior.detach(),xe.unsqueeze(1)],1)
return GeodesicResult(final,cur if 'cur' in dir() else prev,converged,iters)
# ═══════════════════════════════════════════════════════════════════
# 第3部分 · 纤维联络 + RK4平行移动
# ═══════════════════════════════════════════════════════════════════
class FiberConnection(nn.Module):
def __init__(self, d_M, d_F, metric, grad_coupling=True):
super().__init__(); self.d_F=d_F; self.metric=metric; self.grad_coupling=grad_coupling
d_g=d_M*(d_M+1)//2
self.net=nn.Sequential(nn.Linear(2*d_M+d_g,4*d_F),nn.SiLU(),
nn.Linear(4*d_F,4*d_F),nn.SiLU(),nn.Linear(4*d_F,d_F*d_F))
nn.init.normal_(self.net[-1].weight,std=0.01); nn.init.normal_(self.net[-1].bias,std=0.01)
def forward(self, x, v):
g=self.metric(x); d=g.shape[-1]; idx=torch.triu_indices(d,d,device=x.device)
gf=g[:,idx[0],idx[1]]
if not self.grad_coupling: gf=gf.detach()
raw=self.net(torch.cat([x,v,gf],-1)).reshape(-1,self.d_F,self.d_F)
return (raw-raw.transpose(1,2))/2
class FiberTransporter(nn.Module):
def __init__(self, conn, cfg):
super().__init__(); self.conn=conn; self.cfg=cfg
def forward(self, fiber, path):
f=fiber; n0=fiber.norm(dim=-1,keepdim=True).clamp(min=1e-8)
nci=self.cfg.norm_correction_interval
for k in range(path.shape[1]-1):
p0,p1=path[:,k],path[:,k+1]; v=p1-p0; mid=(p0+p1)/2
k1=-(self.conn(p0,v)@f.unsqueeze(-1)).squeeze(-1)
k2=-(self.conn(mid,v)@(f+.5*k1).unsqueeze(-1)).squeeze(-1)
k3=-(self.conn(mid,v)@(f+.5*k2).unsqueeze(-1)).squeeze(-1)
k4=-(self.conn(p1,v)@(f+k3).unsqueeze(-1)).squeeze(-1)
f=f+(k1+2*k2+2*k3+k4)/6
if (k+1)%nci==0: f=f*(n0/f.norm(dim=-1,keepdim=True).clamp(min=1e-8))
return f
# ═══════════════════════════════════════════════════════════════════
# 第4部分 · 编码器 + 策略模块
# ═══════════════════════════════════════════════════════════════════
class CtxEncoder(nn.Module):
def __init__(self, c):
super().__init__()
self.f1=nn.Linear(c.d_LLM,4*c.d_M); self.f2=nn.Linear(4*c.d_M,4*c.d_M)
self.f3=nn.Linear(4*c.d_M,c.d_M); self.skip=nn.Linear(c.d_LLM,c.d_M)
self.n1=nn.LayerNorm(4*c.d_M); self.n2=nn.LayerNorm(4*c.d_M); self.no=nn.LayerNorm(c.d_M)
def forward(self, h):
x=F.silu(self.n1(self.f1(h))); x=F.silu(self.n2(self.f2(x)))
return self.no(self.f3(x)+self.skip(h))
class FibEncoder(nn.Module):
def __init__(self, c):
super().__init__()
self.enc=nn.Sequential(nn.Linear(c.d_LLM+c.d_M,4*c.d_F),nn.SiLU(),nn.LayerNorm(4*c.d_F),
nn.Linear(4*c.d_F,4*c.d_F),nn.SiLU(),nn.LayerNorm(4*c.d_F),
nn.Linear(4*c.d_F,c.d_F))
self.sg=nn.Sequential(nn.Linear(1,c.d_F),nn.SiLU(),nn.Linear(c.d_F,c.d_F),nn.Sigmoid())
def forward(self, h, x, surprise=None):
f=self.enc(torch.cat([h,x],-1))
if surprise is not None:
s=surprise.view(-1,1) if surprise.dim()>=1 else surprise.unsqueeze(0).unsqueeze(0)
if s.shape[0]!=f.shape[0]: s=s.expand(f.shape[0],-1)
f=f*self.sg(s)
return f
class DirectionPredictor(nn.Module):
def __init__(self, d_M, d_F):
super().__init__()
self.net=nn.Sequential(nn.Linear(d_M+d_F,4*d_M),nn.SiLU(),
nn.LayerNorm(4*d_M),nn.Linear(4*d_M,d_M))
def forward(self, x, f):
return F.normalize(self.net(torch.cat([x,f],-1)),dim=-1,eps=1e-8)
class EmptyStateNet(nn.Module):
def __init__(self, d_M, d_F):
super().__init__()
self.net=nn.Sequential(nn.Linear(d_M+d_F,2*d_F),nn.SiLU(),nn.LayerNorm(2*d_F),
nn.Linear(2*d_F,d_F))
def forward(self, xq, fq):
return self.net(torch.cat([xq,fq],-1))
class WriteGate(nn.Module):
def __init__(self, c):
super().__init__()
self.net=nn.Sequential(nn.Linear(c.d_LLM+1,c.d_LLM//4),nn.SiLU(),nn.Linear(c.d_LLM//4,1))
def forward(self, h, surprise):
s=surprise.view(-1,1) if surprise.dim()>=1 else surprise.unsqueeze(0).unsqueeze(0)
if s.shape[0]!=h.shape[0]: s=s[:h.shape[0]]
return torch.sigmoid(self.net(torch.cat([h,s],-1)).squeeze(-1))
class RetentionScorer(nn.Module):
def __init__(self, c):
super().__init__()
self.net=nn.Sequential(nn.Linear(c.d_M+c.d_F+3,64),nn.SiLU(),
nn.Linear(64,64),nn.SiLU(),nn.Linear(64,1),nn.Sigmoid())
def forward(self, base, fiber, surprise, dt, cnt):
return self.net(torch.cat([base,fiber,
surprise.unsqueeze(-1) if surprise.dim()==1 else surprise,
dt.unsqueeze(-1) if dt.dim()==1 else dt,
cnt.float().unsqueeze(-1) if cnt.dim()==1 else cnt.float()],-1)).squeeze(-1)
# ═══════════════════════════════════════════════════════════════════
# 第5部分 · 检索重排序
# ═══════════════════════════════════════════════════════════════════
class RetrievalReranker(nn.Module):
def __init__(self, d_M, d_F, clip=0.2):
super().__init__()
self.clip=clip
inp=2*d_M+2*d_F+1
self.net=nn.Sequential(nn.Linear(inp,128),nn.SiLU(),nn.LayerNorm(128),
nn.Linear(128,64),nn.SiLU(),nn.LayerNorm(64),nn.Linear(64,1))
nn.init.zeros_(self.net[-1].weight); nn.init.zeros_(self.net[-1].bias)
def forward(self, xq, fq, xc, fc, dir_sim):
B,C=xc.shape[:2]
xq_e=xq.unsqueeze(1).expand(-1,C,-1); fq_e=fq.unsqueeze(1).expand(-1,C,-1)
inp=torch.cat([xq_e,fq_e,xc,fc,dir_sim.unsqueeze(-1)],-1)
correction=self.net(inp).squeeze(-1)
correction=correction.clamp(-self.clip,self.clip)
return dir_sim+correction
# ═══════════════════════════════════════════════════════════════════
# 第6部分 · ContentBypass
# ═══════════════════════════════════════════════════════════════════
class ContentBypass(nn.Module):
def __init__(self, d_F, d_LLM, gate_bias=-0.5):
super().__init__()
self.proj=nn.Sequential(
nn.Linear(d_F,2*d_LLM),nn.SiLU(),nn.LayerNorm(2*d_LLM),
nn.Linear(2*d_LLM,d_LLM),nn.LayerNorm(d_LLM))
self.gate_net=nn.Sequential(
nn.Linear(d_F+d_LLM,128),nn.SiLU(),nn.Linear(128,1))
nn.init.constant_(self.gate_net[-1].bias,gate_bias)
nn.init.normal_(self.proj[3].weight,std=0.02)
nn.init.zeros_(self.proj[3].bias)
self._last_gate=None
def forward(self, fiber_summary, qformer_context):
projected=self.proj(fiber_summary)
gate_in=torch.cat([fiber_summary,qformer_context],-1)
g=torch.sigmoid(self.gate_net(gate_in))
self._last_gate=g.detach()
return projected*g
# ═══════════════════════════════════════════════════════════════════
# 第7部分 · PrefixSemanticProbe
# ═══════════════════════════════════════════════════════════════════
class PrefixSemanticProbe(nn.Module):
def __init__(self, d_LLM, L_mem, d_F):
super().__init__()
self.attn_pool=nn.Linear(d_LLM,1)
self.fiber_decode=nn.Sequential(
nn.Linear(d_LLM,2*d_F),nn.SiLU(),nn.LayerNorm(2*d_F),nn.Linear(2*d_F,d_F))
def forward(self, prefix):
w=F.softmax(self.attn_pool(prefix).squeeze(-1),dim=1)
pooled=(w.unsqueeze(-1)*prefix).sum(1)
return self.fiber_decode(pooled)
# ═══════════════════════════════════════════════════════════════════
# 第8部分 · PrefixAligner
# ═══════════════════════════════════════════════════════════════════
class PrefixAligner(nn.Module):
def __init__(self, d_LLM, init_scale=-0.2):
super().__init__()
self.ln=nn.LayerNorm(d_LLM)
self.scale_logit=nn.Parameter(torch.tensor(init_scale))
self.register_buffer('_target_std',torch.tensor(1.0))
self._calibrated=False
def calibrate(self, llm):
with torch.no_grad():
wte=llm.transformer.wte.weight; wpe=llm.transformer.wpe.weight
si=min(2000,wte.shape[0]); sp=min(32,wpe.shape[0])
combined=wte[:si].unsqueeze(1)+wpe[:sp].unsqueeze(0)
self._target_std.fill_(combined.std().item())
self._calibrated=True
def forward(self, prefix):
normed=self.ln(prefix)
scale=torch.sigmoid(self.scale_logit)*self._target_std
return normed*scale
# ═══════════════════════════════════════════════════════════════════
# 第9部分 · ContentTokenClassifier
# ═══════════════════════════════════════════════════════════════════
class ContentTokenClassifier:
STOPWORDS = frozenset({
'the','a','an','is','are','was','were','be','been','being',
'have','has','had','having','do','does','did','doing',
'will','would','could','should','may','might','can','shall',
'and','but','or','nor','for','yet','so',
'in','on','at','to','of','by','with','from','as','into','through',
'during','before','after','above','below','between','under','over',
'that','this','these','those','it','its',
'he','she','they','we','you','me','him','her','them','us',
'his','her','their','our','your','my','mine','yours',
'not','no','if','then','than','when','where','what','which','who',
'how','all','each','every','both','few','more','most','some','any',
'also','just','about','very','really','only','even','still','already',
'up','down','out','off','away','back','here','there','now',
'too','much','many','such','own','other','another',
'because','since','while','although','though','until','unless',
'however','therefore','moreover','furthermore','nevertheless',
'like','get','got','go','went','gone','come','came',
'make','made','take','took','give','gave','see','saw','know','knew',
'think','thought','say','said','tell','told','want','need',
'use','used','find','found','put','keep','kept','let',
'seem','become','became','leave','left','call','called',
'try','tried','ask','asked','work','worked','well','way',
'thing','things','something','anything','nothing','everything',
'one','two','first','new','old','good','bad','big','small',
'long','little','right','same','different','last','next',
'part','being','going','using','getting','making','looking',
'coming','taking','having','doing','saying','working','trying',
'include','includes','including','included'
})
def __init__(self, tokenizer, min_len=3):
self.content_ids: Set[int] = set()
self.function_ids: Set[int] = set()
self.punct_ids: Set[int] = set()
self.newline_ids: Set[int] = set()
vocab_size = getattr(tokenizer, 'vocab_size', 50257)
for i in range(min(vocab_size, 50300)):
try:
tok_text = tokenizer.decode([i])
stripped = tok_text.strip().lower()
cleaned = ''.join(c for c in stripped if c.isalpha())
if '\n' in tok_text:
self.newline_ids.add(i); self.function_ids.add(i)
elif stripped == '' or all(not c.isalnum() for c in stripped):
self.punct_ids.add(i); self.function_ids.add(i)
elif len(cleaned) >= min_len and cleaned not in self.STOPWORDS:
self.content_ids.add(i)
else:
self.function_ids.add(i)
except:
self.function_ids.add(i)
self._content_tensor = None
self.starter_ids: Set[int] = set()
starters_words = {'the','a','an','it','this','that','there','here','its','my',
'our','his','her','their','we','they','he','she','one'}
for i in range(min(vocab_size, 50300)):
try:
tok_text = tokenizer.decode([i]).strip().lower()
cleaned = ''.join(c for c in tok_text if c.isalpha())
if cleaned in starters_words:
self.starter_ids.add(i)
except:
pass
def content_mask(self, device):
if self._content_tensor is None or self._content_tensor.device != device:
V = max(max(self.content_ids, default=0), max(self.function_ids, default=0),
max(self.punct_ids, default=0), max(self.newline_ids, default=0)) + 1
m = torch.zeros(V, device=device)
for i in self.content_ids:
if i < V: m[i] = 1.0
self._content_tensor = m
return self._content_tensor
def get_content_ids_from_tokens(self, token_ids):
return [t for t in token_ids if t in self.content_ids]
def get_content_positions(self, token_ids, mask=None):
positions = []
for pos, tid in enumerate(token_ids):
if mask is not None and pos < len(mask) and not mask[pos]:
continue
if tid in self.content_ids:
positions.append(pos)
return positions
# ═══════════════════════════════════════════════════════════════════
# 第10部分 · MemoryVocabProjector
# ═══════════════════════════════════════════════════════════════════
class MemoryVocabProjector(nn.Module):
def __init__(self, d_F, d_LLM):
super().__init__()
self.proj = nn.Sequential(
nn.Linear(d_F, 4*d_LLM), nn.SiLU(), nn.LayerNorm(4*d_LLM),
nn.Linear(4*d_LLM, 2*d_LLM), nn.SiLU(), nn.LayerNorm(2*d_LLM),
nn.Linear(2*d_LLM, d_LLM))
nn.init.zeros_(self.proj[-1].weight); nn.init.zeros_(self.proj[-1].bias)
def forward(self, fiber_summary, wte_weight):
mem_emb = self.proj(fiber_summary)
mem_n = F.normalize(mem_emb, dim=-1, eps=1e-8)
wte_n = F.normalize(wte_weight, dim=-1, eps=1e-8)
return mem_n @ wte_n.T
# ═══════════════════════════════════════════════════════════════════
# 第11部分 · MemEntry + DirectionTree
# ═══════════════════════════════════════════════════════════════════
@dataclass
class MemEntry:
mid: int; base: torch.Tensor; fiber: torch.Tensor; dirn: torch.Tensor
surprise: float; ts: float; last: float; cnt: int = 0; version: int = 0
source_text: str = ""
content_token_ids: List[int] = field(default_factory=list)
semantic_emb: Optional[torch.Tensor] = None
expanded_content_ids: List[int] = field(default_factory=list)
class _Node:
__slots__=('leaf','ids','children','centers','depth')
def __init__(self,d=0):
self.depth=d; self.leaf=True; self.ids=[]; self.children=[]; self.centers=None
def count(self):
return len(self.ids) if self.leaf else sum(c.count() for c in self.children)
class DirectionTree:
def __init__(self, c):
self.c=c; self.root=_Node(); self.store:Dict[int,MemEntry]={}; self.nid=0
def insert(self, m):
self.store[m.mid]=m; self._ins(self.root,m)
def _ins(self, nd, m):
if nd.leaf:
nd.ids.append(m.mid)
if len(nd.ids)>self.c.tree_max_leaf: self._split(nd)
else:
best=self._best(nd,m.dirn); self._ins(nd.children[best],m); self._update_centers(nd)
def update(self, mid, new_base=None, new_fiber=None, new_dirn=None):
if mid not in self.store: return
m=self.store[mid]; dc=False
if new_base is not None: m.base=new_base.detach().clone()
if new_fiber is not None: m.fiber=new_fiber.detach().clone()
if new_dirn is not None: dc=True; m.dirn=new_dirn.detach().clone()
m.version+=1
if dc: self._rm(self.root,mid); self._ins(self.root,m); self._rebalance(self.root)
def _split(self, nd):
ids=nd.ids
if len(ids)<2: return
K=min(self.c.tree_K,len(ids))
if K<2: return
dirs=torch.stack([self.store[i].dirn for i in ids])
centered=dirs-dirs.mean(0)
try: _,_,Vh=torch.linalg.svd(centered,full_matrices=False)
except: return
n_comp=min(K,dirs.shape[1]); proj=centered@Vh[:n_comp].T
asgn=self._farthest_kmeans(proj,K)
children=[]
for k in range(K):
ch=_Node(nd.depth+1); ch.ids=[ids[i] for i in range(len(ids)) if asgn[i]==k]
if ch.ids: children.append(ch)
if len(children)<=1: return
nd.leaf=False; nd.children=children; nd.ids=[]; self._update_centers(nd)
for ch in nd.children:
if ch.leaf and len(ch.ids)>self.c.tree_max_leaf: self._split(ch)
@staticmethod
def _farthest_kmeans(data, K, max_iter=50):
N=data.shape[0]; K=min(K,N)
if K<=0: return torch.zeros(N,dtype=torch.long,device=data.device)
ctrs=[data[0].clone()]
for _ in range(K-1):
d2=torch.cdist(data,torch.stack(ctrs)).min(1)[0].pow(2)
ctrs.append(data[d2.argmax()].clone())
ctrs=torch.stack(ctrs); asgn=torch.zeros(N,dtype=torch.long,device=data.device)
for _ in range(max_iter):
dists=torch.cdist(data,ctrs); new=dists.argmin(1)
if (new==asgn).all(): break
asgn=new
for k in range(K):
mk=asgn==k
if mk.any(): ctrs[k]=data[mk].mean(0)
else:
far=dists.min(1)[0].argmax(); ctrs[k]=data[far].clone(); asgn[far]=k
return asgn
def _best(self, nd, d):
if nd.centers is None or len(nd.children)==0: return 0
return (nd.centers@d).argmax().item()
def retrieve(self, qdir, bw=3)->List[Tuple[int,float]]:
beams:List[Tuple[_Node,float]]=[(self.root,0.)]
results:Dict[int,float]={}
while beams:
nb=[]
for nd,sc in beams:
if nd.leaf:
for mid in nd.ids:
if mid in self.store:
s=(qdir@self.store[mid].dirn).item()+sc
if mid not in results or s>results[mid]: results[mid]=s
elif nd.centers is not None:
sims=nd.centers@qdir; tk=min(bw,len(nd.children)); _,idxs=sims.topk(tk)
for i in idxs: nb.append((nd.children[i.item()],sc+sims[i.item()].item()))
else:
for ch in nd.children: nb.append((ch,sc))
nb.sort(key=lambda x:-x[1]); beams=nb[:bw]
return sorted(results.items(),key=lambda x:-x[1])
def remove(self, mid):
if mid not in self.store: return
del self.store[mid]; self._rm(self.root,mid); self._rebalance(self.root)
def _rm(self, nd, mid):
if nd.leaf:
if mid in nd.ids: nd.ids.remove(mid); return True
return False
return any(self._rm(c,mid) for c in nd.children)
def _rebalance(self, nd):
if nd.leaf: return
for c in nd.children: self._rebalance(c)
nd.children=[c for c in nd.children if c.count()>0]
if not nd.children: nd.leaf=True; nd.ids=[]; nd.centers=None
elif len(nd.children)==1:
ch=nd.children[0]; nd.leaf=ch.leaf; nd.ids=ch.ids; nd.children=ch.children; nd.centers=ch.centers
else: self._update_centers(nd)
def _update_centers(self, nd):
cs=[]
for c in nd.children:
ids=self._collect(c); dirs=[self.store[i].dirn for i in ids if i in self.store]
if not dirs: continue
cs.append(F.normalize(torch.stack(dirs).mean(0),dim=0))
nd.centers=torch.stack(cs) if cs else None
def _collect(self, nd):
if nd.leaf: return list(nd.ids)
return [i for c in nd.children for i in self._collect(c)]
def _enforce_capacity(self, nd):
if nd.leaf:
if len(nd.ids)>self.c.tree_max_leaf: self._split(nd)
return
for ch in nd.children: self._enforce_capacity(ch)
def rebuild(self):
ms=list(self.store.values()); self.root=_Node()
for m in ms: self._ins(self.root,m)
self._enforce_capacity(self.root)
def max_depth(self, nd=None):
if nd is None: nd=self.root
if nd.leaf: return nd.depth
return max(self.max_depth(c) for c in nd.children) if nd.children else nd.depth
def verify_consistency(self)->List[str]:
errs=[]; ti=set(self._collect(self.root)); si=set(self.store.keys())
if ti!=si: errs.append(f"tree≠store: tree_only={ti-si}, store_only={si-ti}")
if self.root.count()!=len(self.store): errs.append(f"count: tree={self.root.count()}, store={len(self.store)}")
return errs
def leaf_size_violations(self)->List[Tuple[int,int]]:
v=[]; self._check_leaves(self.root,v); return v
def _check_leaves(self, nd, v):
if nd.leaf:
if len(nd.ids)>self.c.tree_max_leaf: v.append((nd.depth,len(nd.ids)))
else:
for c in nd.children: self._check_leaves(c,v)
def check_direction_degeneracy(self, threshold: float = 0.95) -> List[Tuple[List[int], float]]:
degenerate = []
self._check_degeneracy_recursive(self.root, threshold, degenerate)
return degenerate
def _check_degeneracy_recursive(self, nd, threshold, results):
if nd.leaf:
if len(nd.ids) >= 2:
dirs = [self.store[mid].dirn for mid in nd.ids if mid in self.store]
if len(dirs) >= 2:
dt = torch.stack(dirs)
dn = F.normalize(dt, dim=-1)
sim = dn @ dn.T
mask_off = ~torch.eye(len(dirs), dtype=torch.bool, device=sim.device)
avg_sim = sim[mask_off].mean().item() if mask_off.any() else 0.0
if avg_sim > threshold:
results.append((list(nd.ids), avg_sim))
else:
for ch in nd.children:
self._check_degeneracy_recursive(ch, threshold, results)
# ═══════════════════════════════════════════════════════════════════
# 第12部分 · 纤维注意力
# ═══════════════════════════════════════════════════════════════════
class FiberAttn(nn.Module):
def __init__(self, c):
super().__init__()
self.nh=c.n_heads_fiber; self.hd=c.d_F//c.n_heads_fiber
self.Wq=nn.Linear(c.d_F,c.d_F,bias=False); self.Wk=nn.Linear(c.d_F,c.d_F,bias=False)
self.Wv=nn.Linear(c.d_F,c.d_F,bias=False); self.Wo=nn.Linear(c.d_F,c.d_F,bias=False)
self.n1=nn.LayerNorm(c.d_F)
self.ff=nn.Sequential(nn.Linear(c.d_F,2*c.d_F),nn.GELU(),nn.Linear(2*c.d_F,c.d_F))
self.n2=nn.LayerNorm(c.d_F)
def forward(self, qf, mf, mem_mask=None, dir_bias=None):
B,C,d=mf.shape; nh=self.nh; hd=self.hd; S=1+C
seq=torch.cat([qf.unsqueeze(1),mf],1)
Q=self.Wq(seq).reshape(B,S,nh,hd).permute(0,2,1,3)
K=self.Wk(seq).reshape(B,S,nh,hd).permute(0,2,1,3)
V=self.Wv(seq).reshape(B,S,nh,hd).permute(0,2,1,3)
a=(Q@K.transpose(-2,-1))/math.sqrt(hd)
if dir_bias is not None:
db=dir_bias.unsqueeze(1).unsqueeze(2)
pad=torch.zeros(B,1,1,1,**_dev(a))
a=a+torch.cat([pad,db],-1)
if mem_mask is not None:
qm=torch.ones(B,1,**_dev(mem_mask))
full=torch.cat([qm,mem_mask],1)
a=a.masked_fill(full.unsqueeze(1).unsqueeze(2)==0,-1e9)
a=F.softmax(a,-1); out=(a@V).permute(0,2,1,3).reshape(B,S,d)
out=self.n1(seq+self.Wo(out)); out=self.n2(out+self.ff(out))
return out[:,1:]
# ═══════════════════════════════════════════════════════════════════
# 第13部分 · QFormer + 嵌入桥
# ═══════════════════════════════════════════════════════════════════
class QFormerLayer(nn.Module):
def __init__(self, c):
super().__init__(); d=c.d_LLM; nh=c.bridge_heads
self.sa=nn.MultiheadAttention(d,nh,batch_first=True)
self.ca=nn.MultiheadAttention(d,nh,batch_first=True)
self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d))
self.n1=nn.LayerNorm(d); self.n2=nn.LayerNorm(d); self.n3=nn.LayerNorm(d)
def forward(self, q, k, v, kv_mask=None):
h=self.n1(q); q=q+self.sa(h,h,h)[0]; h=self.n2(q)
kpm=None
if kv_mask is not None:
kpm=(kv_mask==0); all_m=kpm.all(dim=-1)
if all_m.any(): kpm=kpm.clone(); kpm[all_m]=False
q=q+self.ca(h,k,v,key_padding_mask=kpm)[0]
return q+self.ff(self.n3(q))
class QFormerProj(nn.Module):
def __init__(self, c):
super().__init__()
self.q=nn.Parameter(torch.randn(c.L_mem,c.d_LLM)*0.02)
self.fkv=nn.Linear(c.d_F,c.d_LLM*2)
self.layers=nn.ModuleList([QFormerLayer(c) for _ in range(c.bridge_layers)])
self.norm=nn.LayerNorm(c.d_LLM)
def forward(self, fibers, mem_mask=None):
B=fibers.shape[0]; kv=self.fkv(fibers); k,v=kv.chunk(2,-1)
q=self.q.unsqueeze(0).expand(B,-1,-1)
for l in self.layers: q=l(q,k,v,kv_mask=mem_mask)
return self.norm(q)
class AdaptiveLayerPool(nn.Module):
def __init__(self, n, d):
super().__init__(); self.w=nn.Parameter(torch.linspace(-2,2,n))
def forward(self, hs):
w=F.softmax(self.w,0); return sum(w[i]*h for i,h in enumerate(hs))
def weight_dist(self):
return F.softmax(self.w.detach(),0)
class StateExtractor(nn.Module):
def __init__(self, c):
super().__init__()
pos_dim=5
self.sc=nn.Sequential(nn.Linear(c.d_LLM+pos_dim,c.d_LLM//4),nn.Tanh(),nn.Linear(c.d_LLM//4,1))
self.tb=nn.Linear(c.d_LLM,c.d_M); self.tf=nn.Linear(c.d_LLM,c.d_F)
def _pos_feat(self, T, ref):
pos=torch.linspace(0,1,T,**_dev(ref))
return torch.stack([pos,torch.sin(pos*math.pi),torch.cos(pos*math.pi),
torch.sin(2*pos*math.pi),torch.cos(2*pos*math.pi)],-1)
def forward(self, h, mask=None):
B,T,_=h.shape; pf=self._pos_feat(T,h).unsqueeze(0).expand(B,-1,-1)
s=self.sc(torch.cat([h,pf],-1)).squeeze(-1)
if mask is not None:
if mask.shape[1]==T: s=s.masked_fill(mask==0,-1e9)
w=F.softmax(s,-1); p=(w.unsqueeze(-1)*h).sum(1)
return self.tb(p), self.tf(p)
class EmbBridge(nn.Module):
def __init__(self, c):
super().__init__()
self.proj=QFormerProj(c); self.ext=StateExtractor(c)
self.pe=nn.Parameter(torch.randn(c.L_mem,c.d_LLM)*0.02)
self.bypass=ContentBypass(c.d_F,c.d_LLM,gate_bias=c.bypass_init_gate_bias)
self.aligner=PrefixAligner(c.d_LLM,c.prefix_init_scale)
self.content_inject_scale=c.content_inject_scale
self.prefix_inject_last_ratio=c.prefix_inject_last_ratio
self.prefix_inject_last_multiplier=c.prefix_inject_last_multiplier
self.prefix_inject_other_multiplier=c.prefix_inject_other_multiplier
self.inject_mode='both'
self._last_inject_diag={}
self._last_fiber_summary=None
def inject(self, fibers, mem_mask=None, fiber_summary=None, content_wte_mean=None):
B=fibers.shape[0]
if self.inject_mode in ('both','qformer_only'):
qf_out=self.proj(fibers,mem_mask)+self.pe.unsqueeze(0)
else:
qf_out=self.pe.unsqueeze(0).expand(B,-1,-1)
bp_out=None; gate_val=None
if fiber_summary is not None and self.inject_mode in ('both','bypass_only'):
qf_context=qf_out.mean(1)
bp_out=self.bypass(fiber_summary,qf_context)
gate_val=self.bypass._last_gate
qf_out=qf_out+bp_out.unsqueeze(1)
qf_out=self.aligner(qf_out)
if content_wte_mean is not None:
cwm=content_wte_mean
if cwm.dim()==2: cwm=cwm.unsqueeze(1)
L=qf_out.shape[1]
n_last=max(1,int(L*self.prefix_inject_last_ratio))
pos_scale=torch.ones(L,device=qf_out.device)
pos_scale[:L-n_last]=self.prefix_inject_other_multiplier
pos_scale[L-n_last:]=self.prefix_inject_last_multiplier
pos_scale=pos_scale.view(1,-1,1)
qf_out=qf_out+cwm*self.content_inject_scale*pos_scale
self._last_fiber_summary=fiber_summary.detach() if fiber_summary is not None else None
self._last_inject_diag={
'bypass_gate':gate_val.mean().item() if gate_val is not None else None,
'qf_norm':qf_out.norm().item(),
'bypass_norm':bp_out.norm().item() if bp_out is not None else 0.0,
'aligner_scale':torch.sigmoid(self.aligner.scale_logit).item()*self.aligner._target_std.item(),
'cwm_applied':content_wte_mean is not None}
return qf_out
# ═══════════════════════════════════════════════════════════════════
# 第14部分 · Loss 相关工具
# ═══════════════════════════════════════════════════════════════════
class LossWarmup:
def __init__(self, schedules:Dict[str,int]):
self.schedules=schedules; self.step_count=0
def weight(self, name:str)->float:
ws=self.schedules.get(name,0)
if ws<=0: return 1.0
return min(1.0, self.step_count/max(ws,1))
def advance(self): self.step_count+=1
class GradientMonitor:
def __init__(self): self._groups:Dict[str,nn.Module]={}
def register(self, name:str, mod:nn.Module): self._groups[name]=mod
def register_param(self, name:str, param:nn.Parameter):
class _W(nn.Module):
def __init__(self, p): super().__init__(); self._p=p
def parameters(self, recurse=True): yield self._p
self._groups[name]=_W(param)
def snapshot(self)->Dict[str,float]:
norms={}
for name,mod in self._groups.items():
total=0.0; cnt=0
for p in mod.parameters():
if p.grad is not None: total+=p.grad.norm().item()**2; cnt+=1
norms[name]=math.sqrt(total) if cnt>0 else 0.0
return norms
# ═══════════════════════════════════════════════════════════════════
# 第15部分 · DegenerationGuard
# ═══════════════════════════════════════════════════════════════════
class DegenerationGuard:
def __init__(self, tok, cfg, content_classifier=None):
self.tok=tok; self.cfg=cfg; self.cc=content_classifier; self._built=False
def _build(self):
if self._built: return
if self.cc is not None:
self._punct_ids=self.cc.punct_ids; self._newline_ids=self.cc.newline_ids
else:
self._punct_ids=set(); self._newline_ids=set()
vocab_sz=getattr(self.tok,'vocab_size',50257)
for i in range(min(vocab_sz,50300)):
try:
t=self.tok.decode([i]); stripped=t.strip()
if stripped=='' or all(not c.isalnum() for c in stripped):
self._punct_ids.add(i)
if '\n' in t: self._newline_ids.add(i)
except: pass
self._built=True
def process(self, logits, generated_ids, step, first_step_penalty_mult=1.0):
self._build()
punct_pen = self.cfg.degen_early_punct_penalty
newline_pen = self.cfg.degen_early_newline_penalty
if step == 0:
punct_pen *= first_step_penalty_mult
newline_pen *= first_step_penalty_mult
if step<self.cfg.early_content_steps:
for pid in self._punct_ids:
if pid<logits.shape[-1]: logits[0,pid]-=punct_pen
for nid in self._newline_ids:
if nid<logits.shape[-1]: logits[0,nid]-=newline_pen
if step<self.cfg.degen_min_tokens and self.tok.eos_token_id is not None:
logits[0,self.tok.eos_token_id]=-float('inf')
seen=set(generated_ids[-30:]) if generated_ids else set()
for tid in seen:
if tid<logits.shape[-1]:
if logits[0,tid]>0: logits[0,tid]/=self.cfg.degen_repeat_penalty
else: logits[0,tid]*=self.cfg.degen_repeat_penalty
mc=self.cfg.degen_max_consec_punct
if len(generated_ids)>=mc:
recent=generated_ids[-mc:]
if all(t in self._punct_ids for t in recent):
for pid in self._punct_ids:
if pid<logits.shape[-1]: logits[0,pid]-=10.0
if len(generated_ids)>=2:
recent=generated_ids[-2:]
if all(t in self._newline_ids for t in recent):
for nid in self._newline_ids:
if nid<logits.shape[-1]: logits[0,nid]-=10.0
return logits
# ═══════════════════════════════════════════════════════════════════
# 第16部分 · RetrievalDiag (v3.12: + per_memory_forward_maxsim,
# overlap_pass/fwd_only_pass 计数)
# ═══════════════════════════════════════════════════════════════════
@dataclass
class RetrievalDiag:
was_flat_scan: bool = False
recall_count: int = 0
reranker_delta_mean: float = 0.0
fiber_summary_norm: float = 0.0
top_reranker_score: float = 0.0
top_dir_sim: float = 0.0
top_sem_sim: float = 0.0
top_forward_maxsim: float = 0.0
top_backward_maxsim: float = 0.0
top_overlap: float = 0.0
n_candidates_initial: int = 0
n_after_hard_filter: int = 0
n_after_score_filter: int = 0
n_overlap_pass: int = 0
n_fwd_only_pass: int = 0
batch_mem_weights: List[List[Tuple[int, float]]] = field(default_factory=list)
per_memory_forward_maxsim: Dict[int, float] = field(default_factory=dict)
# ═══════════════════════════════════════════════════════════════════
# 第17部分 · AMM (v3.12: expanded overlap gating, forward_maxsim 传播)
# ═══════════════════════════════════════════════════════════════════
class AMM(nn.Module):
def __init__(self, c):
super().__init__(); self.c=c
self.metric=RiemannianMetric(c.d_M)
self.geo=GeodesicSolver(self.metric,c)
self.conn=FiberConnection(c.d_M,c.d_F,self.metric,grad_coupling=True)
self.trans=FiberTransporter(self.conn,c)
self.ctx=CtxEncoder(c); self.fib=FibEncoder(c)
self.dir_pred=DirectionPredictor(c.d_M,c.d_F)
self.write_gate=WriteGate(c); self.retention=RetentionScorer(c)
self.attn=FiberAttn(c); self.empty_state=EmptyStateNet(c.d_M,c.d_F)
self.contrast_proj_f=nn.Linear(c.d_F,c.d_M,bias=False)
self.contrast_proj_x=nn.Linear(c.d_M,c.d_M,bias=False)
nn.init.eye_(self.contrast_proj_x.weight)
self.reranker=RetrievalReranker(c.d_M,c.d_F,clip=c.reranker_clip)
self.tree=DirectionTree(c); self.time=0.
self.wte_normed: Optional[torch.Tensor] = None
def surprise_proxy(self, logits, tgt):
nll=-F.log_softmax(logits,-1).gather(2,tgt.unsqueeze(-1)).squeeze(-1)
T=nll.shape[1]
if T==0: return logits.new_zeros(logits.shape[0])
w=torch.linspace(0.5,1.5,T,**_dev(nll)); w=w/w.sum()*T
return (nll*w.unsqueeze(0)).mean(-1)
def _compute_dirn(self, base, fiber):
with torch.no_grad():
return self.dir_pred(base.unsqueeze(0),fiber.unsqueeze(0)).squeeze(0)
# ── MaxSim 工具 ──
@staticmethod
def _compute_forward_maxsim(query_ids, mem_ids, wte_normed):
if not query_ids or not mem_ids:
return 0.0
V = wte_normed.shape[0]
q_ids = [i for i in query_ids if i < V]
m_ids = [i for i in mem_ids if i < V]
if not q_ids or not m_ids:
return 0.0
q_vecs = wte_normed[q_ids]
m_vecs = wte_normed[m_ids]
sim = q_vecs @ m_vecs.T
return sim.max(dim=1).values.mean().item()
@staticmethod
def _compute_backward_maxsim(query_ids, mem_ids, wte_normed):
if not query_ids or not mem_ids:
return 0.0
V = wte_normed.shape[0]
q_ids = [i for i in query_ids if i < V]
m_ids = [i for i in mem_ids if i < V]
if not q_ids or not m_ids:
return 0.0
q_vecs = wte_normed[q_ids]
m_vecs = wte_normed[m_ids]
sim = q_vecs @ m_vecs.T
return sim.max(dim=0).values.mean().item()
@staticmethod
def _compute_maxsim_bidi(ids_a, ids_b, wte_normed):
fwd = AMM._compute_forward_maxsim(ids_a, ids_b, wte_normed)
bwd = AMM._compute_backward_maxsim(ids_a, ids_b, wte_normed)
return 0.5 * fwd + 0.5 * bwd
@staticmethod
def _compute_token_overlap(query_ids, mem_ids):
if not query_ids:
return 0.0
q_set = set(query_ids)
m_set = set(mem_ids)
overlap = len(q_set & m_set)
return overlap / len(q_set)
@staticmethod
def _compute_expanded_overlap_count(query_expanded_ids, mem_content_ids):
"""v3.12: 扩展重叠计数.
query 侧用扩展 IDs (提高同域召回),
memory 侧用精确 IDs (避免双重扩展跨域桥接).
返回重叠 token 数 (不是比率).
"""
if not query_expanded_ids or not mem_content_ids: