Download code/train.py from SoulFireMage/weight-reading-probe: direct link, hf CLI and curl.
- Browser
- Download file 6.08 kB
-
https://huggingface.co/datasets/SoulFireMage/weight-reading-probe/resolve/main/code/train.py
- Command line
-
hf download hf://datasets/SoulFireMage/weight-reading-probe/code/train.py
-
curl -L -o train.py https://huggingface.co/datasets/SoulFireMage/weight-reading-probe/resolve/main/code/train.py
6.08 kB
| """PPO trainer for the weight-reading probe. | |
| The policy is the network under study: 500 -> 32 -> 32 -> 5, tanh, PyTorch default init. | |
| The value function is a SEPARATE network, so no shared trunk contaminates the policy weights. | |
| Identical hyperparameters for every game (see CONFIG). | |
| """ | |
| import argparse, json, time | |
| import numpy as np, torch, torch.nn as nn | |
| from games import GAMES, random_returns | |
| CONFIG = dict( | |
| total_steps=20_000_000, n_envs=128, n_steps=128, epochs=4, minibatches=4, | |
| lr=2.5e-4, gamma=0.99, gae_lambda=0.95, clip=0.2, ent_coef=0.01, vf_coef=0.5, | |
| max_grad_norm=0.5, eval_episodes=500, | |
| # Competence gate (frozen before launch): trained mean return must exceed the | |
| # random-policy mean by >= 1.0 AND Welch t-statistic must exceed 3.3 (p < ~0.001). | |
| gate_min_diff=1.0, gate_min_t=3.3, | |
| ) | |
| def policy_net(): | |
| return nn.Sequential(nn.Linear(500, 32), nn.Tanh(), nn.Linear(32, 32), nn.Tanh(), nn.Linear(32, 5)) | |
| def value_net(): | |
| return nn.Sequential(nn.Linear(500, 64), nn.Tanh(), nn.Linear(64, 64), nn.Tanh(), nn.Linear(64, 1)) | |
| def weights_dict(pi): | |
| sd = pi.state_dict() | |
| names = {"0.weight": "fc1.weight", "0.bias": "fc1.bias", "2.weight": "fc2.weight", | |
| "2.bias": "fc2.bias", "4.weight": "out.weight", "4.bias": "out.bias"} | |
| return {names[k]: v.detach().cpu().numpy().astype(np.float32) for k, v in sd.items()} | |
| def evaluate(pi, game, episodes, seed): | |
| env = GAMES[game](64, seed) | |
| obs = env.reset(); ep = np.zeros(64); out = [] | |
| while len(out) < episodes: | |
| logits = pi(torch.as_tensor(obs)) | |
| a = torch.distributions.Categorical(logits=logits).sample().numpy() | |
| obs, r, d = env.step(a) | |
| ep += r | |
| for i in np.where(d)[0]: | |
| out.append(ep[i]); ep[i] = 0 | |
| return np.array(out[:episodes]) | |
| def train(game, seed, total_steps=None, log_every=50): | |
| c = dict(CONFIG) | |
| if total_steps: | |
| c["total_steps"] = total_steps | |
| torch.manual_seed(seed); np.random.seed(seed) | |
| torch.set_num_threads(1) | |
| pi, vf = policy_net(), value_net() | |
| opt = torch.optim.Adam(list(pi.parameters()) + list(vf.parameters()), lr=c["lr"], eps=1e-5) | |
| env = GAMES[game](c["n_envs"], seed) | |
| obs = torch.as_tensor(env.reset()) | |
| N, T = c["n_envs"], c["n_steps"] | |
| iters = c["total_steps"] // (N * T) | |
| ep_ret = np.zeros(N); recent = [] | |
| t0 = time.time() | |
| for it in range(iters): | |
| frac = 1 - it / iters | |
| for g in opt.param_groups: | |
| g["lr"] = c["lr"] * frac | |
| bo, ba, blp, br, bd, bv = [], [], [], [], [], [] | |
| with torch.no_grad(): | |
| for _ in range(T): | |
| logits = pi(obs); dist = torch.distributions.Categorical(logits=logits) | |
| a = dist.sample(); v = vf(obs).squeeze(-1) | |
| nobs, r, d = env.step(a.numpy()) | |
| bo.append(obs); ba.append(a); blp.append(dist.log_prob(a)); bv.append(v) | |
| br.append(torch.as_tensor(r)); bd.append(torch.as_tensor(d, dtype=torch.float32)) | |
| ep_ret += r | |
| for i in np.where(d)[0]: | |
| recent.append(ep_ret[i]); ep_ret[i] = 0 | |
| obs = torch.as_tensor(nobs) | |
| last_v = vf(obs).squeeze(-1) | |
| adv = torch.zeros(T, N); gae = torch.zeros(N) | |
| for t in reversed(range(T)): | |
| nv = last_v if t == T - 1 else bv[t + 1] | |
| nonterm = 1 - bd[t] | |
| delta = br[t] + c["gamma"] * nv * nonterm - bv[t] | |
| gae = delta + c["gamma"] * c["gae_lambda"] * nonterm * gae | |
| adv[t] = gae | |
| ret = adv + torch.stack(bv) | |
| O = torch.stack(bo).reshape(T * N, 500); A = torch.stack(ba).reshape(-1) | |
| LP = torch.stack(blp).reshape(-1); ADV = adv.reshape(-1); RET = ret.reshape(-1) | |
| mb = (T * N) // c["minibatches"] | |
| for _ in range(c["epochs"]): | |
| perm = torch.randperm(T * N) | |
| for s in range(0, T * N, mb): | |
| j = perm[s:s + mb] | |
| dist = torch.distributions.Categorical(logits=pi(O[j])) | |
| lp = dist.log_prob(A[j]); ratio = (lp - LP[j]).exp() | |
| ad = (ADV[j] - ADV[j].mean()) / (ADV[j].std() + 1e-8) | |
| pl = -torch.min(ratio * ad, ratio.clamp(1 - c["clip"], 1 + c["clip"]) * ad).mean() | |
| vl = ((vf(O[j]).squeeze(-1) - RET[j]) ** 2).mean() | |
| loss = pl + c["vf_coef"] * vl - c["ent_coef"] * dist.entropy().mean() | |
| opt.zero_grad(); loss.backward() | |
| nn.utils.clip_grad_norm_(list(pi.parameters()) + list(vf.parameters()), c["max_grad_norm"]) | |
| opt.step() | |
| if it % log_every == 0 or it == iters - 1: | |
| m = np.mean(recent[-200:]) if recent else float("nan") | |
| sps = (it + 1) * N * T / (time.time() - t0) | |
| print(f"[{game} s{seed}] it {it}/{iters} steps {(it+1)*N*T:,} return {m:.2f} sps {sps:,.0f}", flush=True) | |
| trained = evaluate(pi, game, c["eval_episodes"], seed + 10_000) | |
| rand = random_returns(game, c["eval_episodes"], seed + 20_000) | |
| diff = trained.mean() - rand.mean() | |
| t = diff / np.sqrt(trained.var(ddof=1) / len(trained) + rand.var(ddof=1) / len(rand) + 1e-12) | |
| stats = dict(game=game, seed=seed, steps=iters * N * T, trained_mean=float(trained.mean()), | |
| trained_sd=float(trained.std()), random_mean=float(rand.mean()), | |
| random_sd=float(rand.std()), diff=float(diff), welch_t=float(t), | |
| passes_gate=bool(diff >= c["gate_min_diff"] and t >= c["gate_min_t"]), | |
| wall_seconds=time.time() - t0, config=c) | |
| return pi, stats | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--game", required=True); ap.add_argument("--seed", type=int, default=0) | |
| ap.add_argument("--steps", type=int, default=None); ap.add_argument("--out", default=None) | |
| a = ap.parse_args() | |
| pi, stats = train(a.game, a.seed, a.steps) | |
| print(json.dumps({k: v for k, v in stats.items() if k != "config"}, indent=1)) | |
| if a.out: | |
| np.savez(a.out, **weights_dict(pi)) | |