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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Fit the joint pretraining-RL scaling law from the T2/T2b sweep results.
|
| 3 |
+
|
| 4 |
+
Replicates arXiv:2607.16097 App. G at reduced scale on the 20M family:
|
| 5 |
+
1. Per RL run: OLS fit of pass@1 vs (log10 C_RL - log10 C_ref), C_ref = 1e20
|
| 6 |
+
(Eq. 7), giving per-run (R_ref, B).
|
| 7 |
+
2. Claim 4a: R_ref vs pretraining validation loss L_pt — Spearman rho and an
|
| 8 |
+
exponential fit f(L) = gamma + alpha*exp(-beta*L) (Eq. 8).
|
| 9 |
+
3. Claim 4b: local RL slope B vs log10 pretraining tokens T — Pearson r
|
| 10 |
+
(paper: +0.84 on B3-B4) and linear fit.
|
| 11 |
+
|
| 12 |
+
Two evaluation subsets are fit separately:
|
| 13 |
+
b3b4 = the paper's fitting bins (results/t2/); at our reduced measurement
|
| 14 |
+
scale these floor at zero (reported as a scale limitation).
|
| 15 |
+
b1b2 = the focused high-power sweep (results/t2b/), used because at our
|
| 16 |
+
scale nothing saturates and B1+B2 sits above the resolution floor.
|
| 17 |
+
|
| 18 |
+
C_RL estimation: C = 10 * N * T_rollout, T_rollout = 256 prompts x group 8 x
|
| 19 |
+
(L_prompt + L_resp) per step (paper App. D); a step-only sensitivity variant
|
| 20 |
+
is also reported since a constant multiplier affects R_ref levels but not
|
| 21 |
+
slopes.
|
| 22 |
+
"""
|
| 23 |
+
import argparse
|
| 24 |
+
import json
|
| 25 |
+
import os
|
| 26 |
+
import re
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 30 |
+
from scipy import stats
|
| 31 |
+
from scipy.optimize import curve_fit
|
| 32 |
+
|
| 33 |
+
RESULTS_REPO = "ML-Intern-lab/pre2post-chess-replication"
|
| 34 |
+
C_REF = 1e20
|
| 35 |
+
N_PARAMS_20M = 20.5e6
|
| 36 |
+
PROMPTS_PER_STEP = 256
|
| 37 |
+
GROUP = 8
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def load_results():
|
| 41 |
+
api = HfApi()
|
| 42 |
+
files = [f for f in api.list_repo_files(RESULTS_REPO, repo_type="dataset")
|
| 43 |
+
if f.startswith(("results/t2/", "results/t2b/")) and f.endswith(".json")]
|
| 44 |
+
runs = {}
|
| 45 |
+
for f in files:
|
| 46 |
+
p = hf_hub_download(RESULTS_REPO, f, repo_type="dataset")
|
| 47 |
+
d = json.load(open(p))
|
| 48 |
+
tag = os.path.basename(f)[:-5]
|
| 49 |
+
subset = "b1b2" if tag.startswith("t2b_") else "b3b4"
|
| 50 |
+
m = re.match(r"(?:t2b_|rl_)20m_([\dp]+)B_s(\d+)", tag)
|
| 51 |
+
if not m:
|
| 52 |
+
continue
|
| 53 |
+
tok_b = float(m.group(1).replace("p", "."))
|
| 54 |
+
step = int(m.group(2))
|
| 55 |
+
runs.setdefault((subset, tok_b), {})[step] = d["summary"]["pass1_mean_overall"]
|
| 56 |
+
return runs
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def load_losses():
|
| 60 |
+
api = HfApi()
|
| 61 |
+
files = [f for f in api.list_repo_files(RESULTS_REPO, repo_type="dataset")
|
| 62 |
+
if f.startswith("results/loss/loss_model_20m_") and f.endswith(".json")]
|
| 63 |
+
losses = {}
|
| 64 |
+
for f in files:
|
| 65 |
+
p = hf_hub_download(RESULTS_REPO, f, repo_type="dataset")
|
| 66 |
+
d = json.load(open(p))
|
| 67 |
+
tok_b = d.get("pretrain_tokens", 0) / 1e9
|
| 68 |
+
losses[round(tok_b, 2)] = d["val_loss"]
|
| 69 |
+
return losses
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def fit_exp(L, alpha, beta, gamma):
|
| 73 |
+
return gamma + alpha * np.exp(-beta * np.asarray(L))
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def analyze(runs, losses, args, label):
|
| 77 |
+
per_run = []
|
| 78 |
+
for tok_b, curve in sorted(runs.items()):
|
| 79 |
+
steps = sorted(curve)
|
| 80 |
+
if len(steps) < 3:
|
| 81 |
+
print(f"[{label}] [skip] T={tok_b}B has {len(steps)} points")
|
| 82 |
+
continue
|
| 83 |
+
L = losses.get(round(tok_b, 2))
|
| 84 |
+
T_rollout_step = PROMPTS_PER_STEP * GROUP * (args.prompt_len + args.resp_len)
|
| 85 |
+
c_per_step = 10 * N_PARAMS_20M * T_rollout_step
|
| 86 |
+
x = np.array([np.log10(step * c_per_step) - np.log10(C_REF) for step in steps])
|
| 87 |
+
y = np.array([curve[s] for s in steps])
|
| 88 |
+
xs = np.log10(np.array(steps, dtype=float)) # step-only sensitivity fit
|
| 89 |
+
if float(y.max() - y.min()) < 1e-9:
|
| 90 |
+
B, R_ref, Bs, Rs = 0.0, float(y.mean()), 0.0, float(y.mean())
|
| 91 |
+
else:
|
| 92 |
+
A = np.vstack([np.ones_like(x), x]).T
|
| 93 |
+
(R_ref, B), *_ = np.linalg.lstsq(A, y, rcond=None)
|
| 94 |
+
As = np.vstack([np.ones_like(xs), xs]).T
|
| 95 |
+
(Rs, Bs), *_ = np.linalg.lstsq(As, y, rcond=None)
|
| 96 |
+
per_run.append({
|
| 97 |
+
"tokens": tok_b, "log10_tokens": float(np.log10(tok_b * 1e9)),
|
| 98 |
+
"loss": L, "steps": steps, "pass1": [float(v) for v in y],
|
| 99 |
+
"R_ref": float(R_ref), "B": float(B),
|
| 100 |
+
"R_ref_step": float(Rs), "B_step": float(Bs),
|
| 101 |
+
"pass1_last": float(y[-1]),
|
| 102 |
+
})
|
| 103 |
+
print(f"[{label}] T={tok_b:5.1f}B L={('%.3f' % L) if L else ' ? '} "
|
| 104 |
+
f"pass1={[round(float(v), 4) for v in y]} "
|
| 105 |
+
f"-> R_ref={R_ref:.4f} B={B:.5f}")
|
| 106 |
+
|
| 107 |
+
done = [r for r in per_run if r["loss"] is not None]
|
| 108 |
+
out = {"per_run": per_run}
|
| 109 |
+
|
| 110 |
+
# ---- claim 4a: R_ref vs pretraining loss --------------------------------
|
| 111 |
+
if len(done) >= 4:
|
| 112 |
+
Ls = np.array([r["loss"] for r in done])
|
| 113 |
+
Rs = np.array([r["R_ref"] for r in done])
|
| 114 |
+
rho, rho_p = stats.spearmanr(Ls, Rs)
|
| 115 |
+
popt = None
|
| 116 |
+
try:
|
| 117 |
+
popt, _ = curve_fit(fit_exp, Ls, Rs, p0=[100.0, 12.0, 0.03], maxfev=20000)
|
| 118 |
+
pred = fit_exp(Ls, *popt)
|
| 119 |
+
ss_res = float(((Rs - pred) ** 2).sum())
|
| 120 |
+
ss_tot = float(((Rs - Rs.mean()) ** 2).sum())
|
| 121 |
+
r2 = 1 - ss_res / ss_tot if ss_tot > 0 else float("nan")
|
| 122 |
+
except Exception as e:
|
| 123 |
+
r2 = float("nan")
|
| 124 |
+
print(f"[{label}] exp fit failed: {e}")
|
| 125 |
+
out["claim_R_ref_vs_loss"] = {
|
| 126 |
+
"spearman_rho": float(rho), "spearman_p": float(rho_p),
|
| 127 |
+
"exp_fit": {"alpha": float(popt[0]), "beta": float(popt[1]),
|
| 128 |
+
"gamma": float(popt[2]), "R2": r2} if popt is not None else None,
|
| 129 |
+
"paper": {"rho_range": "[-0.99, -0.93]",
|
| 130 |
+
"alpha_f": 129.85, "beta_f": 12.85, "gamma_f": 0.0314,
|
| 131 |
+
"R2_f": 0.980},
|
| 132 |
+
}
|
| 133 |
+
print(f"[{label}] Claim 4a (R_ref vs L): Spearman rho={rho:.3f} "
|
| 134 |
+
f"(paper -0.93..-0.99)")
|
| 135 |
+
|
| 136 |
+
# ---- claim 4a (no-extrapolation variant): pass@1 at fixed RL compute ----
|
| 137 |
+
# At our reduced scale the R_ref extrapolation to C_ref=1e20 is noise-
|
| 138 |
+
# dominated, so also correlate the MEASURED pass@1 at the last (and highest
|
| 139 |
+
# common) RL step with L. This is the same claim read without extrapolation.
|
| 140 |
+
if len(done) >= 4:
|
| 141 |
+
last = {}
|
| 142 |
+
for r in done:
|
| 143 |
+
last[r["tokens"]] = (r["loss"], r["pass1"][-1], r["steps"][-1])
|
| 144 |
+
Ls2 = np.array([v[0] for v in last.values()])
|
| 145 |
+
Rs2 = np.array([v[1] for v in last.values()])
|
| 146 |
+
rho2, rho2_p = stats.spearmanr(Ls2, Rs2)
|
| 147 |
+
r2_lin, r2_p = stats.pearsonr(Ls2, Rs2)
|
| 148 |
+
out["claim_R_ref_vs_loss_measured"] = {
|
| 149 |
+
"note": "pass@1 at the measured (non-extrapolated) final RL step vs L",
|
| 150 |
+
"points": {f"{t}B": {"loss": v[0], "pass1_last": v[1], "step": v[2]}
|
| 151 |
+
for t, v in last.items()},
|
| 152 |
+
"spearman_rho": float(rho2), "spearman_p": float(rho2_p),
|
| 153 |
+
"pearson_r": float(r2_lin), "pearson_p": float(r2_p),
|
| 154 |
+
"paper": {"rho_range": "[-0.99, -0.93]"},
|
| 155 |
+
}
|
| 156 |
+
print(f"[{label}] Claim 4a measured (pass1@last vs L): Spearman "
|
| 157 |
+
f"rho={rho2:.3f}, Pearson r={r2_lin:.3f}")
|
| 158 |
+
|
| 159 |
+
# ---- claim 4b: slope B vs log10 tokens ----------------------------------
|
| 160 |
+
if len(done) >= 4:
|
| 161 |
+
Ts = np.array([r["log10_tokens"] for r in done])
|
| 162 |
+
Bs = np.array([r["B"] for r in done])
|
| 163 |
+
r, r_p = stats.pearsonr(Ts, Bs)
|
| 164 |
+
rho_b, _ = stats.spearmanr(Ts, Bs)
|
| 165 |
+
slope, intercept = np.polyfit(Ts, Bs, 1)
|
| 166 |
+
pred = intercept + slope * Ts
|
| 167 |
+
ss_tot = float(((Bs - Bs.mean()) ** 2).sum())
|
| 168 |
+
r2 = 1 - float(((Bs - pred) ** 2).sum()) / ss_tot if ss_tot > 0 else float("nan")
|
| 169 |
+
out["claim_B_vs_logT"] = {
|
| 170 |
+
"pearson_r": float(r), "p": float(r_p), "spearman_rho": float(rho_b),
|
| 171 |
+
"linear_fit": {"slope_per_decade_tokens": float(slope),
|
| 172 |
+
"intercept": float(intercept), "R2": r2},
|
| 173 |
+
"paper": {"pearson_r": 0.84},
|
| 174 |
+
}
|
| 175 |
+
print(f"[{label}] Claim 4b (B vs log T): Pearson r={r:.3f} (paper +0.84), "
|
| 176 |
+
f"slope={slope:.5f}/decade, R2={r2:.3f}")
|
| 177 |
+
return out
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def main():
|
| 181 |
+
ap = argparse.ArgumentParser()
|
| 182 |
+
ap.add_argument("--resp-len", type=float, default=1400.0,
|
| 183 |
+
help="assumed mean RL response tokens per rollout")
|
| 184 |
+
ap.add_argument("--prompt-len", type=float, default=300.0)
|
| 185 |
+
ap.add_argument("--out", default="fit_results.json")
|
| 186 |
+
args = ap.parse_args()
|
| 187 |
+
|
| 188 |
+
runs = load_results()
|
| 189 |
+
losses = load_losses()
|
| 190 |
+
print(f"RL runs: {sorted(runs)}")
|
| 191 |
+
print(f"losses: {sorted(losses)}")
|
| 192 |
+
|
| 193 |
+
out = {"config": vars(args), "subsets": {}}
|
| 194 |
+
for subset in ("b1b2", "b3b4"):
|
| 195 |
+
sub = {t: curve for (s, t), curve in runs.items() if s == subset}
|
| 196 |
+
if not sub:
|
| 197 |
+
print(f"[skip] no data for subset {subset}")
|
| 198 |
+
continue
|
| 199 |
+
out["subsets"][subset] = analyze(sub, losses, args, subset)
|
| 200 |
+
with open(args.out, "w") as f:
|
| 201 |
+
json.dump(out, f, indent=2, default=float)
|
| 202 |
+
print(f"\nwrote {args.out}")
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
if __name__ == "__main__":
|
| 206 |
+
main()
|