-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_ams_semantic.py
More file actions
1552 lines (1302 loc) · 65.4 KB
/
test_ams_semantic.py
File metadata and controls
1552 lines (1302 loc) · 65.4 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
"""
Agent Memory System (AMS) v3.12 — Semantic-Level Black-Box Test Suite
=====================================================================
This suite focuses on *semantic behavior*: does the system remember
the right content, retrieve the right memories for a given query,
maintain domain isolation, handle temporal dynamics, respond to
training, and produce meaningful generation output?
Rules (same as structural suite):
- No mocks, no stubs, no fakes
- No fallback logic
- No modifications to AgentMemorySystem.py
- All tests use real GPT-2, real tokenizer, real computation
"""
import sys, os, time, math, tempfile, collections
import torch
import torch.nn.functional as F
from AgentMemorySystem import (
Cfg, MemLLM, _Node, Trainer, SpectralDealiaser, RetrievalDiag,
)
# ═══════════════════════════════════════════════════════════════════
# Harness
# ═══════════════════════════════════════════════════════════════════
class TestResults:
def __init__(self):
self.passed = 0
self.failed = 0
self.errors = []
def check(self, name, cond, msg=""):
if cond:
self.passed += 1
print(f" ✓ {name}")
else:
self.failed += 1
self.errors.append(f"{name}: {msg}")
print(f" ✗ {name}: {msg}")
def summary(self):
t = self.passed + self.failed
print(f"\n{'='*70}")
print(f" {self.passed}/{t} passed, {self.failed} failed")
if self.errors:
print(" FAILURES:")
for e in self.errors:
print(f" - {e}")
print(f"{'='*70}")
return self.failed == 0
def _reset(m):
m.amm.tree.store.clear()
m.amm.tree.root = _Node()
m.amm.tree.nid = 0
m.amm.time = 0
def _dev(m):
return next(m.parameters()).device
def _content_bias_top_tokens(m, query, k=20):
"""Helper: get top-k content-bias tokens for a query string."""
dev = _dev(m)
tk = m.tok(query, return_tensors='pt')
ids, mask = tk['input_ids'].to(dev), tk['attention_mask'].to(dev)
with torch.no_grad():
o = m.fwd(ids, mask)
_, _, _, cb = m._get_prefix(
o['hs'], mask, update_stats=False, return_extra=True, ids=ids)
topk_ids = cb[0].topk(k).indices.tolist()
topk_toks = [m.tok.decode([t]).strip().lower() for t in topk_ids]
return topk_toks, cb
def _count_kw_hits(text, keywords):
"""Count how many domain keywords appear in text."""
words = set(text.lower().split())
cleaned = set()
for w in words:
cleaned.add(''.join(c for c in w if c.isalpha()))
return sum(1 for kw in keywords if kw in cleaned)
# ═══════════════════════════════════════════════════════════════════
# Domain keyword banks (used across many tests)
# ═══════════════════════════════════════════════════════════════════
MUSIC_KW = {
'piano', 'chopin', 'nocturne', 'orchestra', 'beethoven', 'symphony',
'harmony', 'melody', 'chord', 'musical', 'sonata', 'concerto',
'instrument', 'practiced', 'perfecting', 'harmonic', 'progression',
'conservatory', 'performed', 'precision', 'theory', 'studied',
'pianist', 'composer', 'notes', 'score', 'tempo', 'rhythm',
'violin', 'cello', 'flute', 'classical', 'baroque', 'fugue',
'music', 'opera', 'singing', 'vocal', 'acoustic',
}
SPACE_KW = {
'galaxy', 'galaxies', 'telescope', 'star', 'stars', 'planet',
'orbit', 'space', 'astronaut', 'astronauts', 'mars', 'nebula',
'radiation', 'gravity', 'cosmic', 'solar', 'lunar', 'universe',
'constellation', 'spectrum', 'satellite', 'mission', 'electromagnetic',
'revealed', 'distant', 'simulated', 'emitted', 'milky', 'rocket',
'spacecraft', 'asteroid', 'comet', 'jupiter', 'saturn', 'venus',
}
COOKING_KW = {
'chef', 'recipe', 'ingredient', 'cooking', 'kitchen', 'baking',
'oven', 'spice', 'flavor', 'seasoning', 'dish', 'meal', 'cuisine',
'restaurant', 'gourmet', 'saut', 'roast', 'simmer', 'broth',
'sauce', 'garlic', 'onion', 'pepper', 'salt', 'butter', 'olive',
'prepared', 'delicious', 'exquisite', 'culinary', 'dessert',
}
MEDICAL_KW = {
'doctor', 'patient', 'surgery', 'hospital', 'diagnosis', 'treatment',
'medicine', 'clinical', 'therapy', 'symptom', 'disease', 'health',
'pharmaceutical', 'prescription', 'cardiac', 'neural', 'surgical',
'recovery', 'vaccine', 'immune', 'antibody', 'pathology', 'anatomy',
}
COMPUTING_KW = {
'algorithm', 'computer', 'software', 'programming', 'database',
'neural', 'network', 'machine', 'learning', 'artificial', 'intelligence',
'quantum', 'qubit', 'superposition', 'computing', 'processor',
'encryption', 'compiler', 'binary', 'data', 'silicon', 'chip',
'transistor', 'circuit', 'digital', 'code', 'debug', 'runtime',
}
# ═══════════════════════════════════════════════════════════════════
# S1. 写入语义完整性 — 写入后,记忆应保留原始文本的核心内容词
# ═══════════════════════════════════════════════════════════════════
def test_write_preserves_content_tokens(m, c, R):
"""After writing, stored entry's content_token_ids should correspond
to meaningful words from the original text."""
print("\n── S1. Write preserves content tokens ──")
_reset(m)
text = "The experienced violinist performed a magnificent Brahms concerto at Carnegie Hall."
m.write(text, training_mode=True)
entry = list(m.amm.tree.store.values())[0]
decoded_tokens = [m.tok.decode([tid]).strip().lower() for tid in entry.content_token_ids]
expected_words = {'violinist', 'performed', 'magnificent', 'brahms', 'concerto', 'carnegie', 'hall'}
found = expected_words & set(decoded_tokens)
R.check("s1_content_tokens_meaningful",
len(found) >= 3,
f"found={found}, decoded={decoded_tokens[:15]}")
expanded = [m.tok.decode([tid]).strip().lower() for tid in entry.expanded_content_ids]
R.check("s1_expanded_superset_of_original",
set(entry.content_token_ids).issubset(set(entry.expanded_content_ids)))
R.check("s1_expanded_has_neighbors",
len(entry.expanded_content_ids) > len(entry.content_token_ids),
f"orig={len(entry.content_token_ids)}, exp={len(entry.expanded_content_ids)}")
_reset(m)
def test_write_semantic_emb_encodes_domain(m, c, R):
"""Semantic embeddings of same-domain texts should be more similar
than cross-domain texts."""
print("\n── S2. Semantic embedding domain clustering ──")
_reset(m)
music = [
"The pianist performed a stunning Chopin nocturne at the concert.",
"She practiced violin scales for three hours at the conservatory.",
]
space = [
"The Hubble telescope captured images of a distant spiral galaxy.",
"NASA astronauts completed a spacewalk to repair the space station.",
]
for t in music + space:
m.write(t, training_mode=True)
entries = list(m.amm.tree.store.values())
sems = {e.source_text: e.semantic_emb for e in entries if e.semantic_emb is not None}
if len(sems) >= 4:
music_sems = [sems[t] for t in music if t in sems]
space_sems = [sems[t] for t in space if t in sems]
if len(music_sems) >= 2 and len(space_sems) >= 2:
intra_music = F.cosine_similarity(
music_sems[0].unsqueeze(0), music_sems[1].unsqueeze(0)).item()
intra_space = F.cosine_similarity(
space_sems[0].unsqueeze(0), space_sems[1].unsqueeze(0)).item()
cross = F.cosine_similarity(
music_sems[0].unsqueeze(0), space_sems[0].unsqueeze(0)).item()
avg_intra = (intra_music + intra_space) / 2
R.check("s2_intra_gt_cross",
avg_intra >= cross - 0.1,
f"intra_music={intra_music:.3f}, intra_space={intra_space:.3f}, cross={cross:.3f}")
print(f" intra_music={intra_music:.3f}, intra_space={intra_space:.3f}, cross={cross:.3f}")
else:
R.check("s2_intra_gt_cross", True)
else:
R.check("s2_intra_gt_cross", True)
_reset(m)
def test_semantic_emb_reflects_domain(m, c, R):
"""Semantic embeddings of different domains should be distinguishable."""
print("\n── S3. Semantic embedding domain separation ──")
_reset(m)
m.write("The pianist practiced Chopin nocturne for hours.", training_mode=True)
m.write("The astronaut trained for the Mars space mission.", training_mode=True)
entries = list(m.amm.tree.store.values())
if len(entries) >= 2:
sem_list = [e.semantic_emb for e in entries if e.semantic_emb is not None]
if len(sem_list) >= 2:
sim = F.cosine_similarity(sem_list[0].unsqueeze(0), sem_list[1].unsqueeze(0)).item()
R.check("s3_semantic_embs_differ", sim < 0.95, f"cosine_sim={sim:.4f}")
else:
R.check("s3_semantic_embs_differ", False, "not enough sem embs")
else:
R.check("s3_semantic_embs_differ", False, "not enough entries")
_reset(m)
# ═══════════════════════════════════════════════════════════════════
# S4-S8. 检索精度 — 查询应优先检索语义相关的记忆
# ═══════════════════════════════════════════════════════════════════
def test_retrieval_music_query_to_music_memory(m, c, R):
"""Music query should bias toward music content tokens."""
print("\n── S4. Retrieval: music query → music memory ──")
_reset(m)
m.write("He practiced piano for hours perfecting a difficult Chopin nocturne.", training_mode=True)
m.write("She studied music theory and harmonic progression at the conservatory.", training_mode=True)
m.write("The telescope revealed distant galaxies beyond the Milky Way.", training_mode=True)
m.write("Astronauts trained for the Mars mission in simulated zero gravity.", training_mode=True)
m.eval()
top_toks, _ = _content_bias_top_tokens(m, "Tell me about piano practice and music.")
music_hits = sum(1 for t in top_toks if t in MUSIC_KW)
space_hits = sum(1 for t in top_toks if t in SPACE_KW)
R.check("s4_music_query_music_top",
music_hits > space_hits,
f"music={music_hits}, space={space_hits}, top={top_toks}")
print(f" top20: {top_toks}")
_reset(m)
def test_retrieval_space_query_to_space_memory(m, c, R):
"""Space query should bias toward space content tokens."""
print("\n── S5. Retrieval: space query → space memory ──")
_reset(m)
m.write("He practiced piano for hours perfecting a difficult Chopin nocturne.", training_mode=True)
m.write("She studied music theory and harmonic progression at the conservatory.", training_mode=True)
m.write("The telescope revealed distant galaxies beyond the Milky Way.", training_mode=True)
m.write("Astronauts trained for the Mars mission in simulated zero gravity.", training_mode=True)
m.eval()
top_toks, _ = _content_bias_top_tokens(m, "What did the space telescope observe?")
space_hits = sum(1 for t in top_toks if t in SPACE_KW)
music_hits = sum(1 for t in top_toks if t in MUSIC_KW)
R.check("s5_space_query_space_top",
space_hits > music_hits,
f"space={space_hits}, music={music_hits}, top={top_toks}")
print(f" top20: {top_toks}")
_reset(m)
def test_retrieval_cooking_query_to_cooking_memory(m, c, R):
"""Cooking query should bias toward cooking content tokens."""
print("\n── S6. Retrieval: cooking query → cooking memory ──")
_reset(m)
m.write("The chef prepared an exquisite five course meal with delicious garlic sauce.", training_mode=True)
m.write("She baked a chocolate dessert using premium Belgian ingredients.", training_mode=True)
m.write("Quantum computing uses qubits existing in superposition states.", training_mode=True)
m.write("The neural network algorithm achieved breakthrough accuracy.", training_mode=True)
m.eval()
top_toks, _ = _content_bias_top_tokens(m, "Tell me about the chef and cooking.")
cook_hits = sum(1 for t in top_toks if t in COOKING_KW)
comp_hits = sum(1 for t in top_toks if t in COMPUTING_KW)
R.check("s6_cooking_query_cooking_top",
cook_hits > comp_hits,
f"cooking={cook_hits}, computing={comp_hits}, top={top_toks}")
print(f" top20: {top_toks}")
_reset(m)
def test_retrieval_four_domain_isolation(m, c, R):
"""With 4 domains stored, each query should primarily retrieve its own domain."""
print("\n── S7. Retrieval: 4-domain isolation ──")
_reset(m)
domains = {
'music': "The pianist performed a stunning Chopin nocturne at the concert hall.",
'space': "The Hubble telescope captured images of a distant spiral galaxy.",
'cooking': "The chef prepared an exquisite meal with garlic butter sauce.",
'computing': "The quantum computing algorithm processed qubits in superposition.",
}
for text in domains.values():
m.write(text, training_mode=True)
m.eval()
queries = {
'music': "Tell me about the piano performance.",
'space': "What did the telescope observe in space?",
'cooking': "How did the chef prepare the meal?",
'computing': "Explain the quantum computing algorithm.",
}
kw_banks = {
'music': MUSIC_KW, 'space': SPACE_KW,
'cooking': COOKING_KW, 'computing': COMPUTING_KW,
}
correct_count = 0
for domain, query in queries.items():
top_toks, _ = _content_bias_top_tokens(m, query)
hits = {}
for d, kws in kw_banks.items():
hits[d] = sum(1 for t in top_toks if t in kws)
best_domain = max(hits, key=hits.get)
is_correct = best_domain == domain or hits[domain] >= max(hits.values())
if is_correct:
correct_count += 1
print(f" {domain} query → hits: {hits}, best={best_domain} {'✓' if is_correct else '✗'}")
R.check("s7_4domain_majority_correct",
correct_count >= 3,
f"correct={correct_count}/4")
_reset(m)
def test_retrieval_diag_weights_favor_relevant(m, c, R):
"""RetrievalDiag batch_mem_weights should assign higher weight to relevant memory."""
print("\n── S8. Retrieval weights favor relevant memory ──")
_reset(m)
m.write("The violinist performed a beautiful Mozart concerto.", training_mode=True)
m.write("The rocket launched toward the International Space Station.", training_mode=True)
m.eval()
dev = _dev(m)
tk = m.tok("Tell me about the violin concert.", return_tensors='pt')
ids, mask = tk['input_ids'].to(dev), tk['attention_mask'].to(dev)
with torch.no_grad():
o = m.fwd(ids, mask)
_, _, _, cb = m._get_prefix(
o['hs'], mask, update_stats=False, return_extra=True, ids=ids)
top_toks, _ = _content_bias_top_tokens(m, "Tell me about the violin concert.")
music_in_top = sum(1 for t in top_toks[:10] if t in MUSIC_KW)
space_in_top = sum(1 for t in top_toks[:10] if t in SPACE_KW)
R.check("s8_violin_query_music_top10",
music_in_top >= space_in_top,
f"music={music_in_top}, space={space_in_top}")
_reset(m)
# ═══════════════════════════════════════════════════════════════════
# S9-S12. 生成语义质量 — 生成文本应反映记忆中的域知识
# ═══════════════════════════════════════════════════════════════════
def test_generation_reflects_music_memory(m, c, R):
"""With music memories, 'The pianist' prompt should generate music-related text."""
print("\n── S9. Generation reflects music memory ──")
_reset(m)
for t in [
"He practiced piano for hours perfecting a difficult Chopin nocturne.",
"The orchestra performed Beethoven symphony with remarkable precision.",
"She studied music theory and harmonic progression at the conservatory.",
]:
m.write(t, training_mode=True)
m.eval()
results = []
for seed in [42, 123, 777]:
torch.manual_seed(seed)
with torch.no_grad():
gen = m.generate("The pianist", mt=40, greedy=False)
results.append(gen)
total_music = sum(_count_kw_hits(g, MUSIC_KW) for g in results)
total_space = sum(_count_kw_hits(g, SPACE_KW) for g in results)
R.check("s9_music_gen_has_music_kw",
total_music > 0,
f"total_music_kw={total_music}")
R.check("s9_music_gen_music_gt_space",
total_music >= total_space,
f"music={total_music}, space={total_space}")
for i, g in enumerate(results[:1]):
print(f" gen[{i}]: '{g[:80]}'")
_reset(m)
def test_generation_reflects_space_memory(m, c, R):
"""With space memories, 'The telescope' prompt should generate space-related text."""
print("\n── S10. Generation reflects space memory ──")
_reset(m)
for t in [
"The telescope revealed distant galaxies beyond the Milky Way.",
"Astronauts trained for the Mars mission in simulated zero gravity.",
"The nebula emitted radiation across the electromagnetic spectrum.",
]:
m.write(t, training_mode=True)
m.eval()
results = []
for seed in [42, 123, 777]:
torch.manual_seed(seed)
with torch.no_grad():
gen = m.generate("The space telescope", mt=40, greedy=False)
results.append(gen)
total_space = sum(_count_kw_hits(g, SPACE_KW) for g in results)
total_music = sum(_count_kw_hits(g, MUSIC_KW) for g in results)
R.check("s10_space_gen_has_space_kw",
total_space > 0,
f"total_space_kw={total_space}")
R.check("s10_space_gen_space_gt_music",
total_space >= total_music,
f"space={total_space}, music={total_music}")
for i, g in enumerate(results[:1]):
print(f" gen[{i}]: '{g[:80]}'")
_reset(m)
def test_generation_domain_switching(m, c, R):
"""System should switch domain based on prompt, even with mixed memories."""
print("\n── S11. Generation domain switching ──")
_reset(m)
all_texts = [
"He practiced piano for hours perfecting a difficult Chopin nocturne.",
"The orchestra performed Beethoven symphony with remarkable precision.",
"The telescope revealed distant galaxies beyond the Milky Way.",
"Astronauts trained for the Mars mission in simulated zero gravity.",
]
for t in all_texts:
m.write(t, training_mode=True)
m.eval()
torch.manual_seed(42)
with torch.no_grad():
gen_music = m.generate("The piano performance", mt=40, greedy=False)
gen_space = m.generate("The space telescope", mt=40, greedy=False)
m_in_music = _count_kw_hits(gen_music, MUSIC_KW)
s_in_music = _count_kw_hits(gen_music, SPACE_KW)
s_in_space = _count_kw_hits(gen_space, SPACE_KW)
m_in_space = _count_kw_hits(gen_space, MUSIC_KW)
R.check("s11_music_prompt_music_dominant",
m_in_music >= s_in_music,
f"music_kw={m_in_music}, space_kw={s_in_music}")
R.check("s11_space_prompt_space_dominant",
s_in_space >= m_in_space,
f"space_kw={s_in_space}, music_kw={m_in_space}")
print(f" music_gen: '{gen_music[len('The piano performance'):][:60]}'")
print(f" space_gen: '{gen_space[len('The space telescope'):][:60]}'")
_reset(m)
def test_generation_greedy_consistency(m, c, R):
"""Greedy generation should always produce the same result."""
print("\n── S12. Greedy generation consistency ──")
_reset(m)
m.write("Cats are fluffy animals that love to chase mice.", training_mode=True)
m.eval()
gens = []
for _ in range(3):
with torch.no_grad():
gen = m.generate("The cat", mt=20, greedy=True)
gens.append(gen)
R.check("s12_greedy_all_same",
all(g == gens[0] for g in gens),
f"gens={[g[:40] for g in gens]}")
_reset(m)
# ═══════════════════════════════════════════════════════════════════
# S13-S15. 记忆的影响力 — 有记忆 vs 无记忆
# ═══════════════════════════════════════════════════════════════════
def test_memory_influences_generation(m, c, R):
"""Generation with relevant memories should differ from without."""
print("\n── S13. Memory influences generation ──")
_reset(m)
m.write("The quantum physicist discovered a new subatomic particle.", training_mode=True)
m.write("Dark matter interactions were observed in the hadron collider.", training_mode=True)
m.eval()
with torch.no_grad():
gen_with = m.generate("The physicist", mt=30, greedy=True)
saved = dict(m.amm.tree.store)
saved_root = m.amm.tree.root
saved_nid = m.amm.tree.nid
m.amm.tree.store = {}
m.amm.tree.root = _Node()
with torch.no_grad():
gen_without = m.generate("The physicist", mt=30, greedy=True)
m.amm.tree.store = saved
m.amm.tree.root = saved_root
m.amm.tree.nid = saved_nid
R.check("s13_mem_changes_output",
gen_with != gen_without,
f"with='{gen_with[:50]}', without='{gen_without[:50]}'")
print(f" with memory: '{gen_with[:60]}'")
print(f" no memory: '{gen_without[:60]}'")
_reset(m)
def test_irrelevant_memory_less_impact(m, c, R):
"""Storing irrelevant memories should have less impact on unrelated prompts
than storing relevant ones."""
print("\n── S14. Irrelevant memory less impact ──")
_reset(m)
m.eval()
with torch.no_grad():
gen_base = m.generate("The ancient temple", mt=25, greedy=True)
m.write("The ancient temple was hidden deep within the tropical rainforest.",
training_mode=True)
m.eval()
with torch.no_grad():
gen_relevant = m.generate("The ancient temple", mt=25, greedy=True)
_reset(m)
m.write("Quantum computing uses qubits in superposition states.",
training_mode=True)
m.eval()
with torch.no_grad():
gen_irrelevant = m.generate("The ancient temple", mt=25, greedy=True)
diff_relevant = 1 if gen_relevant != gen_base else 0
diff_irrelevant = 1 if gen_irrelevant != gen_base else 0
R.check("s14_relevant_memory_changes_gen",
diff_relevant >= diff_irrelevant,
f"relevant_changed={diff_relevant}, irrelevant_changed={diff_irrelevant}")
print(f" base: '{gen_base[:60]}'")
print(f" relevant: '{gen_relevant[:60]}'")
print(f" irrelevant:'{gen_irrelevant[:60]}'")
_reset(m)
def test_progressive_memory_accumulation(m, c, R):
"""Adding more same-domain memories should strengthen domain signal."""
print("\n── S15. Progressive memory accumulation ──")
_reset(m)
music_texts = [
"He practiced piano for hours perfecting a difficult Chopin nocturne.",
"The orchestra performed Beethoven symphony with remarkable precision.",
"She studied music theory and harmonic progression at the conservatory.",
"The violinist mastered a complex Bach partita through dedicated practice.",
]
scores = []
for i in range(len(music_texts)):
_reset(m)
for t in music_texts[:i+1]:
m.write(t, training_mode=True)
m.eval()
top_toks, cb = _content_bias_top_tokens(m, "Tell me about music performance.")
music_score = sum(1 for t in top_toks[:20] if t in MUSIC_KW)
scores.append(music_score)
print(f" {i+1} memories: music_score={music_score}")
R.check("s15_more_memories_stronger_signal",
scores[-1] >= scores[0],
f"scores={scores}")
_reset(m)
# ═══════════════════════════════════════════════════════════════════
# S16-S18. 时间衰减与新鲜度
# ═══════════════════════════════════════════════════════════════════
def test_recent_memory_preferred(m, c, R):
"""Recently accessed memories should survive decay while old ones may not."""
print("\n── S16. Recent memory preferred in decay ──")
_reset(m)
dev = _dev(m)
h_old = torch.randn(c.d_LLM, device=dev)
m.amm.store_mem(h_old, 0.1, training_mode=True, source_text="old memory")
m.amm.time += 100
h_new = torch.randn(c.d_LLM, device=dev)
m.amm.store_mem(h_new, 0.5, training_mode=True, source_text="new memory")
m.amm.time += 5000
n_before = len(m.amm.tree.store)
n_decayed = m.amm.decay()
has_new = any(e.source_text == "new memory" for e in m.amm.tree.store.values())
R.check("s16_decay_runs", n_decayed >= 0)
R.check("s16_some_survive", len(m.amm.tree.store) > 0 or n_before == n_decayed)
print(f" before={n_before}, decayed={n_decayed}, has_new={has_new}")
_reset(m)
def test_high_surprise_survives_decay(m, c, R):
"""High-surprise memories may survive decay better than low-surprise ones."""
print("\n── S17. High surprise memory decay resilience ──")
_reset(m)
dev = _dev(m)
h_low = torch.randn(c.d_LLM, device=dev)
m.amm.store_mem(h_low, 0.01, training_mode=True, source_text="boring")
h_high = torch.randn(c.d_LLM, device=dev)
m.amm.store_mem(h_high, 5.0, training_mode=True, source_text="surprising")
m.amm.time += 3000
m.amm.decay()
texts_remaining = [e.source_text for e in m.amm.tree.store.values()]
R.check("s17_decay_completed", True)
print(f" remaining: {texts_remaining}")
_reset(m)
def test_frequently_accessed_survives(m, c, R):
"""Memories accessed many times should have higher retention."""
print("\n── S18. Frequently accessed memory retention ──")
_reset(m)
dev = _dev(m)
h = torch.randn(c.d_LLM, device=dev)
entry = m.amm.store_mem(h, 1.0, training_mode=True, source_text="popular")
entry.cnt = 50
entry.last = m.amm.time
h2 = torch.randn(c.d_LLM, device=dev)
entry2 = m.amm.store_mem(h2, 1.0, training_mode=True, source_text="unpopular")
m.amm.time += 2000
m.amm.decay()
popular_alive = any(e.source_text == "popular" for e in m.amm.tree.store.values())
R.check("s18_frequently_accessed_survives_or_both_decay",
popular_alive or len(m.amm.tree.store) == 0)
print(f" popular_alive={popular_alive}, store_size={len(m.amm.tree.store)}")
_reset(m)
# ═══════════════════════════════════════════════════════════════════
# S19-S21. 记忆合并语义
# ═══════════════════════════════════════════════════════════════════
def test_consolidation_merges_similar(m, c, R):
"""Writing near-identical text repeatedly should consolidate into fewer entries."""
print("\n── S19. Consolidation merges similar memories ──")
_reset(m)
for _ in range(5):
m.write("The cat sat on the mat.", training_mode=True)
n_before = len(m.amm.tree.store)
R.check("s19_dedup_on_write",
n_before <= 5,
f"entries={n_before} (store_mem dedup may reduce)")
n_merged = m.amm.consolidate()
n_after = len(m.amm.tree.store)
R.check("s19_consolidation_reduces_or_maintains",
n_after <= n_before,
f"before={n_before}, after={n_after}")
print(f" writes=5, before_consol={n_before}, merged={n_merged}, after={n_after}")
_reset(m)
def test_consolidation_preserves_content_ids(m, c, R):
"""After consolidation, merged entry should retain content tokens from both parents."""
print("\n── S20. Consolidation preserves content tokens ──")
_reset(m)
dev = _dev(m)
h1 = torch.randn(c.d_LLM, device=dev) * 0.001
m.amm.store_mem(h1, 1.0, training_mode=True,
content_token_ids=[100, 200], source_text="mem_a")
h2 = h1 + torch.randn(c.d_LLM, device=dev) * 0.0001
m.amm.store_mem(h2, 1.0, training_mode=True,
content_token_ids=[300, 400], source_text="mem_b")
m.amm.consolidate()
if len(m.amm.tree.store) == 1:
entry = list(m.amm.tree.store.values())[0]
has_from_a = any(tid in entry.content_token_ids for tid in [100, 200])
has_from_b = any(tid in entry.content_token_ids for tid in [300, 400])
R.check("s20_merged_has_both_content",
has_from_a and has_from_b,
f"ids={entry.content_token_ids}")
else:
R.check("s20_merged_has_both_content", True)
_reset(m)
def test_consolidation_preserves_semantic_emb(m, c, R):
"""After consolidation, merged entry should have a blended semantic embedding."""
print("\n── S21. Consolidation preserves semantic embedding ──")
_reset(m)
dev = _dev(m)
h1 = torch.randn(c.d_LLM, device=dev) * 0.001
sem1 = torch.randn(c.d_LLM, device=dev)
m.amm.store_mem(h1, 1.0, training_mode=True,
content_semantic_emb=sem1, source_text="a")
h2 = h1 + torch.randn(c.d_LLM, device=dev) * 0.0001
sem2 = torch.randn(c.d_LLM, device=dev)
m.amm.store_mem(h2, 1.0, training_mode=True,
content_semantic_emb=sem2, source_text="b")
m.amm.consolidate()
for e in m.amm.tree.store.values():
if e.semantic_emb is not None:
R.check("s21_merged_sem_emb_finite", e.semantic_emb.isfinite().all().item())
R.check("s21_merged_sem_emb_nonzero", e.semantic_emb.abs().max().item() > 0)
break
else:
R.check("s21_merged_sem_emb_finite", True)
R.check("s21_merged_sem_emb_nonzero", True)
_reset(m)
# ═══════════════════════════════════════════════════════════════════
# S22-S24. 训练对语义的影响
# ═══════════════════════════════════════════════════════════════════
def test_training_improves_reconstruction(m, c, R):
"""Training should reduce reconstruction loss over steps."""
print("\n── S22. Training improves reconstruction ──")
_reset(m)
texts = [
"The cat sat on the mat and watched birds outside.",
"Quantum computing uses qubits in superposition states.",
"He practiced piano for hours perfecting a Chopin nocturne.",
"The stock market experienced significant volatility.",
]
for t in texts:
m.write(t, training_mode=True)
trainer = Trainer(m, c)
losses = []
for ep in range(6):
info = trainer.step(texts[:3])
losses.append(info['recon'])
R.check("s22_recon_all_finite",
all(math.isfinite(l) for l in losses))
R.check("s22_recon_not_diverge",
losses[-1] < losses[0] * 3,
f"first={losses[0]:.4f}, last={losses[-1]:.4f}")
print(f" recon losses: {[f'{l:.4f}' for l in losses]}")
m.eval()
_reset(m)
def test_training_preserves_memory_consistency(m, c, R):
"""After training steps, direction tree should remain consistent."""
print("\n── S23. Training preserves tree consistency ──")
_reset(m)
texts = [
"Cats love to chase mice.",
"Dogs enjoy playing fetch.",
"Birds fly south for winter.",
]
for t in texts:
m.write(t, training_mode=True)
trainer = Trainer(m, c)
for _ in range(3):
trainer.step(texts)
errs = m.amm.tree.verify_consistency()
R.check("s23_tree_consistent_after_train", len(errs) == 0, str(errs))
m.eval()
_reset(m)
def test_training_refreshes_memories(m, c, R):
"""Training should trigger memory refresh and preserve semantic embeddings."""
print("\n── S24. Training triggers memory refresh ──")
_reset(m)
texts = [
"Piano music is beautiful.",
"Space exploration continues.",
]
for t in texts:
m.write(t, training_mode=True)
trainer = Trainer(m, c)
trainer.step(texts)
all_have_sem = all(
e.semantic_emb is not None
for e in m.amm.tree.store.values()
)
R.check("s24_post_train_sem_preserved", all_have_sem)
m.eval()
_reset(m)
# ═══════════════════════════════════════════════════════════════════
# S25-S27. 退化防护语义
# ═══════════════════════════════════════════════════════════════════
def test_generation_not_all_punctuation(m, c, R):
"""Generated text should not consist mainly of punctuation."""
print("\n── S25. Generation not all punctuation ──")
_reset(m)
for t in [
"The cat sat on the mat.",
"Piano music is wonderful.",
"Stars shine in the night sky.",
]:
m.write(t, training_mode=True)
m.eval()
for prompt in ["The cat", "The pianist", "Stars and galaxies"]:
torch.manual_seed(42)
with torch.no_grad():
gen = m.generate(prompt, mt=30, greedy=False)
new_text = gen[len(prompt):].strip()
alpha = sum(1 for ch in new_text if ch.isalpha())
ratio = alpha / max(len(new_text), 1)
R.check(f"s25_{prompt[:8]}_alpha_ratio",
ratio > 0.25,
f"ratio={ratio:.2f}, text='{new_text[:50]}'")
_reset(m)
def test_generation_has_content_words(m, c, R):
"""Generated text should contain actual content words, not just function words."""
print("\n── S26. Generation has content words ──")
_reset(m)
m.write("The experienced surgeon performed a complex cardiac operation.", training_mode=True)
m.eval()
cc = m.content_classifier
torch.manual_seed(42)
with torch.no_grad():
gen = m.generate("The surgeon", mt=30, greedy=False)
new_text = gen[len("The surgeon"):].strip()
if new_text:
new_toks = m.tok.encode(new_text)
content_count = len(cc.get_content_ids_from_tokens(new_toks))
content_ratio = content_count / max(len(new_toks), 1)
R.check("s26_gen_has_content_words",
content_ratio > 0.1,
f"content_ratio={content_ratio:.2f}")
else:
R.check("s26_gen_has_content_words", False, "empty generation")
_reset(m)
def test_generation_no_infinite_repeat(m, c, R):
"""Generated text should not have excessive repeated tokens."""
print("\n── S27. Generation no infinite repeat ──")
_reset(m)
m.write("The algorithm computed optimal solutions.", training_mode=True)
m.eval()
for seed in [42, 99, 200]:
torch.manual_seed(seed)
with torch.no_grad():
gen = m.generate("The algorithm", mt=50, greedy=False)
tokens = m.tok.encode(gen)
if len(tokens) >= 5:
max_consec = 1
current_run = 1
for i in range(1, len(tokens)):
if tokens[i] == tokens[i-1]:
current_run += 1
max_consec = max(max_consec, current_run)
else:
current_run = 1
R.check(f"s27_no_repeat_seed{seed}",
max_consec <= 5,
f"max_consecutive={max_consec}")
_reset(m)
# ═══════════════════════════════════════════════════════════════════
# S28-S30. Content bias 语义正确性
# ═══════════════════════════════════════════════════════════════════
def test_content_bias_scales_with_relevance(m, c, R):
"""Content bias magnitude should be higher for relevant queries."""
print("\n── S28. Content bias scales with relevance ──")
_reset(m)
m.write("The pianist performed a stunning Chopin nocturne.", training_mode=True)
m.eval()
_, cb_relevant = _content_bias_top_tokens(m, "Tell me about the piano performance.")
_, cb_irrelevant = _content_bias_top_tokens(m, "How do rockets fly into space?")
rel_max = cb_relevant.abs().max().item()
irr_max = cb_irrelevant.abs().max().item()
R.check("s28_relevant_bias_higher",
rel_max >= irr_max * 0.5,
f"relevant_max={rel_max:.4f}, irrelevant_max={irr_max:.4f}")
print(f" relevant bias max={rel_max:.4f}, irrelevant bias max={irr_max:.4f}")
_reset(m)
def test_content_bias_zero_for_empty_store(m, c, R):
"""With no memories, content bias should be exactly zero."""
print("\n── S29. Content bias zero for empty store ──")
_reset(m)
m.eval()
_, cb = _content_bias_top_tokens(m, "Tell me anything.")
R.check("s29_empty_store_zero_bias", cb.abs().max().item() < 1e-6)
_reset(m)
def test_content_bias_reflects_stored_text(m, c, R):
"""Content bias top tokens should include actual words from stored text."""
print("\n── S30. Content bias reflects stored text ──")
_reset(m)
m.write("The experienced crystallographer analyzed the molecular lattice structure.",
training_mode=True)
m.eval()
top_toks, _ = _content_bias_top_tokens(m, "Tell me about crystal analysis.", k=30)
expected_subset = {'crystal', 'molecular', 'lattice', 'structure',
'crystallographer', 'analyzed', 'experienced'}
found = sum(1 for t in top_toks if any(exp in t for exp in expected_subset))
R.check("s30_bias_has_stored_words",
found >= 1,
f"found={found}, top30={top_toks}")
print(f" top30: {top_toks}")
_reset(m)
# ═══════════════════════════════════════════════════════════════════
# S31-S33. 多记忆干扰与隔离
# ═══════════════════════════════════════════════════════════════════
def test_many_memories_no_catastrophic_interference(m, c, R):
"""Adding many diverse memories should not destroy existing retrieval quality."""
print("\n── S31. Many memories no catastrophic interference ──")
_reset(m)
core_text = "The experienced pianist performed a magnificent Chopin nocturne."
m.write(core_text, training_mode=True)
m.eval()
top_before, _ = _content_bias_top_tokens(m, "Tell me about the piano performance.")
music_before = sum(1 for t in top_before[:15] if t in MUSIC_KW)
distractors = [
"The chef prepared garlic butter sauce.",
"Quantum computing uses qubits.",
"The surgeon performed cardiac surgery.",
"Stock market volatility increased.",
"The architect designed a modern building.",
"Neural networks process visual data.",
"The athlete won a gold medal.",
"Climate change affects polar bears.",
]
for t in distractors:
m.write(t, training_mode=True)
m.eval()
top_after, _ = _content_bias_top_tokens(m, "Tell me about the piano performance.")
music_after = sum(1 for t in top_after[:15] if t in MUSIC_KW)
R.check("s31_music_signal_survives_distractors",
music_after > 0,
f"before={music_before}, after={music_after}")
print(f" music score: before={music_before}, after={music_after}")
_reset(m)
def test_separate_domains_separate_retrieval(m, c, R):
"""Queries from different domains should retrieve different content biases."""
print("\n── S32. Separate domains separate retrieval ──")
_reset(m)
m.write("The pianist performed Chopin beautifully at the concert.", training_mode=True)
m.write("The telescope observed a distant galaxy cluster.", training_mode=True)
m.write("The chef prepared exquisite French cuisine.", training_mode=True)
m.eval()
top_music, _ = _content_bias_top_tokens(m, "Tell me about piano music.")
top_space, _ = _content_bias_top_tokens(m, "What did the telescope observe?")
top_cook, _ = _content_bias_top_tokens(m, "How did the chef cook?")
overlap_ms = len(set(top_music[:10]) & set(top_space[:10]))
overlap_mc = len(set(top_music[:10]) & set(top_cook[:10]))
overlap_sc = len(set(top_space[:10]) & set(top_cook[:10]))
avg_overlap = (overlap_ms + overlap_mc + overlap_sc) / 3
R.check("s32_low_cross_domain_overlap",
avg_overlap < 7,
f"ms={overlap_ms}, mc={overlap_mc}, sc={overlap_sc}")
print(f" overlaps: music-space={overlap_ms}, music-cook={overlap_mc}, space-cook={overlap_sc}")
_reset(m)
def test_same_domain_memories_reinforce(m, c, R):
"""Multiple memories from the same domain should reinforce retrieval."""
print("\n── S33. Same-domain memories reinforce ──")
_reset(m)
m.write("He practiced piano for hours.", training_mode=True)
m.eval()
top1, _ = _content_bias_top_tokens(m, "Tell me about piano.")
score1 = sum(1 for t in top1[:15] if t in MUSIC_KW)
m.write("The orchestra performed Beethoven symphony.", training_mode=True)
m.write("She studied music theory at the conservatory.", training_mode=True)
m.eval()
top3, _ = _content_bias_top_tokens(m, "Tell me about piano.")
score3 = sum(1 for t in top3[:15] if t in MUSIC_KW)