HRM-Text-checkpoints / code /slurm /eval_bench_multi.py
fhyfhy's picture
Add code, tokenizer and README
23c39b5 verified
Raw History Blame Contribute Delete
7.6 kB
"""Multi-GPU benchmark evaluation: shard prompts across torchrun ranks, each
rank runs a full SimpleEngine on its own GPU, rank 0 merges generations and
computes metrics with the exact upstream scoring code.
Same CLI as evaluation.main (OmegaConf key=value), e.g.:
torchrun --nproc_per_node=8 slurm/eval_bench_multi.py \
ckpt_path=checkpoints/HRM-Text/transformer-L-4n 'run_only=[GSM8k]'
"""
import json
import os
import sys
from collections import defaultdict
from pathlib import Path
import torch
import torch.distributed as dist
from omegaconf import OmegaConf
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from evaluation.main import EvaluationConfig # noqa: E402
from utils.functions import load_model_class # noqa: E402
def _jsonable(o):
if isinstance(o, set):
return sorted(o)
if isinstance(o, dict):
return {k: _jsonable(v) for k, v in o.items()}
if isinstance(o, (list, tuple)):
return [_jsonable(v) for v in o]
return o
def dump_generations(extra: dict, b_name: str, benchmark, prompts: list, generations: list):
"""Write every prompt/generation/ground-truth triple for later inspection.
For benchmarks that expose `_extract_answer` (BBH) the parsed answer and
the correctness flag are recorded too, so a wrong score can be traced to
either the reasoning or the parsing.
"""
ckpt = str(extra.get("ckpt_path", "."))
epoch = extra.get("ckpt_epoch", "latest")
out_dir = os.path.join(ckpt, "generations")
os.makedirs(out_dir, exist_ok=True)
path = os.path.join(out_dir, f"{b_name}_ep{epoch}.jsonl")
gts = getattr(benchmark, "ground_truths", [None] * len(generations))
extractor = getattr(benchmark, "_extract_answer", None)
with open(path, "wt") as f:
for i, (p, g) in enumerate(zip(prompts, generations)):
rec = {"i": i, "prompt": p, "generation": g,
"ground_truth": _jsonable(gts[i] if i < len(gts) else None)}
if extractor is not None:
# Not every benchmark's _extract_answer follows BBH's
# (answer, found_marker) contract — GSM8k returns a bare int.
try:
out = extractor(g)
if isinstance(out, tuple) and len(out) == 2:
answer, found = out
rec["parsed_answer"], rec["found_marker"] = _jsonable(answer), found
accept = rec["ground_truth"].get("accept") if isinstance(rec["ground_truth"], dict) else None
if accept is not None and hasattr(benchmark, "_candidates"):
rec["correct"] = bool(benchmark._candidates(answer) & set(accept))
else:
rec["parsed_answer"] = _jsonable(out)
except Exception as exc: # never let diagnostics kill an eval
rec["parse_error"] = repr(exc)
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
print(f"saved {len(generations)} generations -> {path}", flush=True)
def main():
dist.init_process_group(backend="gloo") # gather_object only; no GPU collectives
RANK, WORLD = dist.get_rank(), dist.get_world_size()
torch.cuda.set_device(int(os.environ.get("LOCAL_RANK", 0)))
# ---- Config: identical to evaluation.main ----
cli_conf = OmegaConf.from_cli()
config_path = cli_conf.pop("config", "evaluation/config/hrm_benchmarking.yaml")
base_conf = OmegaConf.load(config_path)
cfg = EvaluationConfig(**OmegaConf.to_container(OmegaConf.merge(base_conf, cli_conf), resolve=True)) # type: ignore
if RANK == 0:
print(f"Initializing Engine: {cfg.engine} on {WORLD} GPUs...", flush=True)
engine_cls = load_model_class(f"engines@{cfg.engine}", prefix="evaluation.")
# `save_generations` is ours, not an engine argument — pop it before the
# rest of the extras are forwarded to the engine constructor.
extra = dict(cfg.__pydantic_extra__ or {})
save_generations = bool(extra.pop("save_generations", False))
engine = engine_cls(**extra)
# ---- Grouping: identical to evaluation.main ----
grouped_tasks = defaultdict(lambda: {"prompts": [], "benchmarks": []})
for b_cfg in cfg.benchmarks:
b_name = b_cfg.name
if cfg.run_only is not None and b_name not in cfg.run_only:
continue
bench_cls = load_model_class(f"benchmarks@{b_name}", prefix="evaluation.")
benchmark = bench_cls(**(b_cfg.__pydantic_extra__ or {}))
gen_cfg = cfg.generation_config | benchmark.generation_overrides | b_cfg.generation_config
gen_key = json.dumps(gen_cfg, sort_keys=True)
start_idx = len(grouped_tasks[gen_key]["prompts"])
grouped_tasks[gen_key]["prompts"].extend(benchmark.prompts)
end_idx = len(grouped_tasks[gen_key]["prompts"])
grouped_tasks[gen_key]["benchmarks"].append((b_name, benchmark, start_idx, end_idx))
# ---- Generate (sharded) and evaluate per group ----
all_results = {}
for gen_key, task_data in grouped_tasks.items():
gen_cfg = json.loads(gen_key)
prompts = task_data["prompts"]
if RANK == 0:
print("=" * 50 + f"\nGeneration config: {gen_cfg} ({len(prompts)} prompts)", flush=True)
my_idx = list(range(RANK, len(prompts), WORLD))
my_gens = engine.generate([prompts[i] for i in my_idx], **gen_cfg) if my_idx else []
gathered: list = [None] * WORLD
dist.all_gather_object(gathered, (my_idx, my_gens))
if RANK == 0:
generations = [""] * len(prompts)
for idx_list, gen_list in gathered: # type: ignore
for i, g in zip(idx_list, gen_list):
generations[i] = g
for b_name, benchmark, s, e in task_data["benchmarks"]:
res = benchmark.compute_metrics(generations[s:e])
all_results[b_name] = res
if save_generations:
dump_generations(extra, b_name, benchmark, prompts[s:e], generations[s:e])
print(f"--- {b_name} ---", flush=True)
for k, v in res.items():
print(f"{k}{'.' * max(1, 25 - len(k))}: {v:.4f}" if isinstance(v, float) else f"{k}: {v}", flush=True)
if RANK == 0:
extra = cfg.__pydantic_extra__ or {}
ckpt = extra.get("ckpt_path", ".")
# Results are keyed by checkpoint epoch so successive per-epoch evals
# accumulate instead of overwriting each other.
epoch = extra.get("ckpt_epoch")
if epoch is None and os.path.isdir(str(ckpt)):
from glob import glob as _glob
eps = [int(Path(d).name.split("_")[-1]) for d in _glob(os.path.join(str(ckpt), "fsdp2_epoch_*"))]
epoch = max(eps) if eps else "unknown"
out = os.path.join(ckpt, "benchmark_results.json") if os.path.isdir(str(ckpt)) else "benchmark_results.json"
existing = {}
if os.path.exists(out):
with open(out, "rt") as f:
existing = json.load(f)
if any(k in existing for k in ("GSM8k", "MATH", "DROP", "MMLU", "ARC", "HellaSwag", "Winogrande", "BoolQ")):
existing = {"unknown": existing} # migrate legacy flat format
existing.setdefault(str(epoch), {}).update(all_results)
with open(out, "wt") as f:
json.dump(existing, f, indent=2)
print(f"Saved (epoch {epoch}) -> {out}\nBENCH_EVAL_DONE", flush=True)
dist.destroy_process_group()
if __name__ == "__main__":
main()