File size: 6,710 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
"""
OOD memory test for v4: tell/ask sentence patterns NEVER used in training (train_v3.make_fact / train_v4.copy_episode),
plus value types the external report found hard (foreign / odd names, pet names, real Thai names, numbers).
Each item: tell (1 message, new chat) -> optional 3 interference sessions -> ask in a new chat.
Also asked with memory wiped (no-mem baseline). Exact-substring scoring.
"""
from __future__ import annotations

import json
import random
import string

import torch

THAI_NAMES = ["ธนากร", "อนุชิต", "จิราพร", "วรเมธ", "ธีรภัทร", "สุรเชษฐ์", "กมลชนก", "ปวีณา", "ณัฐวุฒิ", "ศิริลักษณ์",
              "พงศกร", "อรอุมา", "ชยพล", "ภัทรวดี", "กิตติศักดิ์", "นภัสสร", "ธนพล", "วิมลรัตน์", "เอกชัย", "สุนิสา"]
FOREIGN = ["Xanthippe", "Zyxqor", "Bartholomew", "Quetzal", "Ingrid", "Oluwaseun", "Siobhan", "Yevgeny", "Kwabena",
           "Mireille", "Thaddeus", "Anneliese", "Ptolemy", "Grzegorz", "Ximena"]
PET_WORDS = ["ข้าวตัง", "มะพร้าว", "ถั่วแดง", "ปลาทู", "ขนมปัง", "ส้มโอ", "ชาเย็น", "บัวลอย", "ทองหยิบ", "ลูกชิ้น"]
PROV = ["แม่ฮ่องสอน", "บึงกาฬ", "อำนาจเจริญ", "นครพนม", "สตูล", "พังงา", "ชัยภูมิ", "หนองบัวลำภู", "อุทัยธานี", "ปราจีนบุรี"]


def rand_odd(rng):
    return "".join(rng.choice(string.ascii_letters) for _ in range(rng.randint(5, 8)))


TYPES = {
    # kind: (value_fn, tell templates, ask templates)
    "name_new_pattern": (lambda r: r.choice(THAI_NAMES),
                         ["เรียกผมว่า {v} ก็ได้นะ", "{v} คือชื่อของผมเอง", "ชื่อที่พ่อแม่ตั้งให้ผมคือ {v}", "ผม {v} ครับ ยินดีที่ได้รู้จัก"],
                         ["คุณควรเรียกผมว่าอะไร", "ผมแนะนำตัวว่าชื่ออะไรนะ", "ชื่อของผมคืออะไรนะ"]),
    "foreign_name": (lambda r: r.choice(FOREIGN),
                     ["เพื่อนต่างชาติของผมชื่อ {v}", "หัวหน้าใหม่ของผมชื่อ {v}", "My new colleague is called {v}"],
                     ["เพื่อนต่างชาติของผมชื่ออะไร", "หัวหน้าใหม่ของผมชื่ออะไร", "What is my new colleague called?"]),
    "odd_string": (rand_odd,
                   ["รหัสเข้าบ้านหลังใหม่คือ {v} อย่าลืมนะ", "ผมตั้งชื่อเกมเซฟว่า {v}"],
                   ["รหัสเข้าบ้านหลังใหม่คืออะไร", "ผมตั้งชื่อเกมเซฟว่าอะไร"]),
    "pet_word": (lambda r: r.choice(PET_WORDS),
                 ["หมาที่บ้านผมชื่อเจ้า{v}", "ผมเพิ่งรับแมวมาเลี้ยง ตั้งชื่อว่า {v}"],
                 ["หมาที่บ้านผมชื่ออะไร", "แมวที่ผมเพิ่งรับมาชื่ออะไร"]),
    "number": (lambda r: str(r.randint(100, 99999)),
               ["บ้านเลขที่ของผมคือ {v}", "เมื่อวานผมวิ่งไป {v} ก้าว"],
               ["บ้านเลขที่ของผมคืออะไร", "เมื่อวานผมวิ่งไปกี่ก้าว"]),
    "province": (lambda r: r.choice(PROV),
                 ["ผมย้ายไปทำงานที่จังหวัด{v}แล้ว", "แฟนผมเป็นคนจังหวัด{v}"],
                 ["ผมย้ายไปทำงานที่จังหวัดไหน", "แฟนผมเป็นคนจังหวัดอะไร"]),
}


def make_items(n_per: int = 100, seed: int = 4242) -> list[dict]:
    rng = random.Random(seed)
    items = []
    for kind, (vf, tells, asks) in TYPES.items():
        for _ in range(n_per):
            i = rng.randrange(len(tells))
            v = vf(rng)
            items.append({"kind": kind, "tell": tells[i].format(v=v), "ask": asks[min(i, len(asks) - 1)], "val": v,
                          "long": rng.random() < 0.5})
    return items


@torch.no_grad()
def run_ood(w, n_per: int = 100) -> dict:
    from train_v4 import Pools, interference_session, live_episode
    rng = random.Random(99)
    P = Pools("test")
    mem = w.memory
    by: dict = {}
    rows = []
    for it in make_items(n_per):
        ep = {"sessions": [{"msgs": [it["tell"]], "gap": 0}], "final_gap": 0}
        if it["long"]:
            ep["sessions"] += [interference_session(P, rng) for _ in range(3)]
        live_episode(w, ep)
        ans = w.generate(it["ask"], max_new_tokens=32, update_memory=False)
        mem.reset_memory()
        ans0 = w.generate(it["ask"], max_new_tokens=32, update_memory=False)
        hit, hit0 = it["val"].lower() in ans.lower(), it["val"].lower() in ans0.lower()
        k = it["kind"] + ("_long" if it["long"] else "")
        for key in (k, it["kind"], "ALL"):
            d = by.setdefault(key, [0, 0, 0])
            d[0] += hit; d[1] += hit0; d[2] += 1
        if len(rows) < 400:
            rows.append({**it, "got": ans[:80], "got_nomem": ans0[:80], "hit": hit})
    summary = {k: {"mem": round(a / t, 3), "nomem": round(b / t, 3), "n": t} for k, (a, b, t) in sorted(by.items())}
    return {"summary": summary, "rows": rows}


def run_ood_eval(variant: str, ckpt: str, n_per: int = 100) -> 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)
    w.model.eval()
    res = run_ood(w, n_per)
    print("OOD", json.dumps(res["summary"], ensure_ascii=False), flush=True)
    return res