#!/usr/bin/env -S uv run --script # /// script # requires-python = ">=3.11" # dependencies = [ # "lighteval @ git+https://github.com/LetheanNetwork/lighteval.git@dev", # "mlx-lm ; sys_platform == 'darwin'", # "mlx-vlm ; sys_platform == 'darwin'", # "openai", # "pandas", # "pyarrow", # "ruamel.yaml", # "pyyaml", # ] # /// # SPDX-License-Identifier: EUPL-1.2 """eval.py — LEM-Eval target-driven 8-PAC benchmark runner. Runs a paired 8-PAC benchmark (unmodified base vs LEK-merged model) on a declared task using lighteval via LetheanNetwork's fork (carries benchmark-stability fixes — see https://github.com/LetheanNetwork/lighteval/tree/dev). Appends canonical results to two destinations per run: 1. The target model repo's .eval_results/.parquet (primary, per-model scorecard — drives HF model-card eval_results rendering) 2. LEM-benchmarks (lthn/LEM-benchmarks) results//.parquet (aggregated, fleet-wide — grows as more machines contribute) Target identity comes from targets.yaml in the same directory. A target declares (base, this, task) and which machine owns it. Workers filter by hostname so the same targets.yaml drives the whole fleet. Usage: uv run eval.py --target lemer uv run eval.py --target lemer --n-questions 1 --rounds 8 uv run eval.py --target lemer --loop 10 uv run eval.py --target lemer --samples-start 42 uv run eval.py --list-targets # show all targets uv run eval.py --my-targets # show targets for this host Output layout per run: /.eval_results/.{parquet,yaml,md} /results//.{parquet,yaml,md} Transient (deleted after run): .eval_results/_work/ # lighteval's per-round raw output Reference: https://huggingface.co/datasets/lthn/LEM-Eval (this tool) https://huggingface.co/datasets/lthn/LEM-benchmarks (aggregated results) https://github.com/LetheanNetwork/lighteval (our lighteval fork) """ import argparse import datetime as _dt import glob import json import math import os import re import shutil import sys import time from collections import Counter from pathlib import Path # --- Identity --------------------------------------------------------------- # # THIS_MODEL and BASE_MODEL are populated per-run from targets.yaml. They # stay as module-level globals only so existing log lines in _run_once can # print them — the actual inference path flows through mlx_lm_wrapper.py or # gguf_wrapper.py, which read config.model_name directly. THIS_MODEL = None BASE_MODEL = None DEFAULT_TASK = "mmlu_pro" DEFAULT_ROUNDS = 8 DEFAULT_N_QUESTIONS = 1 SCRIPT_DIR = Path(__file__).resolve().parent TARGETS_YAML_PATH = SCRIPT_DIR / "targets.yaml" def load_targets(): """Load targets.yaml from the script directory.""" import yaml as _yaml if not TARGETS_YAML_PATH.exists(): raise FileNotFoundError( f"targets.yaml not found at {TARGETS_YAML_PATH}. " "This script expects to live next to a targets.yaml describing the fleet." ) return _yaml.safe_load(TARGETS_YAML_PATH.read_text()) def resolve_target(name, cfg=None, type_filter=None): """Look up a target by (name, type) in targets.yaml. Multiple entries can share a name if they have different types — e.g. the same model family evaluated via mlx and via gguf. `type_filter` disambiguates: - None and one match → return the match - None and multiple matches → error, ask for --type - set/iterable and one matching entry → return it - set/iterable and zero/multiple → error """ if cfg is None: cfg = load_targets() candidates = [t for t in cfg.get("targets", []) if t["name"] == name] if not candidates: names = sorted({t["name"] for t in cfg.get("targets", [])}) raise KeyError(f"target {name!r} not in targets.yaml (known names: {names})") if type_filter is not None: allowed = set(type_filter) if not isinstance(type_filter, str) else {type_filter} candidates = [t for t in candidates if t.get("type") in allowed] if not candidates: raise KeyError( f"target {name!r} has no entry matching type filter {type_filter!r}. " f"Use --type to pick one." ) if len(candidates) > 1: types = [t.get("type", "?") for t in candidates] raise KeyError( f"target {name!r} has multiple entries ({types}). Pass --type to disambiguate." ) return candidates[0] # --- Wrapper routing -------------------------------------------------------- # # Lighteval's custom-model loader wants to be pointed at a single file that # defines exactly one LightevalModel subclass. We keep those files separate # (mlx_lm_wrapper.py + gguf_wrapper.py) so eval.py can import cleanly on # machines that don't have every backend (e.g. charon has no mlx_lm). WRAPPERS_BY_TYPE = { "mlx": "mlx_lm_wrapper.py", "gguf": "gguf_wrapper.py", } def wrapper_file_for_type(target_type): wf = WRAPPERS_BY_TYPE.get(target_type) if wf is None: raise KeyError(f"no wrapper registered for type {target_type!r}") return str(SCRIPT_DIR / wf) # --- Paired 8-PAC analysis -------------------------------------------------- def _extract_numeric(text): if not text: return None m = re.search(r"(-?\d+(?:\.\d+)?)", str(text)) return float(m.group(1)) if m else None def _confidence(answers): if not answers: return 0.0 return Counter(answers).most_common(1)[0][1] / len(answers) def _entropy(answers): if not answers: return 0.0 counter = Counter(answers) total = len(answers) probs = [c / total for c in counter.values()] h = -sum(p * math.log2(p) for p in probs if p > 0) h_max = math.log2(total) if total > 1 else 1.0 return h / h_max if h_max > 0 else 0.0 def _sparkline(answers, gold_letter): return "".join(f"[{a}]" if a == gold_letter else f" {a} " for a in answers) def _histogram(answers, total): lines = [] for ans, count in Counter(answers).most_common(): bar = "█" * count + "░" * (total - count) lines.append(f" {ans}: {bar} ({count}/{total})") return "\n".join(lines) def _run_model_rounds(model_name, task, n_questions, rounds, tmp_dir, wrapper_file, samples_start=0): """Run lighteval R times for the same model, return list of parquet paths. samples_start is passed through to lighteval's --samples-start so each invocation window is the same slice of the shuffled test set — callers progress the canon by incrementing samples_start between runs. wrapper_file is the absolute path to the LightevalModel subclass file (mlx_lm_wrapper.py or gguf_wrapper.py). """ import subprocess out_paths = [] short = model_name.replace("/", "_") for r in range(1, rounds + 1): out_dir = os.path.join(tmp_dir, f"round{r}_{short}_s{samples_start}") if not os.path.exists(out_dir): # Clear lighteval cache to force fresh sampling per round cache_dir = os.path.expanduser("~/.cache/huggingface/lighteval") shutil.rmtree(cache_dir, ignore_errors=True) cmd = [ "lighteval", "custom", model_name, wrapper_file, task, "--max-samples", str(n_questions), "--samples-start", str(samples_start), "--save-details", "--output-dir", out_dir, ] print(f" round {r}/{rounds} @ start={samples_start} for {model_name}", flush=True) subprocess.run(cmd, check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) parquets = glob.glob(f"{out_dir}/details/**/*.parquet", recursive=True) if parquets: out_paths.append(parquets[0]) else: out_paths.append(None) return out_paths def analyze_paired(base_parquets, lek_parquets, n_questions, rounds): """Produce summary dict + per-question structure for a paired 8-PAC run. Returns (summary, questions) where questions contains full per-round CoT text in `round_details` so downstream writers can produce parquet + markdown with content included. """ import pandas as pd ref_df = None for p in base_parquets + lek_parquets: if p and os.path.exists(p): ref_df = pd.read_parquet(p) break if ref_df is None: raise RuntimeError("No round parquet files produced") base_dfs = [pd.read_parquet(p) if p else None for p in base_parquets] lek_dfs = [pd.read_parquet(p) if p else None for p in lek_parquets] questions = [] for q_idx in range(len(ref_df)): doc = ref_df.iloc[q_idx]["doc"] gold_idx = doc["gold_index"] gold_letter = chr(ord("A") + gold_idx) query = doc["query"] choice_map = dict(re.findall(r"^([A-Z]):\s*(.+?)$", query, re.MULTILINE)) gold_text = choice_map.get(gold_letter, "") gold_value = _extract_numeric(gold_text) qm = re.search(r"question\.\s*\n+(.*?)(?=\n[A-Z]:)", query, re.DOTALL) qbody = qm.group(1).strip() if qm else query[:200] q_result = { "question_index": q_idx, "gold_letter": gold_letter, "gold_text": gold_text, "gold_numeric": gold_value, "question_body": qbody, "choice_map": choice_map, "models": {}, } for label, dfs in (("base", base_dfs), ("lek", lek_dfs)): answers, hits, texts = [], [], [] for df in dfs: if df is None or q_idx >= len(df): continue resp = df.iloc[q_idx]["model_response"] text = str(list(resp["text"])[0]) matches = re.findall(r"Answer:\s*([A-Z])", text) answers.append(matches[0] if matches else "?") hits.append(int(df.iloc[q_idx]["metric"]["extractive_match"])) texts.append(text) conf = _confidence(answers) ent = _entropy(answers) hit_count = sum(hits) distances = [] for a in answers: av = _extract_numeric(choice_map.get(a, "")) if av is not None and gold_value is not None: distances.append(abs(av - gold_value)) mean_dist = sum(distances) / len(distances) if distances else None majority = Counter(answers).most_common(1)[0][0] if answers else "?" maj_val = _extract_numeric(choice_map.get(majority, "")) maj_dist = abs(maj_val - gold_value) if (maj_val is not None and gold_value is not None) else None q_result["models"][label] = { "rounds": answers, "round_details": [ {"round": i + 1, "answer": a, "hit": h, "full_text": t} for i, (a, h, t) in enumerate(zip(answers, hits, texts)) ], "hit_count": hit_count, "total_rounds": len(answers), "confidence": round(conf, 4), "entropy": round(ent, 4), "majority_answer": majority, "majority_hit": (majority == gold_letter), "majority_distance": round(maj_dist, 4) if maj_dist is not None else None, "mean_distance": round(mean_dist, 4) if mean_dist is not None else None, } questions.append(q_result) # Build report lines = [] lines.append("=" * 78) lines.append(f" LEM-benchmarks 8-PAC eval — {THIS_MODEL}") lines.append(f" n={n_questions} × {rounds} rounds × 2 models = {n_questions * rounds * 2} samples") lines.append(f" base: {BASE_MODEL}") lines.append(f" lek: {THIS_MODEL}") lines.append("=" * 78) for q in questions: lines.append("") lines.append("─" * 78) body = q["question_body"].replace("\n", " ") lines.append(f" Q{q['question_index']}: {body[:100]}{'...' if len(body) > 100 else ''}") lines.append(f" gold = {q['gold_letter']}: {q['gold_text']}") if q["gold_numeric"] is not None: lines.append(f" (numeric: {q['gold_numeric']})") lines.append("─" * 78) for label in ("base", "lek"): m = q["models"][label] lines.append(f"\n [{label}] rounds: {_sparkline(m['rounds'], q['gold_letter'])} hits: {m['hit_count']}/{m['total_rounds']}") lines.append(_histogram(m["rounds"], m["total_rounds"])) bar = "█" * int(m["confidence"] * 10) + "░" * (10 - int(m["confidence"] * 10)) lines.append(f" confidence: {m['confidence']:.2f} {bar}") lines.append(f" entropy: {m['entropy']:.2f}") if m["majority_distance"] is not None: lines.append(f" maj-dist: {m['majority_distance']:.3f}") lines.append("") lines.append("=" * 78) lines.append(" Summary") lines.append("=" * 78) base_total = sum(q["models"]["base"]["hit_count"] for q in questions) lek_total = sum(q["models"]["lek"]["hit_count"] for q in questions) total = n_questions * rounds base_pct = 100 * base_total / total if total else 0 lek_pct = 100 * lek_total / total if total else 0 lines.append(f" base: {base_total}/{total} ({base_pct:.1f}%)") lines.append(f" lek: {lek_total}/{total} ({lek_pct:.1f}%)") lines.append(f" delta: {lek_pct - base_pct:+.1f} pp") report = "\n".join(lines) # The aggregate summary excludes round_details by default (too big for JSON) # but keeps everything else. Full content goes into the parquet output. questions_lite = [] for q in questions: q_lite = {k: v for k, v in q.items() if k != "choice_map"} q_lite["models"] = {} for label, m in q["models"].items(): q_lite["models"][label] = {k: v for k, v in m.items() if k != "round_details"} questions_lite.append(q_lite) summary = { "this_model": THIS_MODEL, "base_model": BASE_MODEL, "task": DEFAULT_TASK, "n_questions": n_questions, "rounds": rounds, "timestamp": int(time.time()), "questions": questions_lite, "totals": { "base_hits": base_total, "lek_hits": lek_total, "total_per_model": total, "base_accuracy_pct": round(base_pct, 2), "lek_accuracy_pct": round(lek_pct, 2), "delta_pp": round(lek_pct - base_pct, 2), }, } return summary, questions, report def build_iter_rows(summary, questions, iter_timestamp, samples_start=0, machine=None): """Flatten analyze_paired output into a list of per-round row dicts. question_index is offset by samples_start so each run's rows land in a disjoint [start, start+n) window — letting the canonical parquet grow contiguously across many incremental runs without collisions. No file I/O — the rows flow directly into append_to_canon. """ import socket if machine is None: machine = socket.gethostname() rows = [] for q in questions: absolute_qi = samples_start + q["question_index"] for label in ("base", "lek"): m = q["models"][label] model_name = summary["base_model"] if label == "base" else summary["this_model"] for rd in m.get("round_details", []): rows.append({ "iter_timestamp": iter_timestamp, "task": summary["task"], "samples_start": int(samples_start), "question_index": int(absolute_qi), "question_body": q["question_body"][:1000], "gold_letter": q["gold_letter"], "gold_text": q["gold_text"], "model_side": label, "model_name": model_name, "machine": machine, "round": int(rd["round"]), "extracted_answer": rd["answer"], "hit": int(rd["hit"]), "text_length": len(rd["full_text"]), "full_text": rd["full_text"], }) return rows # --- Canon append ---------------------------------------------------------- # # The canon is .eval_results/.parquet — a single append-only file that # grows monotonically as each run contributes new rows. No intermediate # staging files: rows from analyze_paired flow directly into this merger, # which reads the existing canon (if any), concatenates, dedupes on # (machine, iter_timestamp, question_index, round, model_side), writes back # the parquet + regenerates the yaml and md views from the merged data. # # Multi-machine contribution (future): each machine's canon is a valid # contribution unit. An aggregator can pull /.eval_results/.parquet # from multiple model repos and merge them with the same logic. def _compute_canon_stats(df): """Aggregate per-model stats from the merged canonical parquet.""" import pandas as pd out = {"n_rows": len(df), "models": {}, "machines": {}, "iter_timestamps": []} if "model_side" not in df.columns: return out if "iter_timestamp" in df.columns: out["iter_timestamps"] = sorted(df["iter_timestamp"].dropna().unique().tolist()) if "machine" in df.columns: out["machines"] = {str(m): int(n) for m, n in df["machine"].value_counts().items()} for side, sub in df.groupby("model_side"): n_samples = len(sub) n_questions = sub["question_index"].nunique() if "question_index" in sub.columns else 0 n_rounds = sub["round"].nunique() if "round" in sub.columns else 0 per_round_acc = (sub["hit"].astype(float).mean() * 100) if "hit" in sub.columns else 0.0 majority_correct = 0 if "question_index" in sub.columns and "hit" in sub.columns: for _, qsub in sub.groupby("question_index"): if qsub["hit"].astype(float).mean() > 0.5: majority_correct += 1 majority_acc = (majority_correct / n_questions * 100) if n_questions else 0.0 model_name = None if "model_name" in sub.columns and len(sub): model_name = str(sub["model_name"].mode().iat[0]) out["models"][str(side)] = { "model_name": model_name, "n_samples": int(n_samples), "n_questions": int(n_questions), "n_rounds": int(n_rounds), "per_round_accuracy_pct": float(round(per_round_acc, 2)), "majority_accuracy_pct": float(round(majority_acc, 2)), "majority_correct": int(majority_correct), } return out def _build_eval_yaml( stats, task, dataset_id="TIGER-Lab/MMLU-Pro", task_id="mmlu_pro", dataset_revision="3373e0b32277875b8db2aa555a333b78a08477ea", ): """Build .eval_results/.yaml entries for HF's new eval system. The new HF schema is one value per (dataset.id, task_id) pair — the metric identity is implicit from the dataset's own eval.yaml (for TIGER-Lab/MMLU-Pro that's the 'choice' scorer producing accuracy). Our 8-PAC pipeline produces three derived numbers (per-round / majority-vote / mean confidence) but only one of them can be the headline. We pick majority-vote accuracy because that's the 8-PAC primary: the number that captures "the model picked the correct answer more often than not across 8 independent rounds". Per-round accuracy and confidence still live in .eval_results/.md for humans and in the parquet for downstream analysis. """ m = stats["models"].get("lek") or stats["models"].get("base") if not m: return [] date = _dt.datetime.now(_dt.timezone.utc).date().isoformat() source_url = f"https://huggingface.co/{THIS_MODEL}/tree/main/.eval_results" notes = ( f"8-PAC merged canon, {m['n_questions']} questions × {m['n_rounds']} rounds " f"= {m['n_samples']} samples across {len(stats['machines']) or 1} machine(s) " f"and {len(stats['iter_timestamps'])} run(s). " f"Paired A/B vs {stats['models'].get('base', {}).get('model_name', '?')} under " f"Google-calibrated sampling (temp=1.0, top_p=0.95, top_k=64), enable_thinking=True. " f"Headline metric: majority-vote accuracy (LEK'd side). " f"Per-round mean accuracy: {m['per_round_accuracy_pct']:.2f}%." ) return [ { "dataset": { "id": dataset_id, "task_id": task_id, "revision": dataset_revision, }, "value": m["majority_accuracy_pct"], "date": date, "source": { "url": source_url, "name": "LEM-benchmarks canonical parquet", "user": "lthn", }, "notes": notes, }, ] def _render_canon_md(stats, task, dataset_id="TIGER-Lab/MMLU-Pro"): lines = [ f"# {dataset_id} / {task} — 8-PAC Canon", "", f"Merged from {len(stats['iter_timestamps'])} run(s) across " f"{len(stats['machines']) or 1} machine(s). Total rows: **{stats['n_rows']}**.", "", "## Machines", "", ] if stats["machines"]: for m, n in stats["machines"].items(): lines.append(f"- `{m}`: {n} rows") else: lines.append("- (no machine tags yet)") lines.extend([ "", "## Scores", "", "| Side | Model | Samples | Questions | Rounds | Per-round acc | Majority acc |", "|---|---|---|---|---|---|---|", ]) for side, m in stats["models"].items(): lines.append( f"| `{side}` | `{m['model_name'] or '?'}` | {m['n_samples']} | " f"{m['n_questions']} | {m['n_rounds']} | " f"{m['per_round_accuracy_pct']:.2f}% | " f"{m['majority_accuracy_pct']:.2f}% ({m['majority_correct']}/{m['n_questions']}) |" ) if "base" in stats["models"] and "lek" in stats["models"]: base = stats["models"]["base"] lek = stats["models"]["lek"] delta_pr = lek["per_round_accuracy_pct"] - base["per_round_accuracy_pct"] delta_mv = lek["majority_accuracy_pct"] - base["majority_accuracy_pct"] lines.extend([ "", "## LEK delta", "", f"- per-round: **{delta_pr:+.2f}pp**", f"- majority-vote: **{delta_mv:+.2f}pp**", ]) lines.extend(["", f"Last updated: {_dt.datetime.now(_dt.timezone.utc).isoformat()}", ""]) return "\n".join(lines) def append_to_canon(task, eval_results_dir, new_rows, target_type=None): """Append new rows to .eval_results/[.].parquet (the canon). When target_type is given, the canon filename is task-and-type-scoped (e.g. mmlu_pro.mlx.parquet, mmlu_pro.gguf.parquet) so runs on the same model family via different inference backends live in disjoint canons and their stats don't conflate. Reads the existing canon (if any), concatenates the new rows, dedupes on the composite key, writes back the parquet, and regenerates the yaml + md views. Returns the merged DataFrame. """ import io import pandas as pd from ruamel.yaml import YAML eval_results_dir = Path(eval_results_dir).resolve() eval_results_dir.mkdir(parents=True, exist_ok=True) stem = f"{task}.{target_type}" if target_type else task canon_path = eval_results_dir / f"{stem}.parquet" new_df = pd.DataFrame(new_rows) frames = [] if canon_path.exists(): existing = pd.read_parquet(canon_path) frames.append(existing) print(f" existing canon: {len(existing)} rows") frames.append(new_df) print(f" + new rows: {len(new_df)}") merged = pd.concat(frames, ignore_index=True) dedup_cols = [ c for c in ("machine", "iter_timestamp", "question_index", "round", "model_side") if c in merged.columns ] if dedup_cols: before = len(merged) merged = merged.drop_duplicates(subset=dedup_cols, keep="last").reset_index(drop=True) dropped = before - len(merged) if dropped: print(f" deduped {dropped} duplicate rows") merged.to_parquet(canon_path, index=False) print(f" wrote {canon_path.name} ({len(merged)} rows total)") # Regenerate yaml + md from merged stats, using the same type-scoped stem stats = _compute_canon_stats(merged) yaml_entries = _build_eval_yaml(stats, task) yaml = YAML() yaml.indent(mapping=2, sequence=4, offset=2) buf = io.StringIO() yaml.dump(yaml_entries, buf) (eval_results_dir / f"{stem}.yaml").write_text(buf.getvalue()) (eval_results_dir / f"{stem}.md").write_text(_render_canon_md(stats, task)) print(f" wrote {stem}.yaml + {stem}.md") return merged # --- Main ------------------------------------------------------------------- def _compute_next_offset(task, eval_results_dir, target_type=None): """Derive the next samples_start offset from the existing canonical parquet. Returns max(canon.question_index) + 1 if the canon exists and has rows, else 0. This lets eval.py progress the task forward automatically — each run picks up where the last one finished without the caller tracking state externally. When target_type is given, reads the type-scoped canon so mlx runs progress independently from gguf runs on the same model family. """ import pandas as pd stem = f"{task}.{target_type}" if target_type else task canon_path = Path(eval_results_dir) / f"{stem}.parquet" if not canon_path.exists(): return 0 try: df = pd.read_parquet(canon_path, columns=["question_index"]) except Exception: return 0 if len(df) == 0: return 0 return int(df["question_index"].max()) + 1 def _run_once( task, n_questions, rounds, samples_start, eval_results_dir, tmp_dir, target_name=None, lem_benchmarks_dir=None, wrapper_file=None, ): """One full paired run: base rounds, lek rounds, analyze, append to canon(s). Writes to up to two canonical destinations: 1. eval_results_dir — primary. This is the target model repo's .eval_results/.parquet (and yaml + md derivatives). 2. lem_benchmarks_dir — optional. If provided, also writes /results//.parquet so the fleet-wide aggregator view in lthn/LEM-benchmarks stays in sync with the same run's rows. Same row data, two locations. No extra inference — the rows are built once and appended to both canons independently (each runs its own dedup against its own existing state). """ print(f"\n{'='*78}") print(f" LEM-Eval 8-PAC run — target: {target_name}") print(f" this model: {THIS_MODEL}") print(f" base model: {BASE_MODEL}") print(f" task: {task}") print(f" n × rounds: {n_questions} × {rounds}") print(f" samples window: [{samples_start}, {samples_start + n_questions})") print(f" primary canon: {eval_results_dir}") if lem_benchmarks_dir: print(f" aggregator: {lem_benchmarks_dir}/results/{target_name}") print(f"{'='*78}\n") print(f" wrapper: {wrapper_file}") print("[1/4] running base model rounds...") base_parquets = _run_model_rounds(BASE_MODEL, task, n_questions, rounds, str(tmp_dir), wrapper_file, samples_start=samples_start) print("[2/4] running lek model rounds...") lek_parquets = _run_model_rounds(THIS_MODEL, task, n_questions, rounds, str(tmp_dir), wrapper_file, samples_start=samples_start) print("[3/4] analyzing...") summary, questions, report = analyze_paired(base_parquets, lek_parquets, n_questions, rounds) print(report) iter_timestamp = _dt.datetime.now().strftime("%Y-%m-%dT%H-%M-%S") rows = build_iter_rows(summary, questions, iter_timestamp, samples_start=samples_start) # Derive target type from the wrapper file path so the canon stem matches. target_type = None if wrapper_file: stem = Path(wrapper_file).stem # mlx_lm_wrapper / gguf_wrapper for t_name, t_file in WRAPPERS_BY_TYPE.items(): if Path(t_file).stem == stem: target_type = t_name break print(f"\n[4/4] appending {len(rows)} rows to canon(s)...") print(" primary (model repo):") append_to_canon(task, eval_results_dir, rows, target_type=target_type) if lem_benchmarks_dir and target_name: agg_dir = lem_benchmarks_dir / "results" / target_name print(f" aggregator (lthn/LEM-benchmarks):") append_to_canon(task, agg_dir, rows, target_type=target_type) # Clean up per-run lighteval scratch — the canons now have everything we need shutil.rmtree(tmp_dir, ignore_errors=True) tmp_dir.mkdir(parents=True, exist_ok=True) print(f"\nWindow delta: {summary['totals']['delta_pp']:+.1f} pp " f"(lek {summary['totals']['lek_accuracy_pct']}% - base {summary['totals']['base_accuracy_pct']}%)") return summary SUPPORTED_TYPES = {"mlx", "gguf"} def detect_default_types(): """Figure out which target types this machine can run by capability probe. Each type is probed independently and added if the dependency is present: mlx : Apple Silicon (Darwin) with mlx_lm importable gguf : any machine with the `openai` client importable (Ollama's endpoint availability is checked at wrapper __init__ time via a lightweight probe request) Workers override with --type or the LEM_TYPES env var. If the probe finds zero types, the caller gets an explicit error from main() asking them to set LEM_TYPES. """ import platform types = set() try: import mlx_lm # noqa: F401 if platform.system() == "Darwin": types.add("mlx") except ImportError: pass try: import openai # noqa: F401 types.add("gguf") except ImportError: pass return types def _print_target_table(targets, highlight_types=None): highlight_types = set(highlight_types or []) print(f"{'name':<18} {'type':<6} {'base':<42} {'this':<24}") print("-" * 94) for t in targets: mark = " *" if (t.get("type") in highlight_types) else "" print(f"{t['name']:<18} {t.get('type', '?'):<6} {t['base']:<42} {t['this']:<24}{mark}") def main(): parser = argparse.ArgumentParser( description="LEM-Eval 8-PAC benchmark runner — target-driven, multi-writer", ) parser.add_argument("--target", help="Target name from targets.yaml") parser.add_argument("--list-targets", action="store_true", help="List all targets and exit") parser.add_argument("--my-targets", action="store_true", help="List targets whose type matches this machine's capabilities and exit") parser.add_argument("--type", default=None, help="Restrict to targets of this type (mlx|gguf). " "Defaults to capability detection (mlx on Apple Silicon).") parser.add_argument("--n-questions", type=int, default=DEFAULT_N_QUESTIONS) parser.add_argument("--rounds", type=int, default=DEFAULT_ROUNDS) parser.add_argument("--task", default=None, help="Override the task from targets.yaml (default: use target's task)") parser.add_argument("--eval-results-dir", default=None, help="Where canonical .eval_results/ tree lives. Defaults to " "./workspaces//.eval_results alongside the LEM-Eval clone.") parser.add_argument("--lem-benchmarks-dir", default=None, help="Local clone of lthn/LEM-benchmarks for fleet-wide aggregation. " "If unset, skip the LEM-benchmarks writer.") parser.add_argument("--tmp-dir", default=None, help="Directory for per-round lighteval scratch (default: /_work)") parser.add_argument("--samples-start", default="auto", help="Zero-based offset into the shuffled test set. " "Pass an integer for an explicit offset or 'auto' (default) " "to derive it from the existing canon.") parser.add_argument("--loop", type=int, default=1, help="Run the eval this many times in sequence, advancing samples_start " "by n_questions between iterations. Default 1 (single run).") args = parser.parse_args() cfg = load_targets() all_targets = cfg.get("targets", []) # Resolve the set of types this invocation accepts. if args.type: if args.type not in SUPPORTED_TYPES: parser.error(f"--type must be one of {sorted(SUPPORTED_TYPES)}, got {args.type!r}") allowed_types = {args.type} elif os.environ.get("LEM_TYPES"): allowed_types = set(os.environ["LEM_TYPES"].split(",")) else: allowed_types = detect_default_types() if not allowed_types: parser.error( "no target types detected on this machine (tried mlx, gguf). " "Install mlx_lm (Apple Silicon) or openai (any), or set LEM_TYPES " "explicitly in the environment." ) if args.list_targets: _print_target_table(all_targets, highlight_types=allowed_types) return 0 if args.my_targets: mine = [t for t in all_targets if t.get("type") in allowed_types] if not mine: print(f"No targets match this machine's types: {sorted(allowed_types)}") return 0 _print_target_table(mine, highlight_types=allowed_types) return 0 if not args.target: parser.error("--target is required (or use --list-targets / --my-targets)") # Let --type / LEM_TYPES / capability detection disambiguate when the # same target name exists with multiple types in targets.yaml. try: target = resolve_target(args.target, cfg, type_filter=allowed_types) except KeyError as e: parser.error(str(e)) target_type = target.get("type") if target_type not in SUPPORTED_TYPES: parser.error(f"target {args.target!r} has unknown type {target_type!r}") try: wrapper_file = wrapper_file_for_type(target_type) except KeyError as e: parser.error(str(e)) # Populate module globals so the lighteval custom-model loader picks # up the right identity when it instantiates MLXLMModel. global THIS_MODEL, BASE_MODEL THIS_MODEL = target["this"] BASE_MODEL = target["base"] task = args.task or target.get("task") or cfg.get("task") or DEFAULT_TASK # Default eval_results_dir: workspaces//.eval_results next to this script. # The worker shell script (lem-eval.sh) can override this to point at a local # clone of the target model repo for a real run. if args.eval_results_dir: eval_results_dir = Path(args.eval_results_dir).resolve() else: eval_results_dir = SCRIPT_DIR / "workspaces" / args.target / ".eval_results" eval_results_dir.mkdir(parents=True, exist_ok=True) tmp_dir = Path(args.tmp_dir or (eval_results_dir / "_work")).resolve() tmp_dir.mkdir(parents=True, exist_ok=True) lem_benchmarks_dir = Path(args.lem_benchmarks_dir).resolve() if args.lem_benchmarks_dir else None if args.samples_start == "auto": samples_start = _compute_next_offset(task, eval_results_dir, target_type=target_type) print(f"[auto] canon progression ({target_type}) → samples_start = {samples_start}", flush=True) else: try: samples_start = int(args.samples_start) except ValueError: print(f"ERROR: --samples-start must be 'auto' or an integer, got {args.samples_start!r}", file=sys.stderr) return 1 total = args.loop for i in range(total): if total > 1: print(f"\n############### loop iteration {i + 1}/{total} ###############") _run_once( task=task, n_questions=args.n_questions, rounds=args.rounds, samples_start=samples_start, eval_results_dir=eval_results_dir, tmp_dir=tmp_dir, target_name=args.target, lem_benchmarks_dir=lem_benchmarks_dir, wrapper_file=wrapper_file, ) samples_start += args.n_questions shutil.rmtree(tmp_dir, ignore_errors=True) return 0 if __name__ == "__main__": sys.exit(main())