"""Eval metric aggregation for MetaMem on LongMemEval-S. Given a list of per-query eval records (one per query), compute: - answer accuracy: EM / F1 / judge, overall + by FIR state (ms_label) + by query_type - retrieval: recall@k / MRR (non-DIRECT only) - strategy: over-retrieval rate, under-retrieval rate, strategy accuracy (vs oracle) - hallucinated-entity rate - cost: avg retrieval calls, retrieved tokens, generated tokens Each record dict is expected to have: query_id, user_id, query_type, oracle_ms (or None), pred_ms, act, answer_em (bool), answer_f1 (float), answer_judge (bool|None), retrieved (list of session_ids), gold_evidence_ids (list), new_rank (int|None), retrieved_tokens, retrieval_calls, gen_tokens, hallucinated (bool) """ from collections import defaultdict from typing import Dict, List, Optional def _mean(xs): xs = [x for x in xs if x is not None] return (sum(xs) / len(xs)) if xs else 0.0 def aggregate(records: List[dict], k: int = 10) -> dict: out: Dict = {} # ---- answer accuracy ---- out["n"] = len(records) out["em"] = _mean([r["answer_em"] for r in records]) out["f1"] = _mean([r["answer_f1"] for r in records]) # answer_judge may be the three-tier verdict string (correct/partial/wrong, new LLMJudge) # or a legacy bool. Map to numeric: correct=1.0, partial=0.5, wrong=0.0, True/False=1/0. def _judge_num(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 judges = [_judge_num(r.get("answer_judge")) for r in records] judges = [j for j in judges if j is not None] out["judge_acc"] = _mean(judges) if judges else None # strict-correct rate (verdict=="correct" only), excludes partial-credit jc = [1.0 if r.get("answer_judge") == "correct" else 0.0 for r in records if r.get("answer_judge") is not None] out["judge_correct_rate"] = round(_mean(jc), 4) if jc else None def grouped(key, valfn): g = defaultdict(list) for r in records: g[r.get(key)].append(valfn(r)) return {str(kk): round(_mean(vv), 4) for kk, vv in g.items()} out["em_by_ms"] = grouped("oracle_ms", lambda r: r["answer_em"]) out["f1_by_ms"] = grouped("oracle_ms", lambda r: r["answer_f1"]) if judges: out["judge_by_ms"] = grouped("oracle_ms", lambda r: _judge_num(r.get("answer_judge")) or 0.0) out["judge_by_qtype"] = grouped("query_type", lambda r: _judge_num(r.get("answer_judge")) or 0.0) out["em_by_qtype"] = grouped("query_type", lambda r: r["answer_em"]) # ---- retrieval recall@k / MRR (non-DIRECT only) ---- non_direct = [r for r in records if r["act"] != "DIRECT"] recalls, rrs = [], [] for r in non_direct: gold = set(r.get("gold_evidence_ids", [])) retrieved = r.get("retrieved", [])[:k] hit = bool(set(retrieved) & gold) recalls.append(1.0 if hit else 0.0) rr = 0.0 for rank, rid in enumerate(retrieved, 1): if rid in gold: rr = 1.0 / rank break rrs.append(rr) out["recall_at_k"] = round(_mean(recalls), 4) if recalls else None out["mrr"] = round(_mean(rrs), 4) if rrs else None out["k"] = k # ---- strategy: over/under-retrieval + strategy accuracy ---- # should_search = oracle != SM (only meaningful when oracle present). On LongMemEval-S # only the FIR-labelled subset has oracle_ms; surface the subset size so these rates # are never misread as a full-500-user metric. with_oracle = [r for r in records if r.get("oracle_ms")] out["n_with_oracle"] = len(with_oracle) out["n_without_oracle"] = out["n"] - len(with_oracle) over, under, correct = [], [], [] for r in with_oracle: should = r["oracle_ms"] != "SM" searched = r["act"] != "DIRECT" over.append(1.0 if (not should and searched) else 0.0) under.append(1.0 if (should and not searched) else 0.0) correct.append(1.0 if (should == searched) else 0.0) out["over_retrieval_rate"] = round(_mean(over), 4) if over else None out["under_retrieval_rate"] = round(_mean(under), 4) if under else None out["strategy_accuracy"] = round(_mean(correct), 4) if correct else None # ---- hallucination (only meaningful for NM/VM non-DIRECT, matching reward) ---- hsubset = [r for r in records if r.get("oracle_ms") in ("NM", "VM") and r.get("act") != "DIRECT"] out["hallucinated_rate"] = round(_mean([1.0 if r.get("hallucinated") else 0.0 for r in hsubset]), 4) if hsubset else None out["hallucinated_subset_n"] = len(hsubset) # ---- cost ---- out["avg_retrieval_calls"] = round(_mean([r.get("retrieval_calls", 0) for r in records]), 3) out["avg_retrieved_tokens"] = round(_mean([r.get("retrieved_tokens", 0) for r in records]), 1) out["avg_gen_tokens"] = round(_mean([r.get("gen_tokens", 0) for r in records]), 1) # ---- action distribution ---- act_counts = defaultdict(int) for r in records: act_counts[r["act"]] += 1 out["action_distribution"] = dict(act_counts) return out