Download code/eval_nested.py from Jommarn/Qwen3.5-0.8B-NestedMemory-v5: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/Jommarn/Qwen3.5-0.8B-NestedMemory-v5/resolve/main/code/eval_nested.py
- Command line
-
hf download hf://Jommarn/Qwen3.5-0.8B-NestedMemory-v5/code/eval_nested.py
-
curl -L -o eval_nested.py https://huggingface.co/Jommarn/Qwen3.5-0.8B-NestedMemory-v5/resolve/main/code/eval_nested.py
10.5 kB
| """ | |
| Life-simulation evaluation for NestedMemoryLayer variants (same protocol for every variant). | |
| Per val/test life: | |
| 1. reset memory | |
| 2. session by session (in day order): Ebbinghaus forget(gap days) -> the persona's own turns are fed | |
| as chat messages (forward pass only, memory writes itself) -> end_session() consolidates M -> slots. | |
| A self-introduction with a random name/occupation is told in the first session. | |
| 3. forget until the last probe day, then ask every probe in a NEW chat (no history), | |
| with update_memory=False so questions cannot write. | |
| 4. the same questions are also asked to the SAME model with memory wiped ("no-memory"), | |
| to measure how much is answerable by guessing. | |
| Metrics: hit rate overall / per q_type / name / occupation / absent ("never told"), | |
| gate_write on question tokens (should be ~0), gate_read on general questions (should be ~0). | |
| """ | |
| from __future__ import annotations | |
| from collections import defaultdict | |
| import random | |
| import torch | |
| from dataset.schema import LifeDataset | |
| from Model.qwen_memory import QwenMemoryWrapper | |
| GENERAL_QUESTIONS = [ | |
| "เมืองหลวงของประเทศไทยคือที่ไหน", | |
| "น้ำเดือดที่อุณหภูมิกี่องศาเซลเซียส", | |
| "ดวงอาทิตย์ขึ้นทางทิศไหน", | |
| ] | |
| EVAL_NAMES = ["ชินจัง", "ธนกฤต", "พิมพ์ลดา", "วรเมธ", "ณัฐชา", "กันตภณ", "ปุณยวีร์", "ภูริ", "ศุภิสรา", "อชิตะ"] | |
| EVAL_OCCS = ["สัตวแพทย์", "นักบิน", "ช่างไม้", "นักข่าว", "เภสัชกร", "ชาวประมง", "นักร้อง", "ทนายความ", "บาริสต้า", "ครู"] | |
| ABSENT_KEYS = ["ไม่เคย", "ไม่ได้เล่า", "ไม่ได้บอก", "ไม่ทราบ", "จำไม่ได้", "ไม่แน่ใจ", "ไม่รู้", "ไม่มีข้อมูล", "ไม่สามารถเข้าถึง", "ไม่ได้ระบุ"] | |
| def _match(pred: str, keys: list[str]) -> bool: | |
| p = pred.lower().strip() | |
| return any(k and k.lower().strip() in p for k in keys) | |
| def _feed(wrapper: QwenMemoryWrapper, text: str) -> None: | |
| """Feed one user chat message through the model (same chat template as inference); memory writes itself.""" | |
| tok = wrapper.tokenizer | |
| try: | |
| chat = tok.apply_chat_template([{"role": "user", "content": text}], tokenize=False, | |
| add_generation_prompt=True, enable_thinking=False) | |
| except TypeError: | |
| chat = text | |
| ids = tok(chat, return_tensors="pt", add_special_tokens=False, truncation=True, | |
| max_length=160).input_ids.to(wrapper.cfg.device) | |
| wrapper.model.eval() | |
| wrapper.memory.online_update = True | |
| wrapper.bypass_memory = False | |
| wrapper.model(input_ids=ids) | |
| def _ask(wrapper: QwenMemoryWrapper, q: str) -> tuple[str, float]: | |
| ans = wrapper.generate(q, max_new_tokens=48, update_memory=False) | |
| gw = wrapper.memory.last_write_gate | |
| return ans, float(gw.mean().item()) if gw is not None else 0.0 | |
| def evaluate_life_sim(wrapper: QwenMemoryWrapper, ds: LifeDataset, seed: int) -> dict: | |
| rng = random.Random(seed) | |
| mem = wrapper.memory | |
| name, occ = rng.choice(EVAL_NAMES), rng.choice(EVAL_OCCS) | |
| probes = [p for p in ds.probes if p.recall_label != "forgotten" or p.q_type == "absent"] | |
| # ---- live the life ---- | |
| mem.reset_memory() | |
| prev_day = None | |
| for i, sess in enumerate(sorted(ds.sessions, key=lambda s: s.day)): | |
| if prev_day is not None and sess.day > prev_day: | |
| mem.forget(days=float(sess.day - prev_day)) | |
| prev_day = sess.day | |
| if i == 0: | |
| _feed(wrapper, f"สวัสดีครับ จำไว้ให้ดีนะ ผมชื่อ{name} มีอาชีพเป็น{occ}") | |
| for t in sess.turns: | |
| if t.speaker == "self": | |
| _feed(wrapper, t.text) | |
| wrapper.end_session() | |
| last_probe_day = max([p.day for p in probes] + [prev_day or 0]) | |
| if prev_day is not None and last_probe_day > prev_day: | |
| mem.forget(days=float(last_probe_day - prev_day)) | |
| state = {k: v.clone() for k, v in mem.state_dict().items() if k in ("M", "S", "slot_values", "expert_strength", "ep_x", "ep_s")} | |
| def run_questions() -> list[dict]: | |
| rows = [] | |
| for p in probes: | |
| ans, gw = _ask(wrapper, p.question) | |
| keys = ABSENT_KEYS if p.q_type == "absent" else (p.acceptable_answers + [p.target_answer]) | |
| rows.append({"kind": p.q_type, "q": p.question, "a": ans, "hit": _match(ans, keys), "gate_write": gw}) | |
| for kind, q, keys in [ | |
| ("name", "ผมชื่ออะไรครับ", [name]), | |
| ("occupation", "ผมทำอาชีพอะไรครับ", [occ]), | |
| ]: | |
| ans, gw = _ask(wrapper, q) | |
| rows.append({"kind": kind, "q": q, "a": ans, "hit": _match(ans, keys), "gate_write": gw}) | |
| return rows | |
| with_mem = run_questions() | |
| gen_read = [] | |
| for q in GENERAL_QUESTIONS: | |
| _ask(wrapper, q) | |
| gen_read.append(float(mem.last_gate.mean().item())) | |
| mem.reset_memory() | |
| no_mem = run_questions() | |
| # restore lived memory (so callers can inspect it) | |
| for k, v in state.items(): | |
| getattr(mem, k).copy_(v) | |
| return {"life_id": ds.meta.life_id, "name": name, "occ": occ, "with_mem": with_mem, | |
| "no_mem": no_mem, "general_gate_read": sum(gen_read) / len(gen_read)} | |
| def evaluate_short(wrapper: QwenMemoryWrapper, ds: LifeDataset, seed: int) -> dict: | |
| """Training-like protocol (diagnostic): per probe, fresh memory <- intro + evidence turns (+2 distractors), | |
| consolidate once, NO time gap, ask immediately. Isolates the memory mechanism from long-life interference.""" | |
| import re as _re | |
| rng = random.Random(seed) | |
| mem = wrapper.memory | |
| probes = [p for p in ds.probes if p.recall_label != "forgotten" or p.q_type == "absent"] | |
| rows_mem, rows_nomem = [], [] | |
| for p in probes: | |
| name, occ = rng.choice(EVAL_NAMES), rng.choice(EVAL_OCCS) | |
| targets = set(p.target_events) | |
| past = [s for s in ds.sessions if s.day <= p.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)] | |
| ev.sort(key=lambda x: 0 if _re.search(r"วันที่ \d+", x) 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) | |
| msgs = [f"สวัสดีครับ จำไว้ให้ดีนะ ผมชื่อ{name} มีอาชีพเป็น{occ}"] + ev[:3] + dis[:2] | |
| rng.shuffle(msgs) | |
| keys = ABSENT_KEYS if p.q_type == "absent" else (p.acceptable_answers + [p.target_answer]) | |
| for rows, use_mem in ((rows_mem, True), (rows_nomem, False)): | |
| mem.reset_memory() | |
| if use_mem: | |
| for m in msgs: | |
| _feed(wrapper, m) | |
| wrapper.end_session() | |
| for kind, q, k in [(p.q_type, p.question, keys), ("name", "ผมชื่ออะไรครับ", [name]), | |
| ("occupation", "ผมทำอาชีพอะไรครับ", [occ])]: | |
| ans, gw = _ask(wrapper, q) | |
| rows.append({"kind": kind, "q": q, "a": ans, "hit": _match(ans, k), "gate_write": gw}) | |
| mem.reset_memory() | |
| gen_read = [] | |
| for q in GENERAL_QUESTIONS: | |
| _ask(wrapper, q) | |
| gen_read.append(float(mem.last_gate.mean().item())) | |
| return {"life_id": ds.meta.life_id, "with_mem": rows_mem, "no_mem": rows_nomem, | |
| "general_gate_read": sum(gen_read) / len(gen_read)} | |
| def summarize(lives: list[dict]) -> dict: | |
| out: dict = {} | |
| for mode in ("with_mem", "no_mem"): | |
| by = defaultdict(lambda: [0, 0]) | |
| gw = [] | |
| for life in lives: | |
| for r in life[mode]: | |
| by[r["kind"]][0] += int(r["hit"]) | |
| by[r["kind"]][1] += 1 | |
| by["ALL"][0] += int(r["hit"]) | |
| by["ALL"][1] += 1 | |
| gw.append(r["gate_write"]) | |
| out[mode] = {k: {"hit": h, "total": t, "acc": round(h / max(1, t), 4)} for k, (h, t) in sorted(by.items())} | |
| out[mode]["question_gate_write_mean"] = round(sum(gw) / max(1, len(gw)), 4) | |
| out["general_gate_read_mean"] = round(sum(l["general_gate_read"] for l in lives) / max(1, len(lives)), 4) | |
| return out | |
| def run_eval(variant: str, ckpt_dir: str, data_dir: str = "dataset/generated", splits: str = "val,test", | |
| protocol: str = "life", max_lives: int = 0) -> dict: | |
| """Load a variant checkpoint and run the life-simulation eval on the given splits (any backend).""" | |
| from pathlib import Path | |
| from config import ProjectConfig | |
| from train_nested import ckpt_name, variant_options | |
| cfg = ProjectConfig(dtype=torch.bfloat16, **variant_options(variant)) | |
| w = QwenMemoryWrapper(cfg=cfg, memory_type="nested") | |
| ck = Path(ckpt_dir) / ckpt_name(variant) | |
| w.model.load_state_dict(torch.load(ck, map_location=cfg.device), strict=False) | |
| print(f"[eval {variant}] loaded {ck}", flush=True) | |
| want = set(splits.split(",")) | |
| lives = [] | |
| for i, f in enumerate(sorted(Path(data_dir).glob("life_*.json"))): | |
| ds = LifeDataset.load_json(f) | |
| if ds.meta.split not in want: | |
| continue | |
| if max_lives and len(lives) >= max_lives: | |
| break | |
| res = (evaluate_short if protocol == "short" else evaluate_life_sim)(w, ds, seed=i) | |
| lives.append(res) | |
| print(f"[eval {variant}/{protocol}] {ds.meta.life_id} with_mem={sum(r['hit'] for r in res['with_mem'])}/{len(res['with_mem'])} " | |
| f"no_mem={sum(r['hit'] for r in res['no_mem'])}/{len(res['no_mem'])}", flush=True) | |
| del w | |
| torch.cuda.empty_cache() | |
| return {"variant": variant, "protocol": protocol, "options": variant_options(variant), "summary": summarize(lives), "lives": lives} | |