File size: 20,685 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
"""
v3 outer-loop training: teach the memory layer to RETRIEVE (v2 never learned it: name recall 0%).

Changes vs train_nested.py (v2):
  1. architecture: shift_key (key t-1 -> value t) + res_rel (injection scaled to the residual RMS)
  2. read loss: the raw memory read at each answer position, decoded by Qwen's own final norm + lm_head,
     must predict the next answer token -> direct gradient into Wq/Wk/Wv/fast_out
  3. entities are random every step (syllable-built names, pets, numbers ...) -> cannot be memorised
     from training data, only copied from memory
  4. curriculum: A) facts told then asked immediately -> B) several messages + distractors + consolidation
     + time gap -> C) mixed with full life-dataset steps
  5. held-out recall check (generation, unseen entities) every eval_every steps; best checkpoint kept
"""
from __future__ import annotations

import json
import math
from pathlib import Path
import random
from typing import Callable

import torch
import torch.nn.functional as F

from config import ProjectConfig
from dataset.schema import LifeDataset
from Model.qwen_memory import QwenMemoryWrapper
from train import GENERAL_TEXTS_TH, encode_qa
from train_nested import OCCUPATIONS_TH, _chat

V3_VARIANTS: dict[str, dict] = {
    "v3": {"mem_shift_key": True, "mem_res_rel": True},
    "v3_atlas": {"mem_shift_key": True, "mem_res_rel": True, "mem_poly_dim": 24, "mem_omega_window": 16,
                 "mem_muon": True, "mem_inner_steps": 1},
}
V3_VARIANTS["v6_2b_s1"] = {**V3_VARIANTS["v3_atlas"], "base_model": "Qwen/Qwen3.5-2B"}


def v3_ckpt_name(variant: str) -> str:
    return f"unified_nested_L18_{variant}_blank.pt"


# ---------------------------------------------------------------------------- random entities
SYL = ["กา", "นิ", "ชา", "พร", "ดา", "วิ", "ภู", "มิ", "ธน", "กร", "สุ", "ปิ", "ยะ", "รัตน์", "ณัฐ", "ชัย", "ศักดิ์",
       "ทิพ", "อร", "จิ", "รา", "พล", "เมธ", "ตะ", "วัน", "ฟ้า", "ใส", "บุญ", "มี", "แก้ว", "ทอง", "เพชร", "ลี", "นา",
       "ปอ", "เจ", "ต้น", "บี", "มด", "ฝน", "เอก", "โอ๊ต", "แพร", "ฟาง", "ข้าว", "หนู", "ตูน", "เบล", "จูน", "ปัน",
       "ภา", "สิริ", "กุล", "นันท์", "ธิ", "ศรี", "วร", "อัญ", "ชลิ", "ปภา", "คุณ", "ธาร", "เดช", "อนุ", "ไอ", "ริน"]
PROVINCES = ["เชียงใหม่", "เชียงราย", "ลำปาง", "น่าน", "ขอนแก่น", "อุดรธานี", "นครราชสีมา", "อุบลราชธานี", "สกลนคร",
             "ชลบุรี", "ระยอง", "จันทบุรี", "ตราด", "ภูเก็ต", "กระบี่", "สงขลา", "สุราษฎร์ธานี", "นครศรีธรรมราช",
             "ตรัง", "พิษณุโลก", "สุโขทัย", "กาญจนบุรี", "ราชบุรี", "เพชรบุรี", "อยุธยา", "ลพบุรี", "สระบุรี", "ตาก"]
FOODS = ["ส้มตำ", "ข้าวมันไก่", "ผัดไทย", "ต้มยำกุ้ง", "ข้าวซอย", "แกงเขียวหวาน", "ข้าวเหนียวมะม่วง", "กะเพราหมูกรอบ",
         "ก๋วยเตี๋ยวเรือ", "ราเมง", "ซูชิ", "พิซซ่า", "สเต๊ก", "หมูกระทะ", "ชาบู", "ขนมจีนน้ำยา", "โจ๊ก", "บะหมี่เกี๊ยว"]
PETS = ["แมว", "หมา", "กระต่าย", "นกแก้ว", "หนูแฮมสเตอร์", "ปลาทอง", "เต่า"]
COLORS = ["สีแดง", "สีน้ำเงิน", "สีเขียว", "สีเหลือง", "สีม่วง", "สีชมพู", "สีส้ม", "สีดำ", "สีขาว", "สีเทา", "สีฟ้า"]
FILLERS = ["วันนี้ฝนตกหนักมากเลย รถติดสุดๆ", "เมื่อวานดูหนังมาเรื่องหนึ่ง สนุกดีนะ", "ช่วงนี้งานยุ่งมาก นอนไม่ค่อยพอ",
           "ตอนเช้าไปวิ่งที่สวนสาธารณะมา", "อากาศร้อนจนไม่อยากออกจากบ้านเลย", "เพิ่งซื้อหนังสือใหม่มาสองเล่ม",
           "สุดสัปดาห์นี้อาจจะไปเที่ยวทะเล", "กาแฟร้านใหม่แถวบ้านอร่อยดี", "เมื่อคืนนอนดึกเพราะดูซีรีส์",
           "วันนี้ทำความสะอาดบ้านทั้งวัน", "อยากลองหัดทำขนมดูบ้าง", "เพื่อนชวนไปกินข้าวเย็นนี้"]
NEVER_TOLD = "คุณยังไม่เคยบอกเรื่องนี้กับผมเลยครับ"


def rand_name(rng: random.Random) -> str:
    return "".join(rng.choice(SYL) for _ in range(rng.choice([1, 2, 2, 3])))


def make_fact(kind: str, rng: random.Random) -> dict:
    sp = " " if rng.random() < 0.5 else ""  # Thai with / without a space before the entity
    if kind == "name":
        x = rand_name(rng)
        return dict(kind=kind, val=x, say=f"ผมชื่อ{sp}{x}", q=rng.choice(["ผมชื่ออะไรครับ", "คุณจำได้ไหมว่าผมชื่ออะไร"]),
                    a=f"คุณชื่อ{sp}{x}ครับ")
    if kind == "occupation":
        x = rng.choice(OCCUPATIONS_TH)
        verb = rng.choice(["ทำงานเป็น", "มีอาชีพเป็น", "เป็น"])
        return dict(kind=kind, val=x, say=f"ผม{verb}{sp}{x}", q=rng.choice(["ผมทำอาชีพอะไรครับ", "ผมทำงานอะไร"]),
                    a=f"คุณ{verb}{sp}{x}ครับ")
    if kind == "hometown":
        x = rng.choice(PROVINCES)
        return dict(kind=kind, val=x, say=f"บ้านเกิดผมอยู่ที่จังหวัด{x}", q="บ้านเกิดผมอยู่จังหวัดอะไร",
                    a=f"บ้านเกิดของคุณอยู่ที่จังหวัด{x}ครับ")
    if kind == "pet":
        p, x = rng.choice(PETS), rand_name(rng)
        return dict(kind=kind, val=x, say=f"ผมเลี้ยง{p}ไว้ตัวหนึ่ง ชื่อ{sp}{x}", q=f"{p}ของผมชื่ออะไร",
                    a=f"{p}ของคุณชื่อ{sp}{x}ครับ")
    if kind == "food":
        x = rng.choice(FOODS)
        return dict(kind=kind, val=x, say=f"อาหารที่ผมชอบที่สุดคือ{sp}{x}", q="อาหารที่ผมชอบที่สุดคืออะไร",
                    a=f"อาหารที่คุณชอบที่สุดคือ{sp}{x}ครับ")
    if kind == "age":
        x = str(rng.randint(15, 75))
        return dict(kind=kind, val=x, say=f"ปีนี้ผมอายุ {x} ปีแล้ว", q="ปีนี้ผมอายุเท่าไหร่", a=f"ปีนี้คุณอายุ {x} ปีครับ")
    if kind == "color":
        x = rng.choice(COLORS)
        return dict(kind=kind, val=x, say=f"สีที่ผมชอบคือ{x}", q="ผมชอบสีอะไร", a=f"คุณชอบ{x}ครับ")
    if kind == "friend":
        x = rand_name(rng)
        return dict(kind=kind, val=x, say=f"เพื่อนสนิทของผมชื่อ{sp}{x}", q="เพื่อนสนิทของผมชื่ออะไร",
                    a=f"เพื่อนสนิทของคุณชื่อ{sp}{x}ครับ")
    raise ValueError(kind)


KINDS = ["name", "occupation", "hometown", "pet", "food", "age", "color", "friend"]


def make_episode(stage: str, rng: random.Random) -> dict:
    """stage A: 1-2 facts in ONE message, ask now. stage B: 2-4 facts over several messages + fillers,
    consolidation and a time gap. Sometimes asks a fact that was never told."""
    n = rng.randint(1, 2) if stage == "A" else rng.randint(2, 4)
    kinds = rng.sample(KINDS, n + 1)
    facts = [make_fact(k, rng) for k in kinds[:n]]
    if stage == "A":
        msgs = [("สวัสดีครับ " if rng.random() < 0.5 else "") + " และ".join(f["say"] for f in facts)]
        gap = 0
    else:
        msgs = [f["say"] + rng.choice(["", " นะครับ", " จำไว้ด้วยนะ"]) for f in facts]
        msgs += rng.sample(FILLERS, rng.randint(1, 2))
        rng.shuffle(msgs)
        gap = rng.choice([0, 0, 1, 3, 7, 14])
    asks = rng.sample(facts, min(len(facts), 2))
    qa = [(f["q"], f["a"], f["val"]) for f in asks]
    if rng.random() < 0.2:
        absent = make_fact(kinds[n], rng)
        qa.append((absent["q"], NEVER_TOLD, None))
    return dict(msgs=msgs, qa=qa, gap=gap, consolidate=stage != "A")


# ---------------------------------------------------------------------------- losses
def _lm_decode(w: QwenMemoryWrapper, y: torch.Tensor) -> torch.Tensor:
    """Decode a layer-18 vector with Qwen's own final norm + lm_head (frozen) -> vocab logits."""
    head = w.model.get_output_embeddings()
    inner = w.model.model
    norm = getattr(inner, "norm", None) or getattr(getattr(inner, "language_model", None), "norm", None)
    return head(norm(y.to(head.weight.dtype))).float()


def write_messages(w: QwenMemoryWrapper, msgs: list[str], device: str) -> list[torch.Tensor]:
    """Feed user messages (memory writes itself); BCE: write gate open on the user's words, closed on template."""
    mem, tok = w.memory, w.tokenizer
    mem.keep_grad_state = True
    mem.online_update = True
    out = []
    for raw in msgs:
        ctx = _chat(tok, raw)
        enc = tok(ctx, return_tensors="pt", add_special_tokens=False, truncation=True, max_length=140,
                  return_offsets_mapping=True)
        c0 = ctx.find(raw)
        c1 = c0 + len(raw)
        content = [1.0 if (c0 >= 0 and a < c1 and b > c0) else 0.0 for a, b in enc.offset_mapping[0].tolist()]
        w.model(input_ids=enc.input_ids.to(device))
        gw = mem.last_write_gate
        if gw is not None:
            tgt = torch.tensor(content, device=gw.device, dtype=gw.dtype).view(1, -1, 1)
            out.append(F.binary_cross_entropy(gw, tgt))
    return out


def qa_loss(w: QwenMemoryWrapper, q: str, a: str, device: str, lam_read: float = 1.0) -> tuple[torch.Tensor, dict]:
    mem, tok = w.memory, w.tokenizer
    w.bypass_memory = False
    ids, lbl = encode_qa(tok, q, a, device)
    out_m = w.model(input_ids=ids, labels=lbl)
    g_r, g_w = mem.last_gate, mem.last_write_gate
    y_fast = mem.last_y_fast
    # read loss: memory read at position t must predict answer token t+1
    tgt = lbl[:, 1:]
    m = tgt != -100
    read = torch.tensor(0.0, device=device)
    if y_fast is not None and m.any():
        logits = _lm_decode(w, y_fast[:, :-1][m])
        read = F.cross_entropy(logits, tgt[m])

    gen_q = random.choice(["เมืองหลวงของประเทศไทยคือที่ไหน", "น้ำเดือดที่อุณหภูมิกี่องศาเซลเซียส",
                           "ดวงอาทิตย์ขึ้นทางทิศใด", "ภาษาไพทอนนิยมใช้ในงานด้านใด"] + GENERAL_TEXTS_TH)
    gen_in = tok(_chat(tok, gen_q), return_tensors="pt", add_special_tokens=False).input_ids.to(device)
    out_g = w.model(input_ids=gen_in).logits
    g_rg, g_wg = mem.last_gate, mem.last_write_gate
    with torch.no_grad():
        w.bypass_memory = True
        try:
            ref = w.model(input_ids=gen_in).logits
        finally:
            w.bypass_memory = False
    kl = F.kl_div(F.log_softmax(out_g.float(), -1), F.log_softmax(ref.float(), -1), log_target=True, reduction="batchmean")
    # gates: read closed on general knowledge, may open on memory questions; write closed on every question
    gate = (F.binary_cross_entropy(g_rg, torch.zeros_like(g_rg)) + (0.85 - g_r.max()).clamp(min=0.0)
            + 1.5 * F.binary_cross_entropy(g_w, torch.zeros_like(g_w))
            + 1.0 * F.binary_cross_entropy(g_wg, torch.zeros_like(g_wg)))
    total = out_m.loss + lam_read * read + 0.5 * kl + 0.8 * gate
    return total, {"lm": float(out_m.loss), "read": float(read), "kl": float(kl), "g_read": float(g_r.mean()),
                   "g_gen": float(g_rg.mean())}


def run_episode(w: QwenMemoryWrapper, msgs: list[str], qa: list[tuple[str, str]], gap: int, consolidate: bool,
                device: str) -> tuple[torch.Tensor, dict]:
    mem = w.memory
    mem.reset_memory()
    wl = write_messages(w, msgs, device)
    if consolidate:
        mem.consolidate()
    if mem._grad_state is None:  # nothing written (should not happen)
        mem.keep_grad_state = True
    M, S, V, bx, bs = mem._grad_state
    saved = (M * math.exp(-0.05 * gap), S * 0.0 if gap else S, V, bx, bs)
    tot = torch.tensor(0.0, device=device)
    info: dict = {}
    for q, a in qa:
        mem._grad_state = tuple(t.clone() for t in saved)
        l, info = qa_loss(w, q, a, device)
        tot = tot + l
    tot = tot / len(qa)
    if wl:
        tot = tot + 0.8 * sum(wl) / len(wl)
    return tot, info


def life_episode(ds: LifeDataset, rng: random.Random) -> dict:
    """A life-dataset step with a RANDOM persona name (v2 used the persona's fixed name -> memorised)."""
    import re
    active = [p for p in ds.probes if p.recall_label != "forgotten" or p.q_type == "absent"] or ds.probes
    pr = rng.choice(active)
    targets = set(pr.target_events)
    past = [s for s in ds.sessions if s.day <= pr.day] or ds.sessions
    ev = [t.text for s in past for t in s.turns if t.speaker == "self" and targets & set(t.refs)]
    if not ev:
        ev = [e.summary for e in ds.timeline if e.event_id in targets]
    ev.sort(key=lambda s: 0 if re.search(r"วันที่ \d+", s) else 1)
    dis = [t.text for s in past 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]
    rng.shuffle(dis)
    name, occ = make_fact("name", rng), make_fact("occupation", rng)
    msgs = [f"สวัสดีครับ จำไว้ให้ดีนะ {name['say']} {occ['say']}"] + ev[:3] + dis[:2]
    rng.shuffle(msgs)
    qa = [(name["q"], name["a"]), (pr.question, pr.target_answer)]
    if rng.random() < 0.5:
        qa.append((occ["q"], occ["a"]))
    return dict(msgs=msgs, qa=qa, gap=rng.choice([0, 1, 3, 7, 14, 30]), consolidate=True)


# ---------------------------------------------------------------------------- held-out recall check
@torch.no_grad()
def recall_check(w: QwenMemoryWrapper, n: int = 40, seed: int = 12345) -> dict:
    """Generation-based: unseen random entities, told then asked in a NEW chat. Also with memory wiped."""
    from eval_nested import ABSENT_KEYS, _feed
    rng = random.Random(seed)
    mem = w.memory
    mem._grad_state = None
    res = {"A": [0, 0], "B": [0, 0], "nomem": [0, 0], "absent": [0, 0]}
    samples = []
    for i in range(n):
        stage = "A" if i % 2 == 0 else "B"
        ep = make_episode(stage, rng)
        for use in (True, False):
            mem.reset_memory()
            if use:
                for m in ep["msgs"]:
                    _feed(w, m)
                if ep["consolidate"]:
                    w.end_session()
                if ep["gap"]:
                    mem.forget(days=float(ep["gap"]))
            for q, a, val in ep["qa"]:
                ans = w.generate(q, max_new_tokens=32, update_memory=False)
                if val is None:
                    if use:
                        res["absent"][0] += int(any(k in ans for k in ABSENT_KEYS))
                        res["absent"][1] += 1
                    continue
                hit = val in ans
                key = stage if use else "nomem"
                res[key][0] += int(hit)
                res[key][1] += 1
                if use and len(samples) < 6:
                    samples.append({"q": q, "want": val, "got": ans})
    mem.reset_memory()
    out = {k: round(h / max(1, t), 3) for k, (h, t) in res.items()}
    out["samples"] = samples
    return out


# ---------------------------------------------------------------------------- main
def train_v3(variant: str = "v3", data_dir: str = "dataset/generated", ckpt_dir: str = "/vol/checkpoints",
             steps: int = 2400, eval_every: int = 300, lr: float = 1e-3, commit: Callable[[], None] = lambda: None,
             log_path: str | None = None) -> dict:
    ckpt_dir = Path(ckpt_dir)
    ckpt_dir.mkdir(parents=True, exist_ok=True)
    cfg = ProjectConfig(dtype=torch.bfloat16, **V3_VARIANTS[variant])
    w = QwenMemoryWrapper(cfg=cfg, memory_type="nested")
    mem = w.memory
    dev = cfg.device
    rng = random.Random(0)
    random.seed(0)
    lives = [LifeDataset.load_json(f) for f in sorted(Path(data_dir).glob("life_*.json"))]
    lives = [d for d in lives if d.meta.split == "train" and d.sessions and d.probes]
    params = [p for p in mem.parameters() if p.requires_grad]
    opt = torch.optim.AdamW(params, lr=lr, weight_decay=0.01)
    sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: min(1.0, (s + 1) / 100) * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * s / steps))))
    log: dict = {"variant": variant, "options": V3_VARIANTS[variant], "steps": [], "checks": []}
    best = -1.0
    run = {"loss": 0.0, "read": 0.0, "lm": 0.0, "n": 0}
    import time
    t0 = time.time()
    for step in range(1, steps + 1):
        frac = step / steps
        if frac <= 0.25:
            ep = make_episode("A", rng)
        elif frac <= 0.5:
            ep = make_episode("A" if rng.random() < 0.3 else "B", rng)
        else:
            r = rng.random()
            ep = make_episode("A", rng) if r < 0.15 else make_episode("B", rng) if r < 0.5 else life_episode(rng.choice(lives), rng)
        qa = [(q, a) for q, a, *_ in ep["qa"]]
        w.model.train()
        loss, info = run_episode(w, ep["msgs"], qa, ep["gap"], ep["consolidate"], dev)
        opt.zero_grad()
        loss.backward()
        torch.nn.utils.clip_grad_norm_(params, 1.0)
        opt.step()
        sched.step()
        mem._grad_state = None
        run["loss"] += float(loss); run["read"] += info.get("read", 0.0); run["lm"] += info.get("lm", 0.0); run["n"] += 1
        if step % 25 == 0:
            n = run["n"]
            row = {"step": step, "loss": round(run["loss"] / n, 4), "lm": round(run["lm"] / n, 4),
                   "read": round(run["read"] / n, 4), "g_read": round(info.get("g_read", 0), 3),
                   "g_gen": round(info.get("g_gen", 0), 4), "res_scale": round(float(mem.res_scale), 3),
                   "sec": round(time.time() - t0)}
            log["steps"].append(row)
            print(json.dumps(row), flush=True)
            run = {"loss": 0.0, "read": 0.0, "lm": 0.0, "n": 0}
        if step % eval_every == 0 or step == steps:
            w.model.eval()
            chk = recall_check(w)
            chk["step"] = step
            log["checks"].append(chk)
            print("RECALL", json.dumps(chk, ensure_ascii=False), flush=True)
            score = (chk["A"] + chk["B"]) / 2
            mem.reset_memory()
            w.save_unified_model(ckpt_dir / f"unified_nested_L18_{variant}_last.pt")
            if score > best:
                best = score
                w.save_unified_model(ckpt_dir / v3_ckpt_name(variant))
                print(f"  new best {best:.3f} -> {v3_ckpt_name(variant)}", flush=True)
            if log_path:
                Path(log_path).write_text(json.dumps(log, ensure_ascii=False, indent=2), encoding="utf-8")
            commit()
    log["best"] = best
    return log