File size: 15,138 Bytes
6118a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Outer-loop training of the NestedMemoryLayer inside Qwen (backend-agnostic: Modal or Colab).

Phase 1 (frozen):  Qwen frozen, only the memory layer (Loop 3 skills) is trained.
Phase 2 (LoRA)  :  optional. LoRA on the MLPs of the layers AFTER the memory layer, so the LLM learns to
                   USE what the memory returns. KL to the ORIGINAL Qwen (LoRA off, memory bypassed) keeps
                   general knowledge. At the end LoRA is merged into the weights -> still ONE plain model file.
"""
from __future__ import annotations

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

import torch
import torch.nn as nn
import torch.nn.functional as F

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

# Memory-layer variants compared in the same training/eval protocol
VARIANTS: dict[str, dict] = {
    "base": {},  # Titans-style: per-token delta rule + momentum, linear M (256), 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,
    },
    # v3 (train_v3.py): shifted keys + residual-relative injection, curriculum with random entities
    "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},
    # v4 wide: same as v3_atlas with the fast associative memory widened 256 -> 512 (2x rows, ~1.7x cells)
    "v3_atlas_wide": {"mem_shift_key": True, "mem_res_rel": True, "mem_poly_dim": 24, "mem_omega_window": 16,
                      "mem_muon": True, "mem_inner_steps": 1, "mem_d_mem": 512},
}
# v4 = same architectures as v3_atlas / v3_atlas_wide, trained by train_v4.py
VARIANTS["v4_atlas"] = VARIANTS["v3_atlas"]
VARIANTS["v4_atlas_wide"] = VARIANTS["v3_atlas_wide"]
VARIANTS["v4_atlas_wideb"] = VARIANTS["v3_atlas_wide"]
# v5: memory at several depths (primary at layer 18 + extra layers), warm-started from v4_atlas
VARIANTS["v5_l10"] = {**VARIANTS["v3_atlas"], "mem_extra_layers": (10,)}
VARIANTS["v5_l6_12"] = {**VARIANTS["v3_atlas"], "mem_extra_layers": (6, 12)}
# phase B runs (same architectures, different training recipes)
for _n in ("v4_atlas_wide_r41", "v4_atlas_wide_lora", "v4_atlas_wide_rec41"):
    VARIANTS[_n] = VARIANTS["v3_atlas_wide"]
VARIANTS["v5_l10_r42"] = VARIANTS["v5_l10"]
VARIANTS["v5_l6_12_r42"] = VARIANTS["v5_l6_12"]

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


def variant_options(variant: str) -> dict:
    """'base_lora' -> options of 'base' (LoRA is merged into weights, architecture unchanged)."""
    return VARIANTS[variant.removesuffix("_lora")]


def ckpt_name(variant: str) -> str:
    if variant.startswith(("v3", "v4", "v5")):
        return f"unified_nested_L18_{variant}_blank.pt"
    if variant == "base":
        return "unified_nested_L18_v2_blank.pt"
    return f"unified_nested_L18_v2_{variant}_blank.pt"


# ---------------------------------------------------------------------------- LoRA
class LoRALinear(nn.Module):
    enabled: bool = True  # class-wide switch: off = exact original Qwen (used for the KL reference)

    def __init__(self, base: nn.Linear, rank: int = 16, alpha: float = 32.0):
        super().__init__()
        self.base = base
        self.scale = alpha / rank
        self.A = nn.Parameter(torch.randn(rank, base.in_features, device=base.weight.device) * (1.0 / rank))
        self.B = nn.Parameter(torch.zeros(base.out_features, rank, device=base.weight.device))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        y = self.base(x)
        if not LoRALinear.enabled:
            return y
        return y + ((x.float() @ self.A.t()) @ self.B.t() * self.scale).to(y.dtype)

    @torch.no_grad()
    def merged(self) -> nn.Linear:
        w = self.base.weight
        w.add_((self.B @ self.A * self.scale).to(w.dtype))
        return self.base


def add_lora(wrapper: QwenMemoryWrapper, rank: int) -> list[LoRALinear]:
    mods = []
    layers = wrapper.model.model.layers
    for i in range(wrapper.hook_layer_idx + 1, len(layers)):
        mlp = layers[i].mlp
        for name in ("gate_proj", "up_proj", "down_proj"):
            lin = getattr(mlp, name, None)
            if isinstance(lin, nn.Linear):
                lm = LoRALinear(lin, rank=rank)
                setattr(mlp, name, lm)
                mods.append(lm)
    return mods


def merge_lora(wrapper: QwenMemoryWrapper) -> None:
    for layer in wrapper.model.model.layers:
        mlp = layer.mlp
        for name in ("gate_proj", "up_proj", "down_proj"):
            lm = getattr(mlp, name, None)
            if isinstance(lm, LoRALinear):
                setattr(mlp, name, lm.merged())


# ---------------------------------------------------------------------------- one training step (one life)
def _chat(tok, text: str) -> str:
    try:
        return tok.apply_chat_template([{"role": "user", "content": text}], tokenize=False,
                                       add_generation_prompt=True, enable_thinking=False)
    except TypeError:
        return text


def life_step(w: QwenMemoryWrapper, ds: LifeDataset, device: str) -> tuple[torch.Tensor, float, float]:
    mem = w.memory
    tok = w.tokenizer
    mem.reset_memory()

    # Pick the probe FIRST so the turns that actually contain its answer get written into memory.
    active = [p for p in ds.probes if p.recall_label != "forgotten" or p.q_type == "absent"] or ds.probes
    pr = random.choice(active)
    targets = set(pr.target_events)
    past = [s for s in ds.sessions if s.day <= pr.day] or ds.sessions
    evidence = [t.text for s in past for t in s.turns if t.speaker == "self" and targets & set(t.refs)]
    if not evidence:
        evidence = [t.text for s in past 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]
    distractors = [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]
    random.shuffle(distractors)

    mem.keep_grad_state = True
    mem.online_update = True
    write_open = []
    p_name = ds.persona.name
    p_occ = random.choice(OCCUPATIONS_TH + [ds.persona.occupation])
    msgs = [f"สวัสดีครับ จำไว้ให้ดีนะ ผมชื่อ{p_name} มีอาชีพเป็น{p_occ}"]
    evidence.sort(key=lambda s: 0 if re.search(r"วันที่ \d+", s) else 1)  # dated fact turns first
    msgs += evidence[:3] + distractors[:2]
    random.shuffle(msgs)
    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))
        if mem.last_write_gate is not None:
            gw = mem.last_write_gate  # open on the user's words, closed on chat-template tags
            tgt = torch.tensor(content, device=gw.device, dtype=gw.dtype).view(1, -1, 1)
            write_open.append(F.binary_cross_entropy(gw, tgt))

    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 = [(name_q, name_a), (pr.question, pr.target_answer)]

    # End of chat: consolidate M -> slots, then time passes (M fades, slots persist)
    mem.consolidate()
    days_gap = random.choice([0, 1, 3, 7, 14, 30, 60])
    M_c, S_c, V_c, bx_c, bs_c = mem._grad_state
    saved = (M_c * math.exp(-0.05 * days_gap), S_c * 0.0 if days_gap else S_c, V_c, bx_c, bs_c)

    loss_sum = torch.tensor(0.0, device=device)
    gm = gg = 0.0
    for i, (q, a) in enumerate(qa):
        mem._grad_state = tuple(t.clone() for t in saved)
        mem_in, mem_lbl = encode_qa(tok, q, a, device)
        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)
        loss, gm, gg = compute_sleep_step_loss(w, mem_in, mem_lbl, gen_in, lam_kl=0.5, lam_gate=0.8)
        loss_sum = loss_sum + (2.5 if i == 0 else 1.0) * loss
    total = loss_sum / 3.5
    if write_open:
        total = total + 0.8 * (sum(write_open) / len(write_open))
    return total, gm, gg


# ---------------------------------------------------------------------------- main entry
def train(
    variant: str,
    data_dir: str | Path,
    ckpt_dir: str | Path,
    epochs: int = 6,
    fresh: bool = True,
    max_lives: int = 0,
    lora_epochs: int = 0,
    lora_rank: int = 16,
    commit: Callable[[], None] = lambda: None,
) -> dict:
    ckpt_dir = Path(ckpt_dir)
    ckpt_dir.mkdir(parents=True, exist_ok=True)
    cfg = ProjectConfig(dtype=torch.bfloat16, **variant_options(variant))
    print(f"Variant={variant} options={variant_options(variant)} epochs={epochs} lora_epochs={lora_epochs}", flush=True)
    w = QwenMemoryWrapper(cfg=cfg, memory_type="nested")
    mem = w.memory
    assert isinstance(mem, NestedMemoryLayer)

    ck1 = ckpt_dir / ckpt_name(variant)
    if fresh:
        print("Fresh start: memory layer randomly initialised", flush=True)
    elif ck1.exists():
        w.model.load_state_dict(torch.load(ck1, map_location=cfg.device), strict=False)
        print(f"Resumed from {ck1}", flush=True)

    files = sorted(Path(data_dir).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]
    log: dict = {"phase1": [], "phase2": []}

    def run_phase(name: str, n_epochs: int, params: list, lr_groups: list[dict], ck: Path) -> None:
        opt = torch.optim.AdamW(lr_groups, weight_decay=0.01)
        w.model.train()
        for epoch in range(1, n_epochs + 1):
            random.shuffle(train_files)
            tot, steps = 0.0, 0
            gm = gg = 0.0
            for fp in train_files:
                ds = LifeDataset.load_json(fp)
                if not ds.sessions or not ds.probes:
                    continue
                loss, gm, gg = life_step(w, ds, cfg.device)
                opt.zero_grad()
                loss.backward()
                torch.nn.utils.clip_grad_norm_(params, 1.0)
                opt.step()
                mem._grad_state = None
                tot += loss.item()
                steps += 1
                if steps % 35 == 0 or max_lives:
                    print(f"  [{name} epoch {epoch:02d} step {steps:03d}/{len(train_files)}] "
                          f"avg_loss={tot/steps:.4f} gate_mem={gm:.3f} gate_gen={gg:.3f}", flush=True)
            avg = tot / max(1, steps)
            log[name].append({"epoch": epoch, "avg_loss": round(avg, 4), "gate_mem": round(gm, 4), "gate_gen": round(gg, 4)})
            print(f"[{name} epoch {epoch:02d}/{n_epochs:02d}] avg_loss={avg:.4f} gate_mem={gm:.3f} gate_gen={gg:.3f}", flush=True)
            if name == "phase1":  # phase-2 checkpoints are written merged at the end
                mem.reset_memory()
                w.save_unified_model(ck)
                commit()

    # ---- Phase 1: Qwen frozen, memory layer only
    if epochs > 0:
        mem_params = [p for p in mem.parameters() if p.requires_grad]
        run_phase("phase1", epochs, mem_params, [{"params": mem_params, "lr": 1e-3}], ck1)

    # ---- Phase 2: unfreeze via LoRA on layers after the memory layer
    if lora_epochs > 0:
        lora_mods = add_lora(w, lora_rank)
        lora_params = [p for m in lora_mods for p in (m.A, m.B)]
        mem_params = [p for p in mem.parameters() if p.requires_grad]
        print(f"Phase 2: LoRA r={lora_rank} on {len(lora_mods)} MLP linears (layers {w.hook_layer_idx + 1}+)", flush=True)
        ck2 = ckpt_dir / ckpt_name(f"{variant}_lora")
        run_phase("phase2", lora_epochs, mem_params + lora_params,
                  [{"params": mem_params, "lr": 1e-4}, {"params": lora_params, "lr": 1e-4}], ck2)
        merge_lora(w)
        mem.reset_memory()
        w.save_unified_model(ck2)
        commit()
        print(f"Phase 2 merged -> {ck2}", flush=True)
    return log