Download code/slurm/eval_loss.py from fhyfhy/HRM-Text-checkpoints: direct link, hf CLI and curl.
- Browser
- Download file 7.9 kB
-
https://huggingface.co/fhyfhy/HRM-Text-checkpoints/resolve/main/code/slurm/eval_loss.py
- Command line
-
hf download hf://fhyfhy/HRM-Text-checkpoints/code/slurm/eval_loss.py
-
curl -L -o eval_loss.py https://huggingface.co/fhyfhy/HRM-Text-checkpoints/resolve/main/code/slurm/eval_loss.py
7.9 kB
| """Compute held-out eval loss for every epoch checkpoint of a run, in one | |
| multi-node torchrun session (reuses pretrain.py's model/FSDP/DCP machinery). | |
| For each fsdp2_epoch_N in --ckpt_path (complete ones only), reports loss / | |
| accuracy / exact_accuracy over the eval split, for both raw weights and EMA | |
| weights. Metrics are token-weighted global aggregates across all ranks. | |
| Launch (per node, same pattern as train.sbatch step 2): | |
| torchrun --nnodes=$N --nproc_per_node=8 ... slurm/eval_loss.py \ | |
| --ckpt_path checkpoints/HRM-Text/L-4n-repro \ | |
| --eval_data /lustre/.../hrm_data/eval_split_ep4s0_seed1000 \ | |
| [--global_batch_size 172032] | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| from glob import glob | |
| from pathlib import Path | |
| from types import SimpleNamespace | |
| import torch | |
| import torch.distributed as dist | |
| import yaml | |
| from torch.distributed.fsdp import FSDPModule | |
| sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) | |
| import pretrain as P # noqa: E402 | |
| from models.common import wrap_tensor # noqa: E402 | |
| def reshard_all(model): | |
| """Drop cached unsharded FSDP2 params so the next forward re-gathers. | |
| Training uses reshard_after_forward=False: forward caches unsharded | |
| params and only backward frees them. An eval-only loop never runs | |
| backward, so weight updates (dcp.load / optim.swap_ema) applied to the | |
| SHARDED params would be silently masked by the stale cache without this. | |
| """ | |
| for m in model.modules(): | |
| if isinstance(m, FSDPModule): | |
| m.reshard() | |
| def evaluate(model, carry_init, loader, extra_args, prefix): | |
| model.eval() | |
| agg = {} | |
| carry = carry_init | |
| n_batches = 0 | |
| # Per-cycle channel diagnostics for models that support it (loop_cot) | |
| inner = getattr(model, "model", None) | |
| sink = [] if hasattr(inner, "_stats_sink") else None | |
| if sink is not None: | |
| inner._stats_sink = sink | |
| with torch.no_grad(): | |
| for batch, batch_info in loader: | |
| batch = batch | {k: wrap_tensor(torch.tensor(v, device="cpu")) for k, v in batch_info.items()} | |
| carry, _loss, metrics = model(batch=batch, carry=carry, **extra_args) | |
| for k, (num, den) in metrics.items(): | |
| if k not in agg: | |
| agg[k] = [num.double().clone(), den.double().clone()] | |
| else: | |
| agg[k][0] += num.double() | |
| agg[k][1] += den.double() | |
| n_batches += 1 | |
| # Global reduction (sum numerators and denominators) | |
| keys = sorted(agg.keys()) | |
| flat = torch.stack([agg[k][0] for k in keys] + [agg[k][1] for k in keys]) | |
| dist.all_reduce(flat) | |
| nums, dens = flat.chunk(2) | |
| results = {f"{prefix}{k}": (nums[i] / dens[i]).item() for i, k in enumerate(keys)} | |
| if sink is not None: | |
| inner._stats_sink = None | |
| cycles = sorted({e["cycle"] for e in sink}) | |
| fields = ["z_norm", "alpha_decoded_norm", "beta_x_norm", "alpha_mean", "beta_mean"] | |
| # Rank-local mean per (cycle, field), then average across ranks | |
| local = torch.tensor([[sum(e[f] for e in sink if e["cycle"] == c) / max(1, sum(1 for e in sink if e["cycle"] == c)) | |
| for f in fields] for c in cycles], dtype=torch.float64, device="cuda") | |
| dist.all_reduce(local) | |
| local /= dist.get_world_size() | |
| results[f"{prefix}cot_stats"] = {int(c): {f: round(local[ci][fi].item(), 4) for fi, f in enumerate(fields)} | |
| for ci, c in enumerate(cycles)} | |
| # Per-token alpha histograms: summed over batches, then over ranks. | |
| hist_entries = [e for e in sink if "alpha_hist" in e] | |
| if hist_entries: | |
| nb = len(hist_entries[0]["alpha_hist"]) | |
| hist = torch.zeros(len(cycles), nb, dtype=torch.float64, device="cuda") | |
| for e in hist_entries: | |
| hist[cycles.index(e["cycle"])] += torch.tensor(e["alpha_hist"], dtype=torch.float64, device="cuda") | |
| dist.all_reduce(hist) | |
| results[f"{prefix}alpha_hist"] = {int(c): hist[ci].cpu().tolist() for ci, c in enumerate(cycles)} | |
| return results, n_batches | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--ckpt_path", required=True) | |
| ap.add_argument("--eval_data", required=True) | |
| ap.add_argument("--global_batch_size", type=int, default=172032) | |
| args = ap.parse_args() | |
| dist.init_process_group(backend="nccl") | |
| WORLD_SIZE, RANK = dist.get_world_size(), dist.get_rank() | |
| torch.cuda.set_device(int(os.environ["LOCAL_RANK"])) | |
| # Build config from the run's saved snapshot; point data at the eval split. | |
| with open(os.path.join(args.ckpt_path, "all_config.yaml"), "rt") as f: | |
| run_cfg = yaml.safe_load(f) | |
| run_cfg["data"]["path"] = args.eval_data | |
| run_cfg["global_batch_size"] = args.global_batch_size | |
| run_cfg.update(resume_from=None, resume_epoch=None, resume_continue=False, | |
| resume_step=None, checkpoint_step_interval=None, | |
| weights_only_resume_from_ema=False) | |
| config = P.PretrainConfig(**run_cfg) | |
| assert config.global_batch_size % WORLD_SIZE == 0 | |
| local_batch_size = config.global_batch_size // WORLD_SIZE | |
| loader, metadata = P.create_dataloader(config, local_batch_size, drop_last_batch=False, | |
| rank=RANK, world_size=WORLD_SIZE) | |
| # Discover complete epoch checkpoints | |
| epochs = sorted(int(Path(d).name.split("_")[-1]) for d in glob(os.path.join(args.ckpt_path, "fsdp2_epoch_*")) | |
| if os.path.exists(os.path.join(d, ".metadata"))) | |
| if RANK == 0: | |
| print(f"Evaluating epochs {epochs} of {args.ckpt_path} on {metadata.total_length:,} eval tokens " | |
| f"({WORLD_SIZE} ranks, {local_batch_size} tok/rank)", flush=True) | |
| results = {} | |
| for epoch in epochs: | |
| # Fresh model+optimizer per checkpoint: reusing an optimizer through a | |
| # second get/set_optimizer_state_dict round-trip (after swap_ema) | |
| # corrupts DCP's param mapping (KeyError: 0). | |
| model, carry, optim = P.create_model_and_carry(config, metadata, local_batch_size) | |
| extra_args = model.compute_train_extra_args(SimpleNamespace(step=1 << 30, total_steps=1 << 30)) | |
| cfg_e = config.model_copy(update={"resume_from": args.ckpt_path, "resume_epoch": epoch}) | |
| P.load_checkpoint(cfg_e, P.TrainState(model=model, carry=carry, optim=optim, step=0, total_steps=1), | |
| metadata, RANK) | |
| reshard_all(model) | |
| r_raw, nb = evaluate(model, carry, loader, extra_args, "raw/") | |
| optim.swap_ema() | |
| reshard_all(model) | |
| r_ema, _ = evaluate(model, carry, loader, extra_args, "ema/") | |
| results[epoch] = r_raw | r_ema | |
| del model, carry, optim | |
| torch.cuda.empty_cache() | |
| if RANK == 0: | |
| print(f"[epoch {epoch}] ({nb} local batches) " + | |
| " ".join(f"{k}={v:.4f}" for k, v in sorted(results[epoch].items()) if not isinstance(v, dict)), flush=True) | |
| for k, v in sorted(results[epoch].items()): | |
| if isinstance(v, dict): | |
| print(f"[epoch {epoch}] {k}:", flush=True) | |
| for cyc, st in v.items(): | |
| if isinstance(st, dict): | |
| print(f" cycle {cyc}: " + " ".join(f"{f}={x}" for f, x in st.items()), flush=True) | |
| else: # histogram: report the summed count only | |
| print(f" cycle {cyc}: {len(st)} bins, {sum(st):,.0f} tokens", flush=True) | |
| if RANK == 0: | |
| out_file = os.path.join(args.ckpt_path, "eval_loss.json") | |
| with open(out_file, "wt") as f: | |
| json.dump(results, f, indent=2) | |
| print(f"Saved -> {out_file}\nEVAL_LOSS_DONE", flush=True) | |
| dist.destroy_process_group() | |
| if __name__ == "__main__": | |
| main() | |