pocket-storyteller / code /avg_snaps.py
Redhanuman's picture
Pocket Storyteller: 4.6 MB story model, browser demo, weights and training code
ebf8f81 verified
Raw History Blame Contribute Delete
2.67 kB
"""Try averaging the last few saves of a round. Often a little better than the last save alone.
python avg_snaps.py rounds/round2.pt snaps rounds/round2_avg.pt
train.py saves ckpt.pt every 250 steps. If copies of the last saves were kept in a folder, this
averages the weights of the last 2, 4, 8, 12 and 16 of them, measures each average on the same unseen
stories, and writes the best one (as a checkpoint that still works with --resume) if it beats the
final save. Prints what it found either way.
"""
import os, sys, numpy as np, torch
from model import Config, Storyteller
final_path, snap_dir, out_path = sys.argv[1:4]
final = torch.load(final_path, map_location="cpu")
cfg = Config(**final["config"])
snaps = []
for f in sorted(os.listdir(snap_dir)):
if f.endswith(".pt"):
ck = torch.load(os.path.join(snap_dir, f), map_location="cpu")
if ck["step"] <= final["step"] and ck.get("sched", {}).get("tag") == final.get("sched", {}).get("tag"):
snaps.append((ck["step"], ck["model"]))
snaps.sort(key=lambda x: x[0])
if not snaps or snaps[-1][0] != final["step"]:
snaps.append((final["step"], final["model"]))
print("saves found at steps:", [s for s, _ in snaps])
val = np.memmap("data/val.bin", dtype=np.uint16, mode="r")
N, B = 2000, 50 # 512,000 word-pieces from the second part of the validation file (bigval.py uses the first part)
m = Storyteller(cfg); m.eval()
def loss_of(sd):
m.load_state_dict(sd); tot = 0.0
with torch.no_grad():
for b in range(0, N, B):
idx = (np.arange(b, b + B) + 6000) * cfg.ctx
x = torch.from_numpy(np.stack([val[i:i + cfg.ctx].astype(np.int64) for i in idx]))
y = torch.from_numpy(np.stack([val[i + 1:i + 1 + cfg.ctx].astype(np.int64) for i in idx]))
tot += m(x, y).item() * B
return tot / N
def average(k):
use = snaps[-k:]
return {name: sum(sd[name].double() for _, sd in use).div(len(use)).float() for name in use[0][1]}
base = loss_of(final["model"])
print(f"last save alone: {base:.4f}")
best = (base, 1, None)
for k in (2, 4, 8, 12, 16):
if k > len(snaps):
break
sd = average(k); l = loss_of(sd)
print(f"average of the last {k:2d} saves (steps {snaps[-k][0]} to {snaps[-1][0]}): {l:.4f} ({l - base:+.4f})")
if l < best[0]:
best = (l, k, sd)
if best[2] is not None and base - best[0] >= 0.001:
out = dict(final); out["model"] = best[2]; out["averaged_saves"] = best[1]
torch.save(out, out_path)
print(f"wrote {out_path}: average of the last {best[1]} saves, {base - best[0]:.4f} better")
else:
print("averaging does not help enough here; keep the last save")