Download eval_local.py from athena2634/albedo-mining-scripts: direct link, hf CLI and curl.
- Browser
- Download file 7.39 kB
-
https://huggingface.co/datasets/athena2634/albedo-mining-scripts/resolve/main/eval_local.py
- Command line
-
hf download hf://datasets/athena2634/albedo-mining-scripts/eval_local.py
-
curl -L -o eval_local.py https://huggingface.co/datasets/athena2634/albedo-mining-scripts/resolve/main/eval_local.py
7.39 kB
| #!/usr/bin/env python3 | |
| """Local holdout eval: teacher-forced loss on reference assistant turns. | |
| This is not the on-chain 100-sample duel. It answers: did the adapter get | |
| closer to the SOTA reference on samples neither king nor challenger solved? | |
| Compare king-only vs SFT vs DPO. Submit only if holdout NLL drops a lot | |
| (recipe: treat < 5% relative drop as noise). | |
| Usage: | |
| python eval_local.py --model models/king118 --data datasets/mix/holdout_sft.jsonl \\ | |
| --out runs/eval-king.json | |
| python eval_local.py --model models/king118 --adapter runs/sft-on-king118 \\ | |
| --data datasets/mix/holdout_sft.jsonl --out runs/eval-sft.json --compare runs/eval-king.json | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| def load_jsonl(path: Path) -> list[dict]: | |
| return [json.loads(line) for line in path.read_text().splitlines() if line.strip()] | |
| def load_model(model_path: str, adapter: str | None, attn: str): | |
| tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True, use_fast=True) | |
| if tokenizer.pad_token is None: | |
| tokenizer.pad_token = tokenizer.eos_token | |
| model = AutoModelForCausalLM.from_pretrained( | |
| model_path, | |
| trust_remote_code=True, | |
| torch_dtype=torch.bfloat16, | |
| device_map="auto", | |
| attn_implementation=attn, | |
| ) | |
| if adapter: | |
| from peft import PeftModel | |
| model = PeftModel.from_pretrained(model, adapter) | |
| print(f"loaded adapter {adapter}") | |
| model.eval() | |
| return model, tokenizer | |
| def assistant_spans(tokenizer, messages: list[dict], max_len: int) -> tuple[torch.Tensor, list[tuple[int, int]]]: | |
| """Tokenize the full chat and return (input_ids, assistant token ranges).""" | |
| ids = tokenizer.apply_chat_template( | |
| messages, tokenize=True, add_generation_prompt=False, return_tensors="pt" | |
| )[0] | |
| if ids.numel() > max_len: | |
| ids = ids[-max_len:] | |
| # rebuild spans by growing the conversation | |
| spans: list[tuple[int, int]] = [] | |
| prefix: list[dict] = [] | |
| prev_len = 0 | |
| for message in messages: | |
| prefix.append(message) | |
| cur = tokenizer.apply_chat_template( | |
| prefix, tokenize=True, add_generation_prompt=False | |
| ) | |
| cur_len = len(cur) | |
| if message.get("role") == "assistant": | |
| start = prev_len | |
| end = cur_len | |
| # map through left-truncate | |
| full_len = cur_len | |
| shift = max(0, full_len - max_len) | |
| start = max(0, start - shift) | |
| end = max(0, end - shift) | |
| if end > start: | |
| spans.append((start, min(end, ids.numel()))) | |
| prev_len = cur_len | |
| return ids, spans | |
| def score_row(model, tokenizer, messages: list[dict], max_len: int) -> dict: | |
| ids, spans = assistant_spans(tokenizer, messages, max_len) | |
| if not spans: | |
| return {"nll": None, "tokens": 0, "correct": 0} | |
| device = next(model.parameters()).device | |
| x = ids.unsqueeze(0).to(device) | |
| logits = model(input_ids=x).logits[0, :-1] | |
| target = ids[1:].to(device) | |
| logp = torch.log_softmax(logits, dim=-1) | |
| nll_sum = 0.0 | |
| tokens = 0 | |
| correct = 0 | |
| for start, end in spans: | |
| # labels are next-token, so supervise ids[start+1:end] | |
| a = max(start, 0) | |
| b = min(end, target.numel() + 1) | |
| lo = max(a - 1, 0) | |
| hi = min(b - 1, target.numel()) | |
| if hi <= lo: | |
| continue | |
| tok_nll = -logp[lo:hi].gather(1, target[lo:hi].unsqueeze(1)).squeeze(1) | |
| pred = logp[lo:hi].argmax(dim=-1) | |
| nll_sum += float(tok_nll.sum().item()) | |
| tokens += hi - lo | |
| correct += int((pred == target[lo:hi]).sum().item()) | |
| return { | |
| "nll": (nll_sum / tokens) if tokens else None, | |
| "tokens": tokens, | |
| "correct": correct, | |
| } | |
| def main() -> int: | |
| parser = argparse.ArgumentParser(description="Teacher-forced holdout eval against the reference.") | |
| parser.add_argument("--model", required=True, help="king / base model directory") | |
| parser.add_argument("--adapter", help="optional LoRA adapter directory") | |
| parser.add_argument("--data", type=Path, default=Path("datasets/mix/holdout_sft.jsonl")) | |
| parser.add_argument("--out", type=Path, required=True) | |
| parser.add_argument("--compare", type=Path, help="previous eval json to diff against") | |
| parser.add_argument("--max-seq-len", type=int, default=8192) | |
| parser.add_argument("--limit", type=int, default=0, help="score only the first N rows (0 = all)") | |
| parser.add_argument("--attn", default="sdpa") | |
| args = parser.parse_args() | |
| rows = load_jsonl(args.data) | |
| if args.limit: | |
| rows = rows[: args.limit] | |
| model, tokenizer = load_model(args.model, args.adapter, args.attn) | |
| per: list[dict] = [] | |
| nll_num = 0.0 | |
| nll_den = 0 | |
| tok_ok = 0 | |
| tok_n = 0 | |
| by_phase: dict[str, list[float]] = {} | |
| for i, row in enumerate(rows, start=1): | |
| result = score_row(model, tokenizer, row["messages"], args.max_seq_len) | |
| rec = { | |
| "sample_id": row.get("sample_id"), | |
| "phase": row.get("phase"), | |
| "habits": row.get("habits"), | |
| **result, | |
| } | |
| per.append(rec) | |
| if result["nll"] is not None and result["tokens"]: | |
| nll_num += result["nll"] * result["tokens"] | |
| nll_den += result["tokens"] | |
| tok_ok += result["correct"] | |
| tok_n += result["tokens"] | |
| by_phase.setdefault(row.get("phase") or "unknown", []).append(result["nll"]) | |
| print( | |
| f"[{i}/{len(rows)}] nll={result['nll']} tokens={result['tokens']} " | |
| f"phase={row.get('phase')} id={row.get('sample_id')}" | |
| ) | |
| mean_nll = nll_num / nll_den if nll_den else None | |
| acc = tok_ok / tok_n if tok_n else None | |
| report = { | |
| "model": args.model, | |
| "adapter": args.adapter, | |
| "data": str(args.data), | |
| "rows": len(rows), | |
| "mean_nll": mean_nll, | |
| "token_accuracy": acc, | |
| "tokens": tok_n, | |
| "nll_by_phase": {k: sum(v) / len(v) for k, v in by_phase.items() if v}, | |
| "per_sample": per, | |
| } | |
| if args.compare and args.compare.is_file(): | |
| prev = json.loads(args.compare.read_text()) | |
| old = prev.get("mean_nll") | |
| if old and mean_nll: | |
| rel = (old - mean_nll) / old | |
| report["baseline"] = { | |
| "path": str(args.compare), | |
| "mean_nll": old, | |
| "token_accuracy": prev.get("token_accuracy"), | |
| } | |
| report["relative_nll_drop"] = rel | |
| report["gate"] = ( | |
| "pass" | |
| if rel >= 0.08 | |
| else ("weak" if rel >= 0.05 else "fail") | |
| ) | |
| print( | |
| f"\nvs {args.compare}: NLL {old:.4f} → {mean_nll:.4f} " | |
| f"relative drop {rel*100:.1f}% gate={report['gate']}" | |
| ) | |
| print("gate: pass ≥8% weak ≥5% fail <5% (submit only on pass)") | |
| args.out.parent.mkdir(parents=True, exist_ok=True) | |
| args.out.write_text(json.dumps(report, indent=2) + "\n") | |
| print(f"\nmean NLL {mean_nll} token acc {acc} tokens {tok_n}") | |
| print(f"wrote {args.out}") | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |