Download code/fit_scaling.py from ML-Intern-lab/pre2post-chess-replication: direct link, hf CLI and curl.
- Browser
- Download file 8.78 kB
-
https://huggingface.co/datasets/ML-Intern-lab/pre2post-chess-replication/resolve/main/code/fit_scaling.py
- Command line
-
hf download hf://datasets/ML-Intern-lab/pre2post-chess-replication/code/fit_scaling.py
-
curl -L -o fit_scaling.py https://huggingface.co/datasets/ML-Intern-lab/pre2post-chess-replication/resolve/main/code/fit_scaling.py
8.78 kB
| #!/usr/bin/env python | |
| """Fit the joint pretraining-RL scaling law from the T2/T2b sweep results. | |
| Replicates arXiv:2607.16097 App. G at reduced scale on the 20M family: | |
| 1. Per RL run: OLS fit of pass@1 vs (log10 C_RL - log10 C_ref), C_ref = 1e20 | |
| (Eq. 7), giving per-run (R_ref, B). | |
| 2. Claim 4a: R_ref vs pretraining validation loss L_pt — Spearman rho and an | |
| exponential fit f(L) = gamma + alpha*exp(-beta*L) (Eq. 8). | |
| 3. Claim 4b: local RL slope B vs log10 pretraining tokens T — Pearson r | |
| (paper: +0.84 on B3-B4) and linear fit. | |
| Two evaluation subsets are fit separately: | |
| b3b4 = the paper's fitting bins (results/t2/); at our reduced measurement | |
| scale these floor at zero (reported as a scale limitation). | |
| b1b2 = the focused high-power sweep (results/t2b/), used because at our | |
| scale nothing saturates and B1+B2 sits above the resolution floor. | |
| C_RL estimation: C = 10 * N * T_rollout, T_rollout = 256 prompts x group 8 x | |
| (L_prompt + L_resp) per step (paper App. D); a step-only sensitivity variant | |
| is also reported since a constant multiplier affects R_ref levels but not | |
| slopes. | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import re | |
| import numpy as np | |
| from huggingface_hub import HfApi, hf_hub_download | |
| from scipy import stats | |
| from scipy.optimize import curve_fit | |
| RESULTS_REPO = "ML-Intern-lab/pre2post-chess-replication" | |
| C_REF = 1e20 | |
| N_PARAMS_20M = 20.5e6 | |
| PROMPTS_PER_STEP = 256 | |
| GROUP = 8 | |
| def load_results(): | |
| api = HfApi() | |
| files = [f for f in api.list_repo_files(RESULTS_REPO, repo_type="dataset") | |
| if f.startswith(("results/t2/", "results/t2b/")) and f.endswith(".json")] | |
| runs = {} | |
| for f in files: | |
| p = hf_hub_download(RESULTS_REPO, f, repo_type="dataset") | |
| d = json.load(open(p)) | |
| tag = os.path.basename(f)[:-5] | |
| subset = "b1b2" if tag.startswith("t2b_") else "b3b4" | |
| m = re.match(r"(?:t2b_|rl_)20m_([\dp]+)B_s(\d+)", tag) | |
| if not m: | |
| continue | |
| tok_b = float(m.group(1).replace("p", ".")) | |
| step = int(m.group(2)) | |
| runs.setdefault((subset, tok_b), {})[step] = d["summary"]["pass1_mean_overall"] | |
| return runs | |
| def load_losses(): | |
| api = HfApi() | |
| files = [f for f in api.list_repo_files(RESULTS_REPO, repo_type="dataset") | |
| if f.startswith("results/loss/loss_model_20m_") and f.endswith(".json")] | |
| losses = {} | |
| for f in files: | |
| p = hf_hub_download(RESULTS_REPO, f, repo_type="dataset") | |
| d = json.load(open(p)) | |
| tok_b = d.get("pretrain_tokens", 0) / 1e9 | |
| losses[round(tok_b, 2)] = d["val_loss"] | |
| return losses | |
| def fit_exp(L, alpha, beta, gamma): | |
| return gamma + alpha * np.exp(-beta * np.asarray(L)) | |
| def analyze(runs, losses, args, label): | |
| per_run = [] | |
| for tok_b, curve in sorted(runs.items()): | |
| steps = sorted(curve) | |
| if len(steps) < 3: | |
| print(f"[{label}] [skip] T={tok_b}B has {len(steps)} points") | |
| continue | |
| L = losses.get(round(tok_b, 2)) | |
| T_rollout_step = PROMPTS_PER_STEP * GROUP * (args.prompt_len + args.resp_len) | |
| c_per_step = 10 * N_PARAMS_20M * T_rollout_step | |
| x = np.array([np.log10(step * c_per_step) - np.log10(C_REF) for step in steps]) | |
| y = np.array([curve[s] for s in steps]) | |
| xs = np.log10(np.array(steps, dtype=float)) # step-only sensitivity fit | |
| if float(y.max() - y.min()) < 1e-9: | |
| B, R_ref, Bs, Rs = 0.0, float(y.mean()), 0.0, float(y.mean()) | |
| else: | |
| A = np.vstack([np.ones_like(x), x]).T | |
| (R_ref, B), *_ = np.linalg.lstsq(A, y, rcond=None) | |
| As = np.vstack([np.ones_like(xs), xs]).T | |
| (Rs, Bs), *_ = np.linalg.lstsq(As, y, rcond=None) | |
| per_run.append({ | |
| "tokens": tok_b, "log10_tokens": float(np.log10(tok_b * 1e9)), | |
| "loss": L, "steps": steps, "pass1": [float(v) for v in y], | |
| "R_ref": float(R_ref), "B": float(B), | |
| "R_ref_step": float(Rs), "B_step": float(Bs), | |
| "pass1_last": float(y[-1]), | |
| }) | |
| print(f"[{label}] T={tok_b:5.1f}B L={('%.3f' % L) if L else ' ? '} " | |
| f"pass1={[round(float(v), 4) for v in y]} " | |
| f"-> R_ref={R_ref:.4f} B={B:.5f}") | |
| done = [r for r in per_run if r["loss"] is not None] | |
| out = {"per_run": per_run} | |
| # ---- claim 4a: R_ref vs pretraining loss -------------------------------- | |
| if len(done) >= 4: | |
| Ls = np.array([r["loss"] for r in done]) | |
| Rs = np.array([r["R_ref"] for r in done]) | |
| rho, rho_p = stats.spearmanr(Ls, Rs) | |
| popt = None | |
| try: | |
| popt, _ = curve_fit(fit_exp, Ls, Rs, p0=[100.0, 12.0, 0.03], maxfev=20000) | |
| pred = fit_exp(Ls, *popt) | |
| ss_res = float(((Rs - pred) ** 2).sum()) | |
| ss_tot = float(((Rs - Rs.mean()) ** 2).sum()) | |
| r2 = 1 - ss_res / ss_tot if ss_tot > 0 else float("nan") | |
| except Exception as e: | |
| r2 = float("nan") | |
| print(f"[{label}] exp fit failed: {e}") | |
| out["claim_R_ref_vs_loss"] = { | |
| "spearman_rho": float(rho), "spearman_p": float(rho_p), | |
| "exp_fit": {"alpha": float(popt[0]), "beta": float(popt[1]), | |
| "gamma": float(popt[2]), "R2": r2} if popt is not None else None, | |
| "paper": {"rho_range": "[-0.99, -0.93]", | |
| "alpha_f": 129.85, "beta_f": 12.85, "gamma_f": 0.0314, | |
| "R2_f": 0.980}, | |
| } | |
| print(f"[{label}] Claim 4a (R_ref vs L): Spearman rho={rho:.3f} " | |
| f"(paper -0.93..-0.99)") | |
| # ---- claim 4a (no-extrapolation variant): pass@1 at fixed RL compute ---- | |
| # At our reduced scale the R_ref extrapolation to C_ref=1e20 is noise- | |
| # dominated, so also correlate the MEASURED pass@1 at the last (and highest | |
| # common) RL step with L. This is the same claim read without extrapolation. | |
| if len(done) >= 4: | |
| last = {} | |
| for r in done: | |
| last[r["tokens"]] = (r["loss"], r["pass1"][-1], r["steps"][-1]) | |
| Ls2 = np.array([v[0] for v in last.values()]) | |
| Rs2 = np.array([v[1] for v in last.values()]) | |
| rho2, rho2_p = stats.spearmanr(Ls2, Rs2) | |
| r2_lin, r2_p = stats.pearsonr(Ls2, Rs2) | |
| out["claim_R_ref_vs_loss_measured"] = { | |
| "note": "pass@1 at the measured (non-extrapolated) final RL step vs L", | |
| "points": {f"{t}B": {"loss": v[0], "pass1_last": v[1], "step": v[2]} | |
| for t, v in last.items()}, | |
| "spearman_rho": float(rho2), "spearman_p": float(rho2_p), | |
| "pearson_r": float(r2_lin), "pearson_p": float(r2_p), | |
| "paper": {"rho_range": "[-0.99, -0.93]"}, | |
| } | |
| print(f"[{label}] Claim 4a measured (pass1@last vs L): Spearman " | |
| f"rho={rho2:.3f}, Pearson r={r2_lin:.3f}") | |
| # ---- claim 4b: slope B vs log10 tokens ---------------------------------- | |
| if len(done) >= 4: | |
| Ts = np.array([r["log10_tokens"] for r in done]) | |
| Bs = np.array([r["B"] for r in done]) | |
| r, r_p = stats.pearsonr(Ts, Bs) | |
| rho_b, _ = stats.spearmanr(Ts, Bs) | |
| slope, intercept = np.polyfit(Ts, Bs, 1) | |
| pred = intercept + slope * Ts | |
| ss_tot = float(((Bs - Bs.mean()) ** 2).sum()) | |
| r2 = 1 - float(((Bs - pred) ** 2).sum()) / ss_tot if ss_tot > 0 else float("nan") | |
| out["claim_B_vs_logT"] = { | |
| "pearson_r": float(r), "p": float(r_p), "spearman_rho": float(rho_b), | |
| "linear_fit": {"slope_per_decade_tokens": float(slope), | |
| "intercept": float(intercept), "R2": r2}, | |
| "paper": {"pearson_r": 0.84}, | |
| } | |
| print(f"[{label}] Claim 4b (B vs log T): Pearson r={r:.3f} (paper +0.84), " | |
| f"slope={slope:.5f}/decade, R2={r2:.3f}") | |
| return out | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--resp-len", type=float, default=1400.0, | |
| help="assumed mean RL response tokens per rollout") | |
| ap.add_argument("--prompt-len", type=float, default=300.0) | |
| ap.add_argument("--out", default="fit_results.json") | |
| args = ap.parse_args() | |
| runs = load_results() | |
| losses = load_losses() | |
| print(f"RL runs: {sorted(runs)}") | |
| print(f"losses: {sorted(losses)}") | |
| out = {"config": vars(args), "subsets": {}} | |
| for subset in ("b1b2", "b3b4"): | |
| sub = {t: curve for (s, t), curve in runs.items() if s == subset} | |
| if not sub: | |
| print(f"[skip] no data for subset {subset}") | |
| continue | |
| out["subsets"][subset] = analyze(sub, losses, args, subset) | |
| with open(args.out, "w") as f: | |
| json.dump(out, f, indent=2, default=float) | |
| print(f"\nwrote {args.out}") | |
| if __name__ == "__main__": | |
| main() | |