File size: 12,187 Bytes
1c78d11 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 | """Train TD-MPC2's world model on the RISE corpus (gen_q#274, configuration (a) and (b)'s shared model).
Upstream's `TDMPC2._update` (code/tdmpc2/tdmpc2/tdmpc2.py:259) is called VERBATIM, once per step, on
batches this repo's `td_corpus.TDCorpus` hands it in `common/buffer.py:_prepare_batch`'s exact
layout. Nothing in the vendored checkout is edited. What we add around it is what #274 demands and
upstream does not provide offline: a held-out evaluation, the health numbers, and a resumable
checkpoint.
HEALTH written to <out>/health.jsonl at every eval -- read the T-notes and the "honest limit" in
td_corpus.py before quoting any of it:
val/consistency, val/reward_loss, val/value_loss -- upstream's own three losses, no grad, on the
held-out episodes of the SAME split every other column holds out.
fid/lat_rmse_h<h> open-loop latent rollout error ||roll_h(z0,a_{0..h-1}) - enc(o_h)||_2
fid/lat_rmse_h<h>_naive the stay-put predictor ||z0 - enc(o_h)||_2 on the same pairs
fid/lat_ratio_h<h> their quotient. >= 1 means the rollout knows nothing; FLAG the score.
(This is a LATENT fidelity, not DF's observation-space one: TD-MPC2's world model is implicit
and has no decoder. The two baselines' fidelity numbers are therefore NOT interchangeable.)
val/reward_auc the reward head as a provenance discriminator on held-out episodes.
val/q_auc, val/q_expert, val/q_other the terminal value head likewise -- this is the quantity
configuration (a) actually scores candidates with, so it is the one that must be healthy.
val/q_vs_vmax mean Q / (1/(1-gamma)); near 1 or near 0 means the two-hot has collapsed
onto an end bin and the value carries no ordering information.
"""
from __future__ import annotations
import argparse, json, os, sys, time
from pathlib import Path
import numpy as np
import torch
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
sys.path.insert(0, str(Path(__file__).parent))
from td_corpus import (TDCorpus, build_cfg, TD_SRC, install_safe_to, # noqa: E402
install_ensemble_grad_fix, real_state_dict, load_real_state_dict)
def auc(scores, labels):
"""Rank AUC; returns nan if one class is missing (and the caller must print the nan, not hide it)."""
s, y = np.asarray(scores, float), np.asarray(labels, float)
pos, neg = s[y > 0.5], s[y <= 0.5]
if len(pos) == 0 or len(neg) == 0:
return float("nan")
r = np.argsort(np.argsort(np.concatenate([pos, neg]))) + 1.0
return float((r[:len(pos)].sum() - len(pos) * (len(pos) + 1) / 2.0) / (len(pos) * len(neg)))
@torch.no_grad()
def evaluate(agent, corpus, cfg, rng, fid_hs, n_batch=8, batch=128, n_fid=64):
from common import math as tdmath
m, dev = agent.model, agent.device
m.eval()
out = {}
# --- upstream's own three losses on held-out episodes --------------------
cons = rew_l = val_l = 0.0
for _ in range(n_batch):
obs, act, rew, term = corpus.sample(batch, rng, split="val", device=dev)
z = m.encode(obs[0], None)
nz = m.encode(obs[1:], None)
c = 0.0
zs = [z]
for t in range(corpus.H):
z = m.next(z, act[t], None)
c += torch.nn.functional.mse_loss(z, nz[t]).item() * cfg.rho ** t
zs.append(z)
zs = torch.stack(zs[:-1])
cons += c / corpus.H
rp = m.reward(zs, act, None)
rl = 0.0
for t in range(corpus.H):
rl += tdmath.soft_ce(rp[t], rew[t], cfg).mean().item() * cfg.rho ** t
rew_l += rl / corpus.H
tgt = agent._td_target(nz, rew, term, None)
q = m.Q(zs, act, None, return_type="all")
vl = 0.0
for t in range(corpus.H):
for k in range(cfg.num_q):
vl += tdmath.soft_ce(q[k, t], tgt[t], cfg).mean().item() * cfg.rho ** t
val_l += vl / (corpus.H * cfg.num_q)
out["val/consistency"] = cons / n_batch
out["val/reward_loss"] = rew_l / n_batch
out["val/value_loss"] = val_l / n_batch
# --- latent rollout fidelity vs the TRUE future -------------------------
Hmax = max(fid_hs)
wins = corpus.val_episode_rows(n_fid, rng, min_len=Hmax + 1)
if wins:
O = np.stack([corpus.d.obs_rows(r) for r, _ in wins], 1) # [Hmax+1, n, 1545]
A = np.stack([np.asarray(corpus.d.act[r[:-1]], np.float32) for r, _ in wins], 1)
lab = np.array([l for _, l in wins], np.float32)
O = torch.from_numpy(O).to(dev); A = torch.from_numpy(A).to(dev)
z0 = m.encode(O[0], None)
z = z0.clone()
for h in range(1, Hmax + 1):
z = m.next(z, A[h - 1], None)
if h in fid_hs:
zt = m.encode(O[h], None)
e = (z - zt).norm(dim=-1).mean().item()
n = (z0 - zt).norm(dim=-1).mean().item()
out[f"fid/lat_rmse_h{h}"] = e
out[f"fid/lat_rmse_h{h}_naive"] = n
out[f"fid/lat_ratio_h{h}"] = e / max(n, 1e-8)
# --- heads as provenance discriminators on the same held-out frames ---
rp = tdmath.two_hot_inv(m.reward(z0, A[0], None), cfg).squeeze(-1).cpu().numpy()
qv = m.Q(z0, A[0], None, return_type="min").squeeze(-1).cpu().numpy()
out["val/reward_auc"] = auc(rp, lab)
out["val/q_auc"] = auc(qv, lab)
out["val/q_expert"] = float(qv[lab > 0.5].mean()) if (lab > 0.5).any() else float("nan")
out["val/q_other"] = float(qv[lab <= 0.5].mean()) if (lab <= 0.5).any() else float("nan")
# cfg.vmax is in SYMLOG units (td_corpus T2); the ratio must be taken in VALUE units.
out["val/q_vs_vmax"] = float(qv.mean() * (1.0 - float(cfg.discount_min)))
# T6. `val/q_std == 0` and `val/q_headw_absmax == 0` are the DIRECT reading of a Q head
# that never left its zero-initialised last layer -- the failure the first seven cells had
# and that could only be found by recognising ln(num_bins) and symexp(vmax/2) in the logs.
# Never again: both go into every health row, beside the constant they would collapse to.
out["val/q_std"] = float(qv.std())
out["val/q_uniform_const"] = float(np.expm1(float(cfg.vmax) / 2.0))
out["val/q_headw_absmax"] = float(m._Qs.params["2", "weight"].abs().max())
out["val/n_fid_windows"] = len(wins)
m.eval()
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--cache", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--horizon", type=int, default=3, help="TD-MPC2's latent rollout length (its own default 3)")
ap.add_argument("--gamma", type=float, required=True, help="pinned; H = 1/(1-gamma) is the #273 horizon family")
ap.add_argument("--steps", type=int, default=20000)
ap.add_argument("--batch", type=int, default=256)
ap.add_argument("--model-size", type=int, default=5)
ap.add_argument("--lr", type=float, default=None)
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--eval-every", type=int, default=2500)
ap.add_argument("--save-every", type=int, default=5000)
ap.add_argument("--fid-horizons", default="5,10,20")
ap.add_argument("--wandb-name", default=None)
a = ap.parse_args()
out = Path(a.out); out.mkdir(parents=True, exist_ok=True)
fid_hs = sorted({int(x) for x in a.fid_horizons.split(",") if x})
H_gamma = 1.0 / (1.0 - a.gamma)
print(f"[train_tdmpc2] gamma={a.gamma} -> H=1/(1-gamma)={H_gamma:.1f}; vmax pinned to symlog of that "
f"(td_corpus T2); latent rollout horizon={a.horizon}", flush=True)
over = {} if a.lr is None else {"lr": a.lr}
cfg = build_cfg(horizon=a.horizon, gamma=a.gamma, model_size=a.model_size,
batch_size=a.batch, seed=a.seed, work_dir=str(out), **over)
corpus = TDCorpus(a.cache, horizon=a.horizon, seed=a.seed)
sys.path.insert(0, str(TD_SRC))
install_safe_to() # td_corpus T5: TDMPC2.__init__ does WorldModel(cfg).to(device), which
# raises on the meta params tensordict leaves in _detach_Qs/_target_Qs
install_ensemble_grad_fix() # td_corpus T6: without this, `layers.Ensemble.forward` returns a
# DETACHED tensor under torch 2.14/tensordict 0.14.2 and the Q head
# never leaves its zero-init. Measured: status/nb/diag_ensemble.txt.
from tdmpc2 import TDMPC2
torch.manual_seed(a.seed)
agent = TDMPC2(cfg)
print(f"[train_tdmpc2] params {agent.model.total_params:,} latent_dim {cfg.latent_dim} "
f"num_q {cfg.num_q} vmin {cfg.vmin} vmax {cfg.vmax} bin_size {cfg.bin_size:.4g}", flush=True)
step = 0
last = out / "ckpt_last.pt"
if last.exists():
sd = torch.load(last, map_location=agent.device, weights_only=False)
load_real_state_dict(agent.model, sd["model"]); agent.optim.load_state_dict(sd["optim"])
agent.pi_optim.load_state_dict(sd["pi_optim"]); step = int(sd["step"])
print(f"[train_tdmpc2] resumed from {last} at step {step}", flush=True)
def save(tag):
tmp = out / f".tmp_{tag}.pt"
torch.save({"model": real_state_dict(agent.model), "optim": agent.optim.state_dict(),
"pi_optim": agent.pi_optim.state_dict(), "step": step,
"cfg": {k: getattr(cfg, k) for k in
("horizon", "latent_dim", "num_q", "vmin", "vmax", "num_bins",
"action_dim", "model_size", "mlp_dim", "enc_dim", "num_enc_layers",
"simnorm_dim", "task_dim", "multitask", "dropout", "obs_shape",
"bin_size", "log_std_min", "log_std_max", "episodic")},
"gamma": a.gamma, "cache": a.cache}, tmp)
os.replace(tmp, out / tag)
wb = None
if a.wandb_name:
try:
import wandb
wb = wandb.init(project=os.environ.get("WANDB_PROJECT", "rsm_rise"),
entity=os.environ.get("WANDB_ENTITY", "richardrl"),
name=a.wandb_name, config=vars(a), reinit=True)
except Exception as e:
print(f"[train_tdmpc2] wandb off: {e}", flush=True)
rng = np.random.default_rng(a.seed)
erng = np.random.default_rng(a.seed + 9999)
hf = (out / "health.jsonl").open("a")
t0 = time.time()
while step < a.steps:
obs, act, rew, term = corpus.sample(a.batch, rng, split="train", device=agent.device)
info = agent._update(obs, act, rew, term)
step += 1
if step % 200 == 0:
d = {k: float(v) for k, v in info.items()}
print(f"[{step}/{a.steps}] total {d.get('total_loss', float('nan')):.4f} "
f"cons {d.get('consistency_loss', float('nan')):.4f} "
f"rew {d.get('reward_loss', float('nan')):.4f} "
f"val {d.get('value_loss', float('nan')):.4f} "
f"{(time.time()-t0)/step:.3f}s/step", flush=True)
if wb: wb.log({f"train/{k}": v for k, v in d.items()}, step=step)
# step 1 evaluates too: it is the health-path smoke. A bug in evaluate() then costs
# one minute of one GPU instead of the whole eval_every interval of a packed node.
if step == 1 or step % a.eval_every == 0 or step == a.steps:
h = evaluate(agent, corpus, cfg, erng, fid_hs)
h.update({"step": step, "gamma": a.gamma, "H": H_gamma, "cache": a.cache,
"horizon": a.horizon, "model_size": a.model_size, "batch": a.batch,
"wall_s": round(time.time() - t0, 1)})
hf.write(json.dumps(h) + "\n"); hf.flush()
print("[health] " + json.dumps({k: (round(v, 5) if isinstance(v, float) else v)
for k, v in h.items()}), flush=True)
if wb: wb.log(h, step=step)
if step % a.save_every == 0:
save("ckpt_last.pt")
save("ckpt_last.pt"); save(f"ckpt_s{a.steps}.pt")
hf.close()
print("[train_tdmpc2] done", flush=True)
if __name__ == "__main__":
main()
|