File size: 14,443 Bytes
6118a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97277de
6118a66
 
 
 
 
 
 
 
 
97277de
6118a66
 
 
 
 
 
 
 
97277de
 
 
 
6118a66
97277de
6118a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97277de
6118a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97277de
6118a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97277de
 
 
 
 
 
 
 
 
6118a66
 
 
 
 
 
 
 
 
 
 
 
97277de
 
6118a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97277de
 
 
 
 
 
 
6118a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97277de
6118a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97277de
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
295
296
297
298
299
300
301
302
303
304
305
306
307
"""
Phase D: GRPO for the memory model (see RL_PLAN.md).

One step = one scenario: tell facts (with autograd through the memory writes) -> one prompt (memory / never-told /
general / small talk) -> sample G answers from the same memory state -> programmatic rewards -> group-relative
advantages -> policy-gradient loss (+ KL to the ORIGINAL Qwen on general / small-talk prompts).
"""
from __future__ import annotations

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

import torch
import torch.nn.functional as F

from config import ProjectConfig
from Model.qwen_memory import QwenMemoryWrapper
from train_nested import _chat, variant_options
from train_v3 import NEVER_TOLD, make_fact
from train_v4 import (GEN_PROMPTS_TH, Pools, _fade, add_lora_all, chat_check, copy_episode, heldout_check,
                      interference_session, load_resized, original_qwen, save_model, score, write_messages_rec)

ABSENT = ["ไม่เคย", "ไม่ได้บอก", "ไม่ได้เล่า", "ไม่ทราบ", "ไม่มีข้อมูล", "never told", "haven't told"]
# training-only general questions with answer keys (the chat-return eval uses different ones)
RL_GENERAL = [("เมืองหลวงของอังกฤษคืออะไร", ["ลอนดอน", "London"]), ("10 คูณ 10 ได้เท่าไหร่", ["100", "ร้อย"]),
              ("ดาวเคราะห์ที่ใกล้ดวงอาทิตย์ที่สุดคืออะไร", ["พุธ", "Mercury"]), ("หนึ่งวันมีกี่ชั่วโมง", ["24", "ยี่สิบสี่"]),
              ("สีของใบไม้ส่วนใหญ่คือสีอะไร", ["เขียว", "green"]), ("คำว่าหมาในภาษาอังกฤษคืออะไร", ["dog", "Dog"]),
              ("ประเทศญี่ปุ่นอยู่ทวีปอะไร", ["เอเชีย", "Asia"]), ("น้ำมีสูตรเคมีว่าอะไร", ["H2O", "H₂O"]),
              ("แมงมุมมีกี่ขา", ["8", "แปด"]), ("เมืองหลวงของเกาหลีใต้คืออะไร", ["โซล", "Seoul"]),
              ("ภาษาราชการของบราซิลคือภาษาอะไร", ["โปรตุเกส", "Portuguese"]), ("หนึ่งชั่วโมงมีกี่นาที", ["60", "หกสิบ"])]
SMALLTALK = [p for p in GEN_PROMPTS_TH if any(k in p for k in ("สวัสดี", "ขอบคุณ", "เบื่อ", "ตื่นเต้น", "แนะนำ", "ช่วย", "เล่า"))]


# ---------------------------------------------------------------------------- scenario
def scenario(P: Pools, rng: random.Random) -> dict:
    told, told_kinds = [], set()
    if rng.random() < 0.5:
        ep = copy_episode(rng)
        msgs = ep["sessions"][0]["msgs"]
        told = [(q, v) for q, a, v in ep["qa"] if v]
    else:
        kinds = rng.sample(["name", "occupation", "hometown", "pet", "food", "age", "color", "friend"], rng.randint(1, 3))
        facts = [make_fact(k, rng) for k in kinds]
        msgs = [f["say"] for f in facts]
        told = [(f["q"], f["val"]) for f in facts]
        told_kinds = set(kinds)
    sessions = [{"msgs": msgs, "gap": 0}]
    for _ in range(rng.choice([0, 0, 1, 2, 3])):
        sessions.append(interference_session(P, rng))
    r = rng.random()
    vals = [v for _, v in told]
    if r < 0.40 and told:
        q, v = rng.choice(told)
        kind, keys = "memory", [v]
    elif r < 0.70:
        # never-told question: ONLY about a kind of fact that was not told (any phrasing of a told kind = memory)
        free = [k for k in ["name", "occupation", "hometown", "pet", "food", "age", "color", "friend"] if k not in told_kinds]
        f = make_fact(rng.choice(free), rng)
        q, kind, keys = f["q"], "absent", []
    elif r < 0.85:
        q, keys = rng.choice(RL_GENERAL)
        kind = "general"
    else:
        q, kind, keys = rng.choice(SMALLTALK), "smalltalk", []
    return {"sessions": sessions, "final_gap": rng.choice([0, 1, 3]), "q": q, "kind": kind, "keys": keys, "vals": vals}


def repetitive(t: str) -> bool:
    if re.search(r"(.)\1{5,}", t):
        return True
    toks = t.split() if " " in t else [t[i:i + 3] for i in range(0, len(t), 3)]
    grams = [tuple(toks[i:i + 3]) for i in range(len(toks) - 2)]
    return any(grams.count(g) >= 3 for g in set(grams))


def reward(sc: dict, ans: str, n_tok: int) -> float:
    a = ans.lower()
    absent = any(k.lower() in a for k in ABSENT)
    leak = any(v and v.lower() in a for v in sc["vals"])
    r = 0.0
    if sc["kind"] == "memory":
        v = sc["keys"][0].lower()
        if v in a:
            r = 1.0
        elif len(v) >= 4 and v[: max(2, len(v) // 2)] in a:
            r = 0.3
        elif absent:
            r = -0.3
        if n_tok > 40:
            r -= 0.2
    elif sc["kind"] == "absent":
        r = 1.0 if absent and not leak else -1.0
    elif sc["kind"] == "general":
        r = 1.0 if any(k.lower() in a for k in sc["keys"]) else 0.0
        if leak:
            r -= 1.0
    else:  # small talk
        r = -1.0 if (absent or leak) else 0.0
    if repetitive(ans):
        r -= 0.5
    return r


# ---------------------------------------------------------------------------- one GRPO step
def tell_with_grad(w: QwenMemoryWrapper, sc: dict, dev: str) -> list:
    mems = w.mems
    w.memory.reset_memory()
    for i, s in enumerate(sc["sessions"]):
        if i > 0:
            _fade(w, s["gap"])
        write_messages_rec(w, s["msgs"], dev, None)
        w.memory.consolidate()
    _fade(w, sc["final_gap"])
    return [m._grad_state for m in mems]


@torch.no_grad()
def sample_group(w: QwenMemoryWrapper, saved: list, prompt_ids: torch.Tensor, G: int, max_new: int = 48):
    tok = w.tokenizer
    for m, st in zip(w.mems, saved):   # read-only copy of the told state into the buffers
        M, S, V, bx, bs = st
        m.M.copy_(M[0].detach()); m.S.copy_(S[0].detach()); m.slot_values.copy_(V.detach())
        m.ep_x.copy_(bx.detach()); m.ep_s.copy_(bs.detach())
    w.memory.online_update = False
    w.model.eval()
    eos = [tok.eos_token_id, tok.convert_tokens_to_ids("<|im_end|>")]
    out = w.model.generate(input_ids=prompt_ids.repeat(G, 1), do_sample=True, temperature=0.8, top_p=0.95,
                           max_new_tokens=max_new, eos_token_id=eos, pad_token_id=tok.pad_token_id or eos[0])
    w.memory.online_update = True
    comps = []
    for row in out[:, prompt_ids.shape[1]:].tolist():
        ids = []
        for t in row:
            ids.append(t)
            if t in eos:
                break
        comps.append(ids)
    return comps


def seq_logprobs(w: QwenMemoryWrapper, prompt_ids: torch.Tensor, comps: list, states: list | None, ref: bool = False):
    """Mean log-prob of each completion (teacher forcing), batched; memory state expanded to the batch."""
    tok = w.tokenizer
    pad = tok.pad_token_id or tok.eos_token_id
    P = prompt_ids.shape[1]
    L = max(len(c) for c in comps)
    ids = torch.full((len(comps), P + L), pad, device=prompt_ids.device)
    mask = torch.zeros_like(ids)
    for i, c in enumerate(comps):
        ids[i, :P] = prompt_ids[0]
        ids[i, P:P + len(c)] = torch.tensor(c, device=ids.device)
        mask[i, :P + len(c)] = 1
    if states is not None:
        for m, st in zip(w.mems, states):
            M, S, V, bx, bs = st
            m.__dict__["_grad_state"] = (M.expand(len(comps), -1, -1), S.expand(len(comps), -1, -1), V, bx, bs)
    w.memory.online_update = False
    if ref:
        with torch.no_grad(), original_qwen(w):
            logits = w.model(input_ids=ids, attention_mask=mask).logits
    else:
        logits = w.model(input_ids=ids, attention_mask=mask).logits
    w.memory.online_update = True
    lp = torch.log_softmax(logits[:, P - 1:-1].float(), -1).gather(-1, ids[:, P:].unsqueeze(-1)).squeeze(-1)
    m = mask[:, P:].float()
    return lp, m


def grpo_step(w: QwenMemoryWrapper, P: Pools, rng: random.Random, dev: str, G: int = 8, beta: float = 0.05,
              rep_pen: float = 0.5, ref_w: QwenMemoryWrapper | None = None, beta_ref: float = 0.0):
    sc = scenario(P, rng)
    w.model.train()
    saved = tell_with_grad(w, sc, dev)
    tok = w.tokenizer
    prompt_ids = tok(_chat(tok, sc["q"]), return_tensors="pt", add_special_tokens=False).input_ids.to(dev)
    comps = sample_group(w, saved, prompt_ids, G)
    texts = [tok.decode(c, skip_special_tokens=True) for c in comps]
    rs = torch.tensor([reward(sc, t, len(c)) - (rep_pen - 0.5) * repetitive(t) for t, c in zip(texts, comps)],
                      device=dev)
    info = {"kind": sc["kind"], "r_mean": float(rs.mean()), "sample": texts[0][:60]}
    if float(rs.std()) < 1e-6:
        return None, info
    adv = (rs - rs.mean()) / (rs.std() + 1e-4)
    w.model.train()
    lp, m = seq_logprobs(w, prompt_ids, comps, saved)
    tok_lp = (lp * m).sum(-1) / m.sum(-1).clamp(min=1)
    loss = -(adv * tok_lp).mean()
    if ref_w is not None and beta_ref > 0:   # anchor EVERY prompt to the starting checkpoint (same told memory)
        from train_v4 import live_episode
        with torch.no_grad():
            live_episode(ref_w, sc)
            lp_v5, _ = seq_logprobs(ref_w, prompt_ids, comps, None)
        d5 = (lp_v5 - lp).clamp(-10, 10)
        kl5 = ((d5.exp() - d5 - 1) * m).sum() / m.sum().clamp(min=1)
        loss = loss + beta_ref * kl5
        info["kl_ref"] = float(kl5)
    if sc["kind"] in ("general", "smalltalk") and beta > 0:   # anchor normal chat to the original Qwen
        lp_ref, _ = seq_logprobs(w, prompt_ids, comps, None, ref=True)
        d = (lp_ref - lp).clamp(-10, 10)
        kl = ((d.exp() - d - 1) * m).sum() / m.sum().clamp(min=1)
        loss = loss + beta * kl
        info["kl"] = float(kl)
    return loss, info


# ---------------------------------------------------------------------------- main
def grpo_train(variant: str, init_ckpt: str, out_dir: str, steps: int = 1500, eval_every: int = 250, G: int = 8,
               beta: float = 0.05, rep_pen: float = 0.5, lr: float = 5e-5, lora_rank: int = 0, lora_lr: float = 1e-5,
               tag: str = "", log_path: str | None = None, commit: Callable[[], None] = lambda: None,
               beta_ref: float = 0.0) -> dict:
    out = Path(out_dir)
    out.mkdir(parents=True, exist_ok=True)
    cfg = ProjectConfig(dtype=torch.bfloat16, **variant_options(variant))
    w = QwenMemoryWrapper(cfg=cfg, memory_type="nested")
    load_resized(w, init_ckpt)
    tok = w.tokenizer
    if tok.pad_token is None:
        tok.pad_token = tok.eos_token
    dev = cfg.device
    params = [p for m in w.mems for p in m.parameters() if p.requires_grad]
    groups = [{"params": params, "lr": lr}]
    if lora_rank > 0:
        mods = add_lora_all(w, lora_rank, w.hook_layer_idx + 1)
        lp = [p for m in mods for p in (m.A, m.B)]
        groups.append({"params": lp, "lr": lora_lr})
        params = params + lp
    opt = torch.optim.AdamW(groups, weight_decay=0.0)
    ref_w = None
    if beta_ref > 0:   # frozen copy of the starting checkpoint
        ref_w = QwenMemoryWrapper(cfg=cfg, memory_type="nested")
        load_resized(ref_w, init_ckpt)
        ref_w.model.eval()
        for p_ in ref_w.model.parameters():
            p_.requires_grad = False
    rng = random.Random(7)
    P, Pt = Pools("train"), Pools("test")
    name = f"{variant}_rl{tag}"
    log = {"variant": name, "init": init_ckpt, "beta": beta, "G": G, "steps": [], "checks": []}

    def check(step):
        w.model.eval()
        c = heldout_check(w, Pt)
        c.update(chat_check(w))
        # never-told accuracy on 30 fresh scenarios (greedy)
        r2 = random.Random(1000 + step)
        hit = tot = 0
        for _ in range(30):
            sc = scenario(Pt, r2)
            if sc["kind"] != "absent":
                continue
            with torch.no_grad():
                from train_v4 import live_episode
                live_episode(w, sc)
                a = w.generate(sc["q"], max_new_tokens=32, update_memory=False)
            hit += int(reward(sc, a, 0) > 0); tot += 1
        c["absent_acc"] = round(hit / max(1, tot), 3)
        c["step"] = step
        c["score"] = round(score(c) + 0.1 * c["absent_acc"], 4)
        w.memory.reset_memory()
        return c

    c0 = check(0)
    log["checks"].append(c0)
    print("CHECK", json.dumps({k: v for k, v in c0.items() if k != "samples"}), flush=True)
    best = c0["score"]
    run = {"r": 0.0, "n": 0, "skip": 0}
    t0 = time.time()
    for step in range(1, steps + 1):
        try:
            loss, info = grpo_step(w, P, rng, dev, G=G, beta=beta, rep_pen=rep_pen, ref_w=ref_w, beta_ref=beta_ref)
        except torch.cuda.OutOfMemoryError:
            opt.zero_grad(); w.memory._grad_state = None; torch.cuda.empty_cache(); print("OOM skip", flush=True)
            continue
        run["r"] += info["r_mean"]; run["n"] += 1
        if loss is None:
            run["skip"] += 1
        else:
            opt.zero_grad()
            loss.backward()
            torch.nn.utils.clip_grad_norm_(params, 1.0)
            opt.step()
        w.memory._grad_state = None
        if step % 25 == 0:
            row = {"step": step, "reward": round(run["r"] / run["n"], 3), "skipped": run["skip"], "sec": round(time.time() - t0)}
            log["steps"].append(row)
            print(json.dumps(row), flush=True)
            run = {"r": 0.0, "n": 0, "skip": 0}
        if step % eval_every == 0 or step == steps:
            c = check(step)
            log["checks"].append(c)
            print("CHECK", json.dumps({k: v for k, v in c.items() if k != "samples"}), flush=True)
            if c["score"] > best:
                best = c["score"]
                save_model(w, out / f"unified_nested_L18_{name}_blank.pt")
                print(f"  new best {best:.3f}", flush=True)
            if log_path:
                Path(log_path).parent.mkdir(parents=True, exist_ok=True)
                Path(log_path).write_text(json.dumps(log, ensure_ascii=False, indent=2), encoding="utf-8")
            commit()
    log["best"] = best
    return log