File size: 14,091 Bytes
4968ea3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
308
309
310
311
312
313
"""Direct-ask cartridge eval for the trainable-KV length ablation.

Pure "inject cartridge -> ask the user's OWN question -> greedy answer -> judge".
NO retrieval, NO MS/ACT decision pipeline, NO SFT LoRA. This isolates the question
"how much did the trainable-KV cartridge actually memorize?" from the rest of the
MetaMem machinery, so accuracy reflects ONLY the cartridge at a given KV length p.

One (dataset, p) cell per invocation; ALL outputs land under ISOLATED paths keyed by
(dataset, p) — see run_kvlen_cell.sh. Reuses the FIR-probing generation path and the
production gpt-4o-mini LLMJudge so the answer/judge口径 matches the rest of the repo.

Usage:
    python scripts/train/eval_direct_ask.py \
        --dataset       data/processed/longmemeval_s/dataset.json \
        --users-list    data/processed/longmemeval_s/splits/kvlen_sample200_seed42.json \
        --cartridge-dir checkpoints/kvlen/lmes/p256 \
        --output-path   data/eval/kvlen/lmes/p256/preds.jsonl \
        --judge-cache-path data/cache/kvlen/lmes/p256/llm_judge.jsonl \
        --model-path    /mnt/train-gui-agent/zhangzeyu/models/Qwen2.5-7B-Instruct

    # generation only (no API), then judge separately:
    python scripts/train/eval_direct_ask.py ... --no-judge --stage infer
    python scripts/train/eval_direct_ask.py ... --stage eval
"""

import argparse
import json
import os
import sys
from collections import defaultdict

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
os.environ.setdefault("CARTRIDGES_DIR", os.path.join(PROJECT_ROOT, "cartridges-lib"))
os.environ.setdefault("CARTRIDGES_OUTPUT_DIR", os.path.join(PROJECT_ROOT, "checkpoints/cartridge"))

from src.utils import load_json, save_json, set_seed, setup_logger

logger = setup_logger(__name__)

DEFAULT_MODEL_PATH = "/mnt/train-gui-agent/zhangzeyu/models/Qwen2.5-7B-Instruct"
DEFAULT_MAX_NEW_TOKENS = 256


def _r(p):
    return p if os.path.isabs(p) else os.path.join(PROJECT_ROOT, p)


# --------------------------------------------------------------------------------------
# Inference: inject cartridge, greedily answer the user's own questions
# --------------------------------------------------------------------------------------
def _generate_answer(model, tokenizer, cache, query, max_new_tokens):
    """Greedy (temp=0 -> argmax) answer with the cartridge as a CONSTANT KV prefix.

    Mirrors src/data_construction/fir_probing.py::_generate_samples_cartridge but
    single-sample at temperature 0 (deterministic). flex_generate already clears the
    transient per-token KV at the end; we clear again as belt-and-suspenders so no KV
    bleeds across queries.
    """
    import torch
    from cartridges.generation import flex_generate
    from src.data_construction.fir_probing import format_probe_prompt

    prompt = format_probe_prompt(query, tokenizer, mode="answer", enable_thinking=False)
    input_ids = tokenizer.encode(prompt, add_special_tokens=False)
    device = next(model.parameters()).device
    input_ids = torch.tensor(input_ids, device=device)
    seq_ids = torch.zeros_like(input_ids)
    position_ids = torch.arange(len(input_ids), device=device)

    out = flex_generate(
        model=model, tokenizer=tokenizer,
        input_ids=input_ids, seq_ids=seq_ids, position_ids=position_ids,
        cache=cache, max_new_tokens=max_new_tokens, temperature=0.0,  # GREEDY
    )  # Dict[seq_id, List[token_id]]
    cache.clear()
    tok_ids = list(out.values())[0] if out else []
    return tokenizer.decode(tok_ids, skip_special_tokens=True).strip()


def run_inference(cfg):
    import torch
    from transformers import AutoTokenizer
    from cartridges.cache import TrainableCache

    from src.cartridge.model_factory import get_flex_model_cls
    from src.evaluation.metrics.answer_metrics import judge_answer
    from src.utils.cartridge_utils import find_cartridge_path

    dataset = load_json(_r(cfg["dataset"]))
    user_ids = load_json(_r(cfg["users_list"]))
    cartridge_dir = _r(cfg["cartridge_dir"])
    out_path = _r(cfg["output_path"])
    max_new_tokens = cfg.get("max_new_tokens", DEFAULT_MAX_NEW_TOKENS)
    model_path = cfg.get("model_path", DEFAULT_MODEL_PATH)

    user_map = {ud["user_id"]: ud for ud in dataset}
    # Fail loud if the sampled users aren't in this dataset (wrong --dataset path).
    if sum(1 for u in user_ids if u in user_map) == 0:
        raise ValueError(
            f"None of the {len(user_ids)} sampled users exist in {cfg['dataset']}. "
            f"Wrong --dataset? (lmes -> longmemeval_s, metamem5k -> metamem_5k)"
        )

    # Resume: skip query_ids already written.
    done_qids = set()
    if os.path.exists(out_path):
        with open(out_path) as f:
            for line in f:
                line = line.strip()
                if line:
                    try:
                        done_qids.add(json.loads(line)["query_id"])
                    except Exception:
                        pass
        logger.info(f"Resuming: {len(done_qids)} queries already generated")

    # Load model ONCE; swap the cartridge per user.
    # 🔴 device_map={"": 0} forces the WHOLE model onto a single GPU — do NOT use "auto".
    # The eval step runs with ALL 8 GPUs visible (unlike the per-GPU-pinned training
    # steps), so "auto" would shard the 7B across cuda:0..7, and the cartridge attention
    # path isn't model-parallel-safe (rotary cos/sin don't follow each layer's shard ->
    # "tensors on cuda:1 and cuda:6" crash in apply_rotary_pos_emb). A 7B in bf16 (~15GB)
    # fits on one card and serial greedy decode needs no sharding. The cartridge cache is
    # loaded with device="cuda" (current device = GPU 0), so model + cache + inputs all
    # land on the same device. Pin a specific GPU via CUDA_VISIBLE_DEVICES if GPU 0 is busy.
    model_cls = get_flex_model_cls(model_path)
    logger.info(f"Loading {model_cls.__name__} from {model_path} (single GPU)...")
    model = model_cls.from_pretrained(
        model_path, torch_dtype=torch.bfloat16, device_map={"": 0}
    )
    model.eval()
    tokenizer = AutoTokenizer.from_pretrained(model_path)

    os.makedirs(os.path.dirname(out_path), exist_ok=True)
    f = open(out_path, "a", encoding="utf-8")
    n_done = 0
    n_no_cart = 0
    n_stage1_only = 0
    for ui, uid in enumerate(user_ids):
        ud = user_map.get(uid)
        if ud is None:
            logger.warning(f"[{ui+1}/{len(user_ids)}] user {uid} not in dataset, skip")
            continue
        cpath = find_cartridge_path(cartridge_dir, uid)
        if cpath is None:
            n_no_cart += 1
            logger.warning(f"[{ui+1}/{len(user_ids)}] user {uid}: no cartridge, skip")
            continue
        # REFUSE Stage-1-only fallback: with --skip-probing there's no done.flag gate, so
        # find_cartridge_path may silently return the (weaker) ntp_recon_stage1 cartridge.
        # Evaluating that would mix Stage-1-only results into this p-cell's accuracy.
        # Require the Stage-2 CD warmstart cartridge; otherwise treat as "no cartridge".
        if "warmstart" not in os.path.basename(os.path.dirname(cpath)):
            n_stage1_only += 1
            logger.warning(
                f"[{ui+1}/{len(user_ids)}] user {uid}: only Stage-1 cartridge "
                f"({cpath}) — refusing fallback, skip (Stage-2 warmstart missing)"
            )
            continue

        cache = TrainableCache.from_pretrained(cpath, device="cuda").to("cuda")
        for q in ud["queries"]:
            qid = q["id"]
            if qid in done_qids:
                continue
            ans = _generate_answer(model, tokenizer, cache, q["query"], max_new_tokens)
            em, _partial, f1 = judge_answer(ans, q["answer"], [q["answer"]])
            rec = {
                "query_id": qid, "user_id": uid,
                "query_type": q.get("query_type"),
                "oracle_ms": q.get("ms_label"),  # None for metamem_5k; present for lmes
                "act": "DIRECT",                 # required key for downstream aggregators
                "query_text": q["query"], "answer": ans, "gold": q["answer"],
                "answer_em": bool(em), "answer_f1": float(f1),
                "answer_judge": None,            # filled in the judge stage
                "cartridge_path": cpath,
            }
            f.write(json.dumps(rec, ensure_ascii=False) + "\n")
            f.flush()
            n_done += 1
            if n_done % 50 == 0:
                logger.info(f"  generated {n_done} answers (user {ui+1}/{len(user_ids)})")
        # free per-user VRAM before next cartridge
        del cache
        torch.cuda.empty_cache()
    f.close()
    logger.info(
        f"Inference done: {n_done} new answers | {n_no_cart} users w/o cartridge | "
        f"{n_stage1_only} users Stage-1-only (skipped)"
    )
    return out_path


# --------------------------------------------------------------------------------------
# Judge: batched gpt-4o-mini verdicts (correct/partial/wrong)
# --------------------------------------------------------------------------------------
def run_judge(cfg):
    from src.evaluation.metrics.llm_judge import build_judge_from_cfg

    out_path = _r(cfg["output_path"])
    recs = []
    with open(out_path) as fh:
        for line in fh:
            line = line.strip()
            if line:
                recs.append(json.loads(line))

    if not cfg.get("no_judge", False):
        judge = build_judge_from_cfg(
            {"enabled": True, "model": cfg.get("judge_model", "gpt-4o-mini"),
             "cache_path": cfg["judge_cache_path"]},
            PROJECT_ROOT,
        )
        if judge is not None:
            logger.info(f"Judging {len(recs)} answers with {judge.model} (batched)...")
            items = [{"question": r["query_text"], "gold": r["gold"],
                      "answer": r["answer"], "qtype": r.get("query_type") or ""}
                     for r in recs]
            for r, (v, ok) in zip(recs, judge.judge_batch(items)):
                r["answer_judge"] = v if ok else None
            # rewrite jsonl atomically with verdicts filled in
            tmp = out_path + ".tmp"
            with open(tmp, "w", encoding="utf-8") as g:
                for r in recs:
                    g.write(json.dumps(r, ensure_ascii=False) + "\n")
            os.replace(tmp, out_path)

    stats = aggregate_direct(recs)
    stats_path = out_path.replace(".jsonl", ".stats.json")
    save_json(stats, stats_path)
    logger.info(f"Aggregated {len(recs)} records -> {stats_path}")
    print(json.dumps(stats, ensure_ascii=False, indent=2))
    return stats


def aggregate_direct(recs):
    """Bespoke aggregator — only the metrics that MEAN something for direct-ask.

    The stock src/evaluation/eval_metrics.aggregate() emits null/misleading retrieval +
    strategy fields here (every record is act="DIRECT", metamem_5k has no ms_label), so
    we report exactly: n / judge_acc / judge_correct_rate / em / f1, plus the same
    broken out by_query_type. verdict->numeric mapping matches eval_metrics._judge_num.
    """
    def jn(v):
        if isinstance(v, str):
            return {"correct": 1.0, "partial": 0.5, "wrong": 0.0}.get(v)
        if isinstance(v, bool):
            return 1.0 if v else 0.0
        return None

    def mean(xs):
        xs = [x for x in xs if x is not None]
        return round(sum(xs) / len(xs), 4) if xs else None

    jc = [1.0 if r.get("answer_judge") == "correct" else 0.0
          for r in recs if r.get("answer_judge") is not None]
    out = {
        "n": len(recs),
        "n_judged": len(jc),
        "judge_acc": mean([jn(r.get("answer_judge")) for r in recs]),
        "judge_correct_rate": round(sum(jc) / len(jc), 4) if jc else None,
        "em": mean([r["answer_em"] for r in recs]),
        "f1": mean([r["answer_f1"] for r in recs]),
    }
    by = defaultdict(list)
    for r in recs:
        by[r.get("query_type")].append(r)
    out["by_query_type"] = {
        str(qt): {
            "n": len(rs),
            "judge_acc": mean([jn(r.get("answer_judge")) for r in rs]),
            "em": mean([r["answer_em"] for r in rs]),
            "f1": mean([r["answer_f1"] for r in rs]),
        }
        for qt, rs in sorted(by.items(), key=lambda kv: str(kv[0]))
    }
    return out


def main():
    ap = argparse.ArgumentParser(description="Direct-ask cartridge eval (KV-length ablation)")
    ap.add_argument("--dataset", required=True, help="Path to dataset.json")
    ap.add_argument("--users-list", required=True, help="Seeded 200-user split JSON")
    ap.add_argument("--cartridge-dir", required=True, help="ISOLATED cartridge_root for this cell")
    ap.add_argument("--output-path", required=True, help="ISOLATED preds.jsonl for this cell")
    ap.add_argument("--judge-cache-path", required=True, help="ISOLATED judge cache for this cell")
    ap.add_argument("--model-path", default=DEFAULT_MODEL_PATH)
    ap.add_argument("--max-new-tokens", type=int, default=DEFAULT_MAX_NEW_TOKENS)
    ap.add_argument("--judge-model", default="gpt-4o-mini")
    ap.add_argument("--no-judge", action="store_true",
                    help="Skip the LLM judge (no API). EM/F1 + label dist still produced.")
    ap.add_argument("--stage", choices=["infer", "eval", "both"], default="both")
    ap.add_argument("--seed", type=int, default=42)
    args = ap.parse_args()

    set_seed(args.seed)
    cfg = {
        "dataset": args.dataset, "users_list": args.users_list,
        "cartridge_dir": args.cartridge_dir, "output_path": args.output_path,
        "judge_cache_path": args.judge_cache_path, "model_path": args.model_path,
        "max_new_tokens": args.max_new_tokens, "judge_model": args.judge_model,
        "no_judge": args.no_judge,
    }
    if args.stage in ("infer", "both"):
        run_inference(cfg)
    if args.stage in ("eval", "both"):
        run_judge(cfg)


if __name__ == "__main__":
    main()