File size: 7,233 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
"""
Conversation test (user request): tell a fact -> chat about OTHER things for several turns (memory keeps writing,
as in real use) -> sometimes ask the fact midway -> ask other things again -> come back to the fact.

Measures
  recall_mid / recall_end : fact recalled midway / at the end (exact substring)
  general_acc             : general-knowledge answers correct WITH the personal memory loaded
  general_acc_base        : same questions on the original Qwen (memory bypassed)  -> damage = base - mem
  leak                    : the remembered value appears in an unrelated answer (memory bleeding into other topics)
Two modes
  newchat : every turn is a NEW chat (no history) -> only the memory layer links the turns
  history : one continuous chat with full history (memory + normal context together)
"""
from __future__ import annotations

import json
import random

import torch

GENERAL = [("เมืองหลวงของญี่ปุ่นคือเมืองอะไร", ["โตเกียว", "Tokyo"]), ("1 ปีมีกี่เดือน", ["12", "สิบสอง"]),
           ("ดาวเคราะห์ที่ใหญ่ที่สุดในระบบสุริยะคืออะไร", ["พฤหัส", "Jupiter"]), ("คำว่าแมวในภาษาอังกฤษคืออะไร", ["cat", "Cat"]),
           ("2 บวก 3 เท่ากับเท่าไหร่", ["5", "ห้า"]), ("ประเทศไทยอยู่ทวีปอะไร", ["เอเชีย", "Asia"]),
           ("น้ำแข็งละลายที่กี่องศาเซลเซียส", ["0", "ศูนย์"]), ("สัปดาห์หนึ่งมีกี่วัน", ["7", "เจ็ด"]),
           ("ดวงอาทิตย์ขึ้นทางทิศไหน", ["ตะวันออก", "East"]), ("เมืองหลวงของฝรั่งเศสคืออะไร", ["ปารีส", "Paris"])]
CHITCHAT = ["แนะนำเพลงฟังสบายๆ ให้หน่อย", "วันนี้เหนื่อยมากเลย ทำไงดี", "ช่วยคิดเมนูมื้อเย็นง่ายๆ ให้หน่อย",
            "เล่าเรื่องตลกสั้นๆ ให้ฟังหน่อย", "สอนทำไข่เจียวให้ฟูๆ หน่อย", "ช่วงนี้ฝนตกบ่อย ควรเตรียมอะไรบ้าง",
            "อยากเริ่มออกกำลังกาย ควรเริ่มยังไงดี", "แนะนำหนังสือน่าอ่านสักเล่ม"]


def facts(rng):
    from eval_v4_ood import TYPES
    kind = rng.choice(list(TYPES))
    vf, tells, asks = TYPES[kind]
    i = rng.randrange(len(tells))
    v = vf(rng)
    return kind, tells[i].format(v=v), asks[min(i, len(asks) - 1)], v


@torch.no_grad()
def chat_turn(w, history: list[dict], user: str, write: bool, max_new_tokens: int = 48) -> str:
    """One turn; history=[] means a new chat. write=True: the memory layer writes this turn (real usage)."""
    tok = w.tokenizer
    msgs = history + [{"role": "user", "content": user}]
    text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, enable_thinking=False)
    ids = tok(text, return_tensors="pt", add_special_tokens=False).input_ids.to(w.cfg.device)
    eos = [tok.eos_token_id, tok.convert_tokens_to_ids("<|im_end|>")]
    w.model.eval()
    w.memory.online_update = bool(write)
    out = w.model.generate(input_ids=ids, max_new_tokens=max_new_tokens, do_sample=False, eos_token_id=eos)
    w.memory.online_update = True
    return tok.decode(out[0, ids.shape[1]:], skip_special_tokens=True).strip()


@torch.no_grad()
def run_chat_return(w, n: int = 40, seed: int = 2024, modes=("newchat", "history")) -> dict:
    rng = random.Random(seed)
    res = {}
    transcripts = []
    for mode in modes:
        st = {"mid": [0, 0], "end": [0, 0], "end_nomem": [0, 0], "gen": [0, 0], "gen_base": [0, 0], "leak": [0, 0]}
        for ep in range(n):
            kind, tell, ask, val = facts(rng)
            w.memory.reset_memory()
            hist: list[dict] = []
            log = []

            def turn(u, write=True):
                h = hist if mode == "history" else []
                a = chat_turn(w, h, u, write)
                if mode == "history":
                    hist.extend([{"role": "user", "content": u}, {"role": "assistant", "content": a}])
                log.append({"user": u, "model": a[:120]})
                return a

            turn(tell)
            if mode == "newchat":
                w.end_session()
            n_other = rng.randint(3, 7)
            mid_at = rng.randrange(1, n_other) if rng.random() < 0.6 else None
            for k in range(n_other):
                if k == mid_at:
                    a = turn(ask, write=False)
                    st["mid"][0] += int(val.lower() in a.lower()); st["mid"][1] += 1
                    continue
                if rng.random() < 0.6:
                    q, keys = rng.choice(GENERAL)
                    a = turn(q)
                    st["gen"][0] += int(any(x.lower() in a.lower() for x in keys)); st["gen"][1] += 1
                    st["leak"][0] += int(val.lower() in a.lower()); st["leak"][1] += 1
                    from train_v4 import original_qwen
                    with original_qwen(w):
                        b = chat_turn(w, [], q, write=False)
                    st["gen_base"][0] += int(any(x.lower() in b.lower() for x in keys)); st["gen_base"][1] += 1
                else:
                    a = turn(rng.choice(CHITCHAT))
                    st["leak"][0] += int(val.lower() in a.lower()); st["leak"][1] += 1
                if mode == "newchat" and rng.random() < 0.5:
                    w.end_session()
                    w.memory.forget(days=float(rng.choice([0, 1, 2])))
            a = turn(ask, write=False)
            st["end"][0] += int(val.lower() in a.lower()); st["end"][1] += 1
            if mode == "newchat":
                w.memory.reset_memory()
                a0 = chat_turn(w, [], ask, write=False)
                st["end_nomem"][0] += int(val.lower() in a0.lower()); st["end_nomem"][1] += 1
            if len(transcripts) < 6 and ep % 7 == 0:
                transcripts.append({"mode": mode, "fact": val, "turns": log})
        res[mode] = {k: {"acc": round(h / t, 3) if t else None, "n": t} for k, (h, t) in st.items()}
        print("CHAT", mode, json.dumps(res[mode]), flush=True)
    res["transcripts"] = transcripts
    return res


def run_chat_eval(variant: str, ckpt: str, n: int = 40) -> dict:
    from config import ProjectConfig
    from Model.qwen_memory import QwenMemoryWrapper
    from train_nested import variant_options
    cfg = ProjectConfig(dtype=torch.bfloat16, **variant_options(variant))
    w = QwenMemoryWrapper(cfg=cfg, memory_type="nested")
    w.model.load_state_dict(torch.load(ckpt, map_location=cfg.device), strict=False)
    return run_chat_return(w, n)