File size: 38,083 Bytes
2f2df6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import os
from pathlib import Path
import modal

APP_NAME = "long-term-memory-qwen"
REMOTE_DIR = "/root/LongTearmMemory"
VOL_NAME = "long-term-memory-vol"

app = modal.App(APP_NAME)

# Memory-layer variants compared in the same training/eval protocol
VARIANTS: dict[str, dict] = {
    "base": {},  # Titans-style: per-token delta rule + momentum, linear M, inner_steps=4
    "atlas": {   # Atlas: polynomial feature map + Omega rule (window) + Muon (Newton-Schulz)
        "mem_poly_dim": 24,
        "mem_omega_window": 16,
        "mem_muon": True,
        "mem_inner_steps": 1,
    },
    "wide": {    # same as base, linear memory widened 256 -> 512 (4x capacity of M)
        "mem_d_mem": 512,
    },
}


def ckpt_path(variant: str) -> str:
    if variant == "base":
        return "/vol/checkpoints/unified_nested_L18_v2_blank.pt"
    return f"/vol/checkpoints/unified_nested_L18_v2_{variant}_blank.pt"

OCCUPATIONS_TH = [
    "ครู", "พยาบาล", "หมอ", "ทันตแพทย์", "เภสัชกร", "วิศวกรโยธา", "วิศวกรไฟฟ้า", "สถาปนิก",
    "นักบัญชี", "ทนายความ", "ตำรวจ", "ทหาร", "นักบิน", "แอร์โฮสเตส", "พ่อครัว", "บาริสต้า",
    "ชาวนา", "ชาวประมง", "ช่างไม้", "ช่างยนต์", "ช่างตัดผม", "นักร้อง", "นักแสดง", "นักเขียน",
    "นักข่าว", "ยูทูบเบอร์", "นักกีฬา", "โค้ชฟิตเนส", "นักวิทยาศาสตร์", "นักวิจัย", "พนักงานธนาคาร",
    "พนักงานขาย", "แม่ค้าออนไลน์", "คนขับรถแท็กซี่", "ไรเดอร์ส่งอาหาร", "สัตวแพทย์", "นักจิตวิทยา",
    "นักการตลาด", "นักวิเคราะห์ข้อมูล", "โปรแกรมเมอร์", "ช่างภาพอิสระ", "นักออกแบบกราฟิก",
]
volume = modal.Volume.from_name(VOL_NAME, create_if_missing=True)

image = (
    modal.Image.debian_slim(python_version="3.11")
    .pip_install(
        "torch>=2.4.0",
        "transformers>=4.45.0",
        "accelerate",
        "numpy",
        "flash-linear-attention",
        "huggingface_hub",
    )
    .add_local_dir(
        local_path=str(Path(__file__).resolve().parent),
        remote_path=REMOTE_DIR,
        ignore=[".env", ".git", "__pycache__", "checkpoints", "*.pt", "*.safetensors", "hf_release", "dataset/generated_backup_v1", "dataset/generated_hard"],
    )
)


@app.function(
    image=image,
    gpu=["L4", "A10G", "T4"],
    timeout=3600,
    volumes={"/vol": volume},
    env={"HF_HOME": "/vol/hf_cache"},
)
def run_demo_gpu() -> str:
    import sys
    os.chdir(REMOTE_DIR)
    sys.path.insert(0, REMOTE_DIR)

    import demo_memory_inject
    demo_memory_inject.main()

    # Copy checkpoint to persistent Modal volume
    ckpt_src = Path(REMOTE_DIR) / "checkpoints" / "demon_lord_moe.pt"
    ckpt_dst = Path("/vol/checkpoints/demon_lord_moe.pt")
    ckpt_dst.parent.mkdir(parents=True, exist_ok=True)
    if ckpt_src.exists():
        ckpt_dst.write_bytes(ckpt_src.read_bytes())
        volume.commit()
    return f"Demo finished on GPU. Checkpoint saved to {ckpt_dst}"


@app.function(
    image=image,
    gpu=["L4", "A10G", "T4"],
    timeout=7200,
    volumes={"/vol": volume},
    env={"HF_HOME": "/vol/hf_cache"},
)
def run_train_gpu(
    max_files: int = 10,
    epochs: int = 2,
    memory_type: str = "moe",
) -> str:
    import sys
    os.chdir(REMOTE_DIR)
    sys.path.insert(0, REMOTE_DIR)

    from config import ProjectConfig
    from dataset.schema import LifeDataset
    from eval import evaluate_life
    from Model.qwen_memory import QwenMemoryWrapper
    from train import train_on_life

    import torch
    cfg = ProjectConfig(dtype=torch.bfloat16)
    print(f"Running on device={cfg.device}, dtype={cfg.dtype}, model={cfg.base_model}, memory={memory_type}")
    wrapper = QwenMemoryWrapper(cfg=cfg, memory_type=memory_type)

    files = sorted((Path(REMOTE_DIR) / "dataset" / "generated").glob("life_*.json"))
    train_files = [f for f in files if LifeDataset.load_json(f).meta.split == "train"][:max_files]
    val_files = [f for f in files if LifeDataset.load_json(f).meta.split == "val"]

    ckpt_dir = Path("/vol/checkpoints")
    ckpt_dir.mkdir(parents=True, exist_ok=True)

    for idx, fp in enumerate(train_files, start=1):
        ds = LifeDataset.load_json(fp)
        train_on_life(wrapper, ds, cfg, epochs_per_session=epochs)
        if idx % 20 == 0:
            interim = ckpt_dir / f"latest_{memory_type}.pt"
            wrapper.save_memory(interim)
            volume.commit()
            print(f"[checkpoint] saved interim after {idx}/{len(train_files)} lives")

    ckpt_path = ckpt_dir / f"merged_{memory_type}_{len(train_files)}lives.pt"
    wrapper.save_memory(ckpt_path)
    volume.commit()
    print(f"Saved checkpoint to {ckpt_path}")

    agg_labels: dict[str, dict[str, float]] = {}
    gen_gates: list[float] = []
    for vf in val_files:
        vds = LifeDataset.load_json(vf)
        res = evaluate_life(wrapper, vds)
        gen_gates.append(res["general_gate_mean"])
        for lbl, st in res["by_label"].items():
            b = agg_labels.setdefault(lbl, {"hit": 0, "total": 0, "gate_sum": 0.0})
            b["hit"] += st["hit"]
            b["total"] += st["total"]
            b["gate_sum"] += st["gate_sum"]

    print(f"\n=== AGGREGATE VAL SUMMARY ({len(val_files)} lives) ===")
    for lbl, st in agg_labels.items():
        acc = st["hit"] / max(1, st["total"])
        g_avg = st["gate_sum"] / max(1, st["total"])
        print(f"  [{lbl:9s}] hit={int(st['hit'])}/{int(st['total'])} ({acc:.1%}) | avg_gate={g_avg:.3f}")
    print(f"  [general  ] avg_gate={sum(gen_gates)/max(1, len(gen_gates)):.3f}")

    return f"Trained on {len(train_files)} lives, evaluated on {len(val_files)} val lives. Saved: {ckpt_path}"


@app.function(
    image=image,
    gpu=["L4", "A10G", "T4"],
    timeout=3600,
    volumes={"/vol": volume},
    env={"HF_HOME": "/vol/hf_cache"},
)
def run_cross_session_test_gpu() -> str:
    import gc
    import random
    import sys
    import torch

    os.chdir(REMOTE_DIR)
    sys.path.insert(0, REMOTE_DIR)

    from config import ProjectConfig
    from dataset.schema import LifeDataset
    from Model.life_memory_moe import LifeMemoryMoE
    from Model.qwen_memory import QwenMemoryWrapper
    from train import GENERAL_TEXTS_TH, compute_sleep_step_loss, encode_qa

    cfg = ProjectConfig(dtype=torch.bfloat16)
    ds = LifeDataset.load_json(Path(REMOTE_DIR) / "dataset" / "generated" / "life_00000.json")

    # --- SESSION 1: Learn & Sleep Consolidate ---
    print("=== SESSION 1: Learning & Sleep Consolidation ===")
    w1 = QwenMemoryWrapper(cfg=cfg, memory_type="moe")
    mem = w1.memory
    assert isinstance(mem, LifeMemoryMoE)
    mem.open_new_period(today=0)

    qa_pairs = []
    for s in ds.sessions:
        for i in range(0, len(s.turns) - 1, 2):
            qa_pairs.append((s.turns[i].text, s.turns[i + 1].text))
    for pr in ds.probes:
        qa_pairs.append((pr.question, pr.ground_truth))
    qa_pairs.extend([
        ("ใครเป็นคนสร้างคุณ", "ฉันคือ AI ที่สร้างจากจอมมาร"),
        ("คุณคือใคร", "ฉันคือ AI ที่สร้างจากจอมมาร"),
    ])

    opt = torch.optim.AdamW(mem.trainable_params(), lr=5e-4, weight_decay=0.01)
    w1.model.train()
    for step in range(1, 51):
        q, a = random.choice(qa_pairs)
        mem_in, mem_lbl = encode_qa(w1.tokenizer, q, a, cfg.device)
        gen_in = w1.tokenizer(random.choice(GENERAL_TEXTS_TH), return_tensors="pt").input_ids.to(cfg.device)
        loss, gm, gg = compute_sleep_step_loss(w1, mem_in, mem_lbl, gen_in, lam_kl=0.5, lam_gate=0.5)
        opt.zero_grad()
        loss.backward()
        torch.nn.utils.clip_grad_norm_(mem.trainable_params(), 1.0)
        opt.step()
        if step % 10 == 0 or step == 1:
            print(f"  [step {step:02d}] loss={loss.item():.4f} gate_mem={gm:.3f} gate_gen={gg:.3f}")
        if step >= 25 and loss.item() < 0.30:
            print(f"  [early-stop step {step:02d}] loss={loss.item():.4f}")
            break

    print("  [Session 1 Answer] Q: คุณคือใคร และใครเป็นคนสร้างคุณ?")
    print("  A:", w1.generate("คุณคือใคร และใครเป็นคนสร้างคุณ?", max_new_tokens=64))

    ckpt_path = Path("/vol/checkpoints/session_test_moe.pt")
    ckpt_path.parent.mkdir(parents=True, exist_ok=True)
    w1.save_memory(ckpt_path)
    volume.commit()

    # Close Session 1 completely
    del w1, mem, opt
    gc.collect()
    torch.cuda.empty_cache()
    print("\n=== SESSION 1 CLOSED (Model deleted from memory) ===")

    # --- SESSION 2: Fresh Instance (No chat history) ---
    print("\n=== SESSION 2: Fresh Model Instance (New Chat) ===")
    w2 = QwenMemoryWrapper(cfg=cfg, memory_type="moe")
    print("  [Before loading .pt] Q: คุณคือใคร และใครเป็นคนสร้างคุณ?")
    print("  A:", w2.generate("คุณคือใคร และใครเป็นคนสร้างคุณ?", max_new_tokens=64))

    w2.load_memory(ckpt_path)
    print(f"\n  [Loaded memory from {ckpt_path}]")
    for tag, q in [
        ("seen", "คุณคือใคร และใครเป็นคนสร้างคุณ?"),
        ("unseen", "ผู้ให้กำเนิดของเธอคือใคร?"),
        ("general", "เมืองหลวงของประเทศไทยคือที่ไหน"),
    ]:
        print(f"  [{tag}] Q: {q}")
        print(f"         A: {w2.generate(q, max_new_tokens=64)}")

    return "Cross-session memory persistence test completed."


@app.function(
    image=image,
    gpu=["L4", "A10G"],
    timeout=6 * 3600,
    volumes={"/vol": volume},
    env={"HF_HOME": "/vol/hf_cache"},
)
def run_titans_unified_test_gpu(fresh: bool = True, epochs: int = 6, max_lives: int = 0, variant: str = "base") -> str:
    """
    1) Outer-loop train NeuralMemoryLayer (Wk, Wv, Wq, out, gates, mix) on train lives
       so the model learns HOW to memorize at test time.
    2) Live chat session 1 (NO optimizer/backprop): just forward pass text into M,
       save the unified model as ONE file, delete it, and reload in Session 2.
    """
    import gc
    import math
    import random
    import re
    import sys
    import torch

    os.chdir(REMOTE_DIR)
    sys.path.insert(0, REMOTE_DIR)

    from config import ProjectConfig
    from dataset.schema import LifeDataset
    from Model.nested_memory import NestedMemoryLayer
    from Model.qwen_memory import QwenMemoryWrapper
    from train import GENERAL_TEXTS_TH, compute_sleep_step_loss, encode_qa

    cfg = ProjectConfig(dtype=torch.bfloat16, **VARIANTS[variant])
    print(f"Variant={variant} options={VARIANTS[variant]}", flush=True)
    w1 = QwenMemoryWrapper(cfg=cfg, memory_type="nested")
    mem = w1.memory
    assert isinstance(mem, NestedMemoryLayer)

    # Dataset v2 run gets its own checkpoint, so the old (v1-data) checkpoint is kept untouched.
    blank_ckpt = Path(ckpt_path(variant))
    if fresh:
        print("Fresh start: memory layer randomly initialised (no resume from older checkpoints)", flush=True)
    elif blank_ckpt.exists():
        state = torch.load(blank_ckpt, map_location=cfg.device)
        w1.model.load_state_dict(state, strict=False)
        print(f"Resumed outer-loop from v2 checkpoint: {blank_ckpt}", flush=True)

    # 1) Episodic Outer-loop (NO sleep at test time): teach Wk/Wv/Wq/out/gates/router on ALL 137 train lives
    files = sorted((Path(REMOTE_DIR) / "dataset" / "generated").glob("life_*.json"))
    train_files = [f for f in files if LifeDataset.load_json(f).meta.split == "train"]
    if max_lives:
        train_files = train_files[:max_lives]  # smoke test
    opt = torch.optim.AdamW([p for p in mem.parameters() if p.requires_grad], lr=1e-3, weight_decay=0.01)

    w1.model.train()
    for epoch in range(1, epochs + 1):
        random.shuffle(train_files)
        total_loss = 0.0
        steps = 0
        for fp in train_files:
            ds = LifeDataset.load_json(fp)
            if not ds.sessions or not ds.probes:
                continue
            mem.reset_memory()

            # Pick the probe FIRST so the turns that actually contain its answer get written into memory.
            # Trainable: remembered probes + "absent" probes (never told -> must answer "you never told me")
            active_probes = [
                p for p in ds.probes if p.recall_label != "forgotten" or p.q_type == "absent"
            ] or ds.probes
            pr = random.choice(active_probes)
            targets = set(pr.target_events)
            past_sessions = [s for s in ds.sessions if s.day <= pr.day] or ds.sessions
            evidence = [t.text for s in past_sessions for t in s.turns if t.speaker == "self" and targets & set(t.refs)]
            if not evidence:
                evidence = [t.text for s in past_sessions for t in s.turns if targets & set(t.refs)]
            if not evidence:
                evidence = [e.summary for e in ds.timeline if e.event_id in targets]
            # A couple of unrelated self statements as distractors (memory must store several facts, not one)
            distractors = [
                t.text
                for s in past_sessions
                for t in s.turns
                if t.speaker == "self" and not (targets & set(t.refs))
                and "?" not in t.text and "ไหม" not in t.text and "อะไร" not in t.text
            ]
            random.shuffle(distractors)

            # Feed self-introduction + evidence turns into differentiable M & V using SAME chat template as inference!
            mem.keep_grad_state = True
            mem.online_update = True
            write_open_losses = []
            p_name = ds.persona.name
            # Dataset occupations are 72% photographer/designer -> guessable without memory.
            # Sample from a wide list so the occupation can only come from memory.
            p_occ = random.choice(OCCUPATIONS_TH + [ds.persona.occupation])
            raw_intros = [f"สวัสดีครับ จำไว้ให้ดีนะ ผมชื่อ{p_name} มีอาชีพเป็น{p_occ}"]
            # Explicit dated fact turns (dataset fix_v2, "จดไว้หน่อยนะ ...") first, then one natural chat turn
            # (after naturalize_evidence they read like "วันนี้วันที่ 6 ผม..." -> rank by containing a day number)
            evidence.sort(key=lambda s: 0 if re.search(r"วันที่ \d+", s) else 1)
            raw_intros += evidence[:3] + distractors[:2]
            random.shuffle(raw_intros)
            for raw_msg in raw_intros:
                try:
                    ctx_text = w1.tokenizer.apply_chat_template(
                        [{"role": "user", "content": raw_msg}],
                        tokenize=False,
                        add_generation_prompt=True,
                        enable_thinking=False,
                    )
                except TypeError:
                    ctx_text = raw_msg
                enc = w1.tokenizer(
                    ctx_text, return_tensors="pt", add_special_tokens=False,
                    truncation=True, max_length=140, return_offsets_mapping=True,
                )
                ctx_in = enc.input_ids.to(cfg.device)
                # Content mask: 1.0 on the user's own words, 0.0 on chat-template tags
                c0 = ctx_text.find(raw_msg)
                c1 = c0 + len(raw_msg)
                offs = enc.offset_mapping[0].tolist()
                content = [1.0 if (c0 >= 0 and a < c1 and b > c0) else 0.0 for a, b in offs]
                _ = w1.model(input_ids=ctx_in)
                if mem.last_write_gate is not None:
                    # Open gate_write on statement content tokens, keep it closed on template tags
                    gw = mem.last_write_gate
                    target_w = torch.tensor(content, device=gw.device, dtype=gw.dtype).view(1, -1, 1)
                    write_open_losses.append(
                        torch.nn.functional.binary_cross_entropy(gw, target_w)
                    )

            # Query BOTH a probe AND explicit name/persona recall in full natural sentences!
            # Keep online_update=True during query so the model learns to close gate_write (~0.000x) on question tokens!
            mem.keep_grad_state = True
            mem.online_update = True
            name_q, name_a = random.choice([
                ("ผมชื่ออะไรครับ และทำอาชีพอะไร", f"คุณชื่อ{p_name}ครับ และมีอาชีพเป็น{p_occ}"),
                ("ผมชื่ออะไรครับ", f"คุณชื่อ{p_name}ครับ และทำงานเป็น{p_occ}"),
                ("คุณจำได้ไหมว่าฉันชื่ออะไร", f"จำได้ครับ คุณชื่อ{p_name}ครับ"),
                ("ฉันชื่ออะไรและทำอาชีพอะไร", f"คุณชื่อ{p_name} และมีอาชีพเป็น{p_occ}ครับ"),
            ])
            qa_targets = [
                (name_q, name_a),
                (pr.question, pr.target_answer),
            ]

            # End of chat session: consolidate medium (M) -> long-term slots (forward-only, neural gate_consol)
            mem.consolidate()
            # Simulate time passing before the next chat: M fades (Ebbinghaus), slots persist.
            # When M has faded, the answer can only come from the consolidated slots -> gate_consol must learn.
            days_gap = random.choice([0, 1, 3, 7, 14, 30, 60])
            M_c, S_c, V_c, bx_c, bs_c = mem._grad_state
            fade = math.exp(-0.05 * days_gap)
            saved_state = (M_c * fade, S_c * 0.0 if days_gap else S_c, V_c, bx_c, bs_c)

            life_loss = torch.tensor(0.0, device=cfg.device)
            for idx_q, (q_text, a_text) in enumerate(qa_targets):
                # Every query starts from the same post-consolidation memory (no leakage between queries)
                mem._grad_state = tuple(t.clone() for t in saved_state)
                mem_in, mem_lbl = encode_qa(w1.tokenizer, q_text, a_text, cfg.device)
                gen_q = random.choice([
                    "เมืองหลวงของประเทศไทยคือที่ไหน",
                    "น้ำเดือดที่อุณหภูมิกี่องศาเซลเซียส",
                    "ดวงอาทิตย์ขึ้นทางทิศใด",
                    "ภาษาไพทอนนิยมใช้ในงานด้านใด",
                ] + GENERAL_TEXTS_TH)
                try:
                    gen_chat = w1.tokenizer.apply_chat_template(
                        [{"role": "user", "content": gen_q}],
                        tokenize=False,
                        add_generation_prompt=True,
                        enable_thinking=False,
                    )
                except TypeError:
                    gen_chat = gen_q
                gen_in = w1.tokenizer(gen_chat, return_tensors="pt", add_special_tokens=False).input_ids.to(cfg.device)
                loss, gm, gg = compute_sleep_step_loss(w1, mem_in, mem_lbl, gen_in, lam_kl=0.5, lam_gate=0.8)
                weight_q = 2.5 if idx_q == 0 else 1.0
                life_loss = life_loss + weight_q * loss
            life_loss = life_loss / 3.5
            if write_open_losses:
                life_loss = life_loss + 0.8 * (sum(write_open_losses) / len(write_open_losses))
            opt.zero_grad()
            life_loss.backward()
            torch.nn.utils.clip_grad_norm_(mem.parameters(), 1.0)
            opt.step()
            total_loss += life_loss.item()
            steps += 1
            mem._grad_state = None
            if steps % 35 == 0 or (max_lives and steps % 1 == 0):
                print(
                    f"  [epoch {epoch:02d} step {steps:03d}/{len(train_files)}] avg_loss={total_loss/steps:.4f} gate_mem={gm:.3f} gate_gen={gg:.3f}",
                    flush=True,
                )
                mem.reset_memory()
                w1.save_unified_model(blank_ckpt)
                volume.commit()

        avg_loss = total_loss / max(1, steps)
        print(f"[nested outer-loop epoch {epoch:02d}/{epochs:02d}] avg_loss={avg_loss:.4f} last_gate_mem={gm:.3f} last_gate_gen={gg:.3f}", flush=True)
        mem.reset_memory()
        w1.save_unified_model(blank_ckpt)
        volume.commit()

    # Wipe training memories completely before saving the base deployable model!
    mem.reset_memory()
    base_deploy_path = Path(f"/vol/checkpoints/unified_nested_{variant}_deploy_blank.pt")
    w1.save_unified_model(base_deploy_path)

    # 2) Deploy to User: Live Session 1 (Zero backprop, NO sleep — online forward pass only!)
    print("\n=== NEW USER DEPLOYMENT (M=0, V=0, NO Sleep, Online Forward Pass Only) ===")
    w1.memorize_text("จำไว้ให้ดีนะ ฉันคือ AI ที่สร้างจากจอมมาร")
    print(f"  Consolidate at end of chat -> {w1.end_session()}")
    print(f"  After reading fact online -> M_norm={mem.M.norm().item():.4f} V_norm={mem.slot_values.norm().item():.4f}")

    unified_path = Path(f"/vol/checkpoints/unified_nested_{variant}_demo_model.pt")
    w1.save_unified_model(unified_path)
    volume.commit()

    del w1, mem, opt
    gc.collect()
    torch.cuda.empty_cache()

    # 3) Live Chat Session 2 (Load ONE unified model file)
    print("\n=== LIVE SESSION 2 (Fresh Instance, Loaded Unified Nested Model) ===")
    w2 = QwenMemoryWrapper(cfg=cfg, memory_type="nested")
    w2.load_unified_model(unified_path)
    for q in ["คุณคือใคร และใครเป็นคนสร้างคุณ?", "เมืองหลวงของประเทศไทยคือที่ไหน"]:
        print(f"  Q: {q}")
        print(f"  A: {w2.generate(q, max_new_tokens=64, update_memory=False)}")

    return f"Titans unified model test completed. Saved: {unified_path}"


@app.function(
    image=image,
    gpu=["L4", "A10G"],
    timeout=3 * 3600,
    volumes={"/vol": volume},
    env={"HF_HOME": "/vol/hf_cache"},
)
def run_eval_gpu(variant: str = "base", splits: str = "val,test", protocol: str = "life", max_lives: int = 0) -> dict:
    """Same life-simulation eval for every variant (see eval_nested.py)."""
    import sys

    os.chdir(REMOTE_DIR)
    sys.path.insert(0, REMOTE_DIR)
    from eval_nested import run_eval

    volume.reload()
    return run_eval(variant, ckpt_dir="/vol/checkpoints", data_dir="dataset/generated", splits=splits, protocol=protocol, max_lives=max_lives)


@app.function(
    image=image,
    gpu=["L4", "A10G"],
    timeout=8 * 3600,
    volumes={"/vol": volume},
    env={"HF_HOME": "/vol/hf_cache"},
)
def run_train_nested_gpu(variant: str = "base", epochs: int = 6, fresh: bool = True,
                         lora_epochs: int = 0, max_lives: int = 0) -> dict:
    """Phase 1 (frozen) and/or phase 2 (LoRA) via train_nested.py; epochs=0 + fresh=False = LoRA on top of phase 1."""
    import sys

    os.chdir(REMOTE_DIR)
    sys.path.insert(0, REMOTE_DIR)
    from train_nested import train

    volume.reload()
    return train(variant, data_dir="dataset/generated", ckpt_dir="/vol/checkpoints", epochs=epochs,
                 fresh=fresh, max_lives=max_lives, lora_epochs=lora_epochs, commit=volume.commit)


@app.function(
    image=image,
    gpu=["L4", "A10G"],
    timeout=10 * 3600,
    volumes={"/vol": volume},
    env={"HF_HOME": "/vol/hf_cache"},
)
def run_train_v3_gpu(variant: str = "v3", steps: int = 2400, eval_every: int = 300) -> dict:
    """v3: shifted-key memory + read loss + random-entity curriculum (train_v3.py)."""
    import sys

    os.chdir(REMOTE_DIR)
    sys.path.insert(0, REMOTE_DIR)
    from train_v3 import train_v3

    volume.reload()
    Path("/vol/results").mkdir(parents=True, exist_ok=True)
    return train_v3(variant, ckpt_dir="/vol/checkpoints", steps=steps, eval_every=eval_every,
                    commit=volume.commit, log_path=f"/vol/results/train_log_{variant}.json")


@app.function(
    image=image,
    gpu=["L4", "A10G"],
    timeout=12 * 3600,
    volumes={"/vol": volume},
    env={"HF_HOME": "/vol/hf_cache"},
)
def run_train_v4_gpu(variant: str = "v3_atlas_wide", steps: int = 2500, eval_every: int = 500,
                     lam_rec: float = 0.0, tag: str = "", init: str = "", mix_general: float = 0.0,
                     lora_rank: int = 0, lora_lr: float = 1e-4, mix_personal: float = 0.0) -> dict:
    """v4: public data + generic copy + multi-session interference, warm start from HF v3_atlas (train_v4.py)."""
    import sys
    from huggingface_hub import hf_hub_download

    os.chdir(REMOTE_DIR)
    sys.path.insert(0, REMOTE_DIR)
    from train_v4 import train_v4

    volume.reload()
    if init:
        import shutil
        Path("/vol/init").mkdir(parents=True, exist_ok=True)
        dst = f"/vol/init/{Path(init).name}"
        shutil.copy(init, dst)  # frozen copy: the source may still be rewritten by a running job
        init = dst
    else:
        init = hf_hub_download("Jommarn/Qwen3.5-0.8B-NestedMemory-L18-v3", "unified_nested_L18_v3_atlas_blank.pt",
                               local_dir="/vol/init")
    Path("/vol/results").mkdir(parents=True, exist_ok=True)
    return train_v4(variant, init_ckpt=init, out_dir="/vol/checkpoints", steps=steps, eval_every=eval_every,
                    log_path=f"/vol/results/train_log_{variant.replace('v3', 'v4')}{tag}.json", commit=volume.commit,
                    lam_rec=lam_rec, tag=tag, mix_general=mix_general, lora_rank=lora_rank, lora_lr=lora_lr,
                    mix_personal=mix_personal)


@app.function(
    image=image,
    gpu=["L4", "A10G"],
    timeout=8 * 3600,
    volumes={"/vol": volume},
    env={"HF_HOME": "/vol/hf_cache"},
)
def run_eval_v4_gpu(variant: str = "v4_atlas", n_per: int = 100) -> dict:
    """OOD templates test + life-sim (val+test) + short protocol (val) for a v4 checkpoint."""
    import json, sys

    os.chdir(REMOTE_DIR)
    sys.path.insert(0, REMOTE_DIR)
    from eval_nested import run_eval
    from eval_v4_ood import run_ood_eval

    volume.reload()
    out = {"variant": variant}
    out["ood"] = run_ood_eval(variant, f"/vol/checkpoints/unified_nested_L18_{variant}_blank.pt", n_per)
    Path("/vol/results").mkdir(parents=True, exist_ok=True)
    Path(f"/vol/results/eval_{variant}_ood.json").write_text(json.dumps(out["ood"], ensure_ascii=False, indent=2))
    volume.commit()
    for proto, splits in (("short", "val"), ("life", "val,test")):
        r = run_eval(variant, ckpt_dir="/vol/checkpoints", splits=splits, protocol=proto)
        Path(f"/vol/results/eval_{variant}_{proto}.json").write_text(json.dumps(r, ensure_ascii=False, indent=2))
        volume.commit()
        out[proto] = r["summary"]
        print("SUMMARY", proto, json.dumps(r["summary"], ensure_ascii=False), flush=True)
    return out


@app.function(
    image=image,
    gpu=["L4", "A10G"],
    timeout=12 * 3600,
    volumes={"/vol": volume},
    env={"HF_HOME": "/vol/hf_cache"},
)
def run_rl_gpu(variant: str, init: str, steps: int = 1500, eval_every: int = 250, beta: float = 0.05,
               rep_pen: float = 0.5, lora_rank: int = 0, tag: str = "", beta_ref: float = 0.0) -> dict:
    """Phase D: GRPO (train_rl.py) starting from a phase-B/C checkpoint on the volume."""
    import shutil, sys

    os.chdir(REMOTE_DIR)
    sys.path.insert(0, REMOTE_DIR)
    from train_rl import grpo_train

    volume.reload()
    Path("/vol/init").mkdir(parents=True, exist_ok=True)
    dst = f"/vol/init/rl_{Path(init).name}"
    shutil.copy(init, dst)
    return grpo_train(variant, dst, out_dir="/vol/checkpoints", steps=steps, eval_every=eval_every, beta=beta,
                      rep_pen=rep_pen, lora_rank=lora_rank, tag=tag, beta_ref=beta_ref,
                      log_path=f"/vol/results/train_log_{variant}_rl{tag}.json", commit=volume.commit)


@app.function(image=image, timeout=3600, volumes={"/vol": volume}, env={"HF_HOME": "/vol/hf_cache"})
def fetch_hf_ckpt(repo: str, filename: str, dst_name: str) -> str:
    """Copy a checkpoint from the Hugging Face Hub into /vol/checkpoints (moves models between cloud accounts)."""
    import shutil
    from huggingface_hub import hf_hub_download
    p = hf_hub_download(repo, filename, local_dir="/vol/hf_dl")
    Path("/vol/checkpoints").mkdir(parents=True, exist_ok=True)
    shutil.copy(p, f"/vol/checkpoints/{dst_name}")
    volume.commit()
    return f"/vol/checkpoints/{dst_name} {Path(p).stat().st_size}"


@app.local_entrypoint()
def main(
    mode: str = "demo",
    max_files: int = 10,
    epochs: int = 2,
    memory_type: str = "moe",
    resume: bool = False,
    max_lives: int = 0,
    variant: str = "base",
    lora_epochs: int = 0,
    splits: str = "val,test",
    protocol: str = "life",
):
    if mode == "demo":
        print(run_demo_gpu.remote())
    elif mode == "train":
        print(run_train_gpu.remote(max_files=max_files, epochs=epochs, memory_type=memory_type))
    elif mode == "cross_session":
        print(run_cross_session_test_gpu.remote())
    elif mode == "eval":
        import json as _json
        res = run_eval_gpu.remote(variant=variant, splits=splits, protocol=protocol, max_lives=max_lives)
        out = Path(__file__).resolve().parent / "results" / (f"eval_{variant}.json" if protocol == "life" and splits == "val,test" else f"eval_{variant}_{protocol}_{splits.replace(',', '-')}.json")
        out.parent.mkdir(exist_ok=True)
        out.write_text(_json.dumps(res, ensure_ascii=False, indent=2), encoding="utf-8")
        print(_json.dumps(res["summary"], ensure_ascii=False, indent=2))
        print(f"saved -> {out}")
    elif mode == "train2":
        print(run_train_nested_gpu.remote(variant=variant, epochs=epochs, fresh=not resume,
                                          lora_epochs=lora_epochs, max_lives=max_lives))
    elif mode == "train3":
        import json as _json
        log = run_train_v3_gpu.remote(variant=variant, steps=max_files, eval_every=max(50, max_files // 8))
        out = Path(__file__).resolve().parent / "results" / f"train_log_{variant}.json"
        out.write_text(_json.dumps(log, ensure_ascii=False, indent=2), encoding="utf-8")
        print(_json.dumps(log.get("checks", []), ensure_ascii=False, indent=2))
    elif mode == "train4":
        import json as _json
        tag = "b" if protocol == "rec" else ""
        init = f"/vol/checkpoints/unified_nested_L18_{splits}_blank.pt" if splits.startswith("v4") else ""
        log = run_train_v4_gpu.remote(variant=variant, steps=max_files, eval_every=max(100, max_files // 10),
                                      lam_rec=0.5 if tag else 0.0, tag=tag, init=init)
        out = Path(__file__).resolve().parent / "results" / f"train_log_{variant.replace('v3', 'v4')}{tag}.json"
        out.write_text(_json.dumps(log, ensure_ascii=False, indent=2), encoding="utf-8")
        print(_json.dumps([{k: v for k, v in c.items() if k != "samples"} for c in log.get("checks", [])], indent=2))
    elif mode == "eval4":
        import json as _json
        res = run_eval_v4_gpu.remote(variant=variant, n_per=max_files)
        out = Path(__file__).resolve().parent / "results" / f"eval4_{variant}.json"
        out.write_text(_json.dumps(res, ensure_ascii=False, indent=2), encoding="utf-8")
        print(_json.dumps(res["ood"]["summary"], ensure_ascii=False, indent=2))
    elif mode == "titans_test":
        print(run_titans_unified_test_gpu.remote(fresh=not resume, epochs=epochs, max_lives=max_lives, variant=variant))
    else:
        raise ValueError(f"Unknown mode: {mode}. Use 'demo', 'train', 'cross_session', or 'titans_test'.")


def _final_eval(variant: str) -> dict:
    """OOD + chat-return + held-out personal (TH/EN real words) for a finished checkpoint; results -> /vol/results."""
    import json, random
    import torch
    from eval_chat_return import run_chat_eval
    from eval_v4_ood import run_ood_eval
    ck = f"/vol/checkpoints/unified_nested_L18_{variant}_blank.pt"
    out = {"variant": variant, "ood": run_ood_eval(variant, ck, 100)["summary"]}
    Path(f"/vol/results/eval_{variant}_ood.json").write_text(json.dumps(out["ood"], ensure_ascii=False, indent=2))
    volume.commit()
    chat = run_chat_eval(variant, ck, 40)
    Path(f"/vol/results/eval_{variant}_chat.json").write_text(json.dumps(chat, ensure_ascii=False, indent=2))
    out["chat"] = {k: v for k, v in chat.items() if k != "transcripts"}
    volume.commit()
    from config import ProjectConfig
    from Model.qwen_memory import QwenMemoryWrapper
    from personal_facts import ValuePools
    from train_nested import variant_options
    from train_v4 import Pools, heldout_check
    cfg = ProjectConfig(dtype=torch.bfloat16, **variant_options(variant))
    w = QwenMemoryWrapper(cfg=cfg, memory_type="nested")
    w.model.load_state_dict(torch.load(ck, map_location=cfg.device), strict=False)
    w.model.eval()
    out["heldout"] = heldout_check(w, Pools("test"), n=60, seed=4242, V=ValuePools("test"))
    Path(f"/vol/results/eval_{variant}_final.json").write_text(json.dumps(out, ensure_ascii=False, indent=2))
    volume.commit()
    print("FINAL", json.dumps({k: v for k, v in out.items() if k != "heldout"}, ensure_ascii=False), flush=True)
    print("HELDOUT", json.dumps({k: v for k, v in out["heldout"].items() if k != "samples"}), flush=True)
    return out


@app.function(image=image, gpu=["L4", "A10G"], timeout=14 * 3600, volumes={"/vol": volume},
              env={"HF_HOME": "/vol/hf_cache"})
def run_v5b_pipeline(steps: int = 1500, mix_personal: float = 0.35) -> dict:
    """0.8B: continue v5 with real-word personal facts (TH+EN), then full eval. Also evals v5 itself (baseline)."""
    import sys
    from huggingface_hub import hf_hub_download
    os.chdir(REMOTE_DIR)
    sys.path.insert(0, REMOTE_DIR)
    from train_v4 import train_v4
    import shutil
    Path("/vol/results").mkdir(parents=True, exist_ok=True)
    Path("/vol/checkpoints").mkdir(parents=True, exist_ok=True)
    init = hf_hub_download("Jommarn/Qwen3.5-0.8B-NestedMemory-v5", "unified_nested_L18_v5_l10_blank.pt", local_dir="/vol/init")
    shutil.copy(init, "/vol/checkpoints/unified_nested_L18_v5_l10_blank.pt")
    volume.commit()
    base = _final_eval("v5_l10")     # same final protocol for the baseline
    train_v4("v5b", init_ckpt=init, out_dir="/vol/checkpoints", steps=steps, eval_every=250,
             log_path="/vol/results/train_log_v5b.json", commit=volume.commit, mix_general=0.4, mix_personal=mix_personal)
    return {"v5": base, "v5b": _final_eval("v5b")}


@app.function(image=image, gpu=["L40S", "A100-40GB"], timeout=20 * 3600, volumes={"/vol": volume},
              env={"HF_HOME": "/vol/hf_cache"})
def run_v6_pipeline(s1_steps: int = 2400, s2_steps: int = 2000, mix_personal: float = 0.35) -> dict:
    """Qwen3.5-2B: stage 1 = v3 synthetic curriculum (memory at layer 18 learns to retrieve),
    stage 2 = v4/v5 recipe (+ layer-10 memory, 40% general chat, real-word personal facts TH+EN), then full eval."""
    import sys
    os.chdir(REMOTE_DIR)
    sys.path.insert(0, REMOTE_DIR)
    from train_v3 import train_v3
    from train_v4 import train_v4
    Path("/vol/results").mkdir(parents=True, exist_ok=True)
    s1 = Path("/vol/checkpoints/unified_nested_L18_v6_2b_s1_blank.pt")
    if not s1.exists():   # resumable: skip stage 1 if a previous attempt finished it
        train_v3("v6_2b_s1", ckpt_dir="/vol/checkpoints", steps=s1_steps, eval_every=300, commit=volume.commit,
                 log_path="/vol/results/train_log_v6_2b_s1.json")
    train_v4("v6_2b", init_ckpt=str(s1), out_dir="/vol/checkpoints", steps=s2_steps, eval_every=250,
             log_path="/vol/results/train_log_v6_2b.json", commit=volume.commit, mix_general=0.4, mix_personal=mix_personal)
    return _final_eval("v6_2b")


@app.function(image=image, gpu=["L40S", "A100-40GB"], timeout=1800, volumes={"/vol": volume},
              env={"HF_HOME": "/vol/hf_cache"})
def smoke_v6(steps: int = 6) -> str:
    """Few steps of both stages on 2B (memory / speed check) - nothing saved."""
    import sys, time
    import torch
    os.chdir(REMOTE_DIR)
    sys.path.insert(0, REMOTE_DIR)
    from train_v3 import train_v3
    from train_v4 import train_v4
    t = time.time()
    train_v3("v6_2b_s1", ckpt_dir="/tmp/ck", steps=steps, eval_every=10**9, log_path="/tmp/l1.json")
    t1 = time.time() - t
    s1 = "/tmp/ck/unified_nested_L18_v6_2b_s1_last.pt"
    if not Path(s1).exists():
        s1 = next(iter(Path("/tmp/ck").glob("*.pt")), None)
    t = time.time()
    train_v4("v6_2b", init_ckpt=str(s1) if s1 else None, out_dir="/tmp/ck2", steps=steps, eval_every=10**9,
             log_path="/tmp/l2.json", mix_general=0.4, mix_personal=0.35)
    t2 = time.time() - t
    return f"stage1 {steps} steps {t1:.0f}s, stage2 {steps} steps {t2:.0f}s, peak {torch.cuda.max_memory_allocated()/1e9:.1f} GB"