rsm_rise_code / code_src /tdmpc2_rise /td_fidelity.py
rli14's picture
rsm_rise code snapshot (HF_PUSH_ALL) (part 5)
1c78d11 verified
Raw History Blame Contribute Delete
5.63 kB
"""gen_q#274: TD-MPC2 rollout fidelity AT THE HORIZON OF THE ROW IT IS PUBLISHED BESIDE.
WHY THIS IS A SEPARATE SCRIPT AND NOT MORE `--fid-horizons`. `train_tdmpc2.evaluate` draws ONE
window set of length max(fid_hs)+1 and computes BOTH the fidelity and the Q-head diagnostics on it.
Raising its horizons to 100 would therefore silently restrict `val/q_auc`, `val/q_std` and
`val/reward_auc` to episodes of >= 101 frames -- the health numbers that gate the whole column would
quietly change their population. So the trainer keeps its short, cheap, fixed window, and the
row-horizon fidelity is measured here, after training, with a POOL OF ITS OWN PER HORIZON and the
window count reported next to every number.
WHAT IT REPORTS, per horizon h (in FRAMES; a TD-MPC2 latent step is one frame):
lat_rmse_h ||roll_h(z0, a_0..h-1) - enc(o_h)||_2 , mean over windows
lat_rmse_h_naive ||z0 - enc(o_h)||_2 on the SAME windows -- the stay-put predictor
lat_ratio_h their quotient. >= 1 means the rollout carries no information about the
true future and any score at that horizon must be flagged, exactly as the
DF screen's obs_ratio is (status/NEW_BASELINES_DONE, DF world-model screen).
n_windows / n_episodes_long_enough / frac_val_episodes_usable
the coverage. An H that no held-out episode is long enough to reach reports
`null` and the reason, never a number from a short-episode subsample.
This is a LATENT fidelity: TD-MPC2's world model is implicit and has no observation decoder, so it
is NOT comparable with Diffusion Forcing's observation-space RMSE. Both are reported; they are
never put in one column (docs/tex/new_baselines_controls.tex says so too).
usage: td_fidelity.py --ckpt <ckpt.pt> --cache <cache/<task>> --out <json>
[--horizons 10,20,50,100,200] [--windows 256] [--device cpu] [--seed 0]
"""
from __future__ import annotations
import argparse, json, sys
from pathlib import Path
import numpy as np
import torch
sys.path.insert(0, str(Path(__file__).resolve().parent))
from td_backend import load_td_world_model # noqa: E402
from td_corpus import TDCorpus # noqa: E402
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--ckpt", required=True)
ap.add_argument("--cache", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--horizons", default="10,20,50,100,200")
ap.add_argument("--windows", type=int, default=256)
ap.add_argument("--device", default="cpu")
ap.add_argument("--seed", type=int, default=0)
a = ap.parse_args()
hs = sorted({int(x) for x in a.horizons.split(",") if x})
m, cfg, gamma, step, train_cache = load_td_world_model(a.ckpt, a.device)
# the corpus is built at the TRAINING horizon so the train/val split is the one the model was
# trained under; only the window LENGTH varies below, per horizon.
corpus = TDCorpus(a.cache, horizon=int(cfg.horizon), seed=a.seed)
rng = np.random.default_rng(a.seed)
n_val = len(corpus.val_eps)
ep_len = corpus.d.ep_len
res = {"ckpt": str(a.ckpt), "cache": str(a.cache), "train_cache": str(train_cache),
"gamma": gamma, "H_of_gamma": (1.0 / (1.0 - gamma)) if gamma < 1 else None,
"train_step": step, "latent_dim": int(cfg.latent_dim), "train_horizon": int(cfg.horizon),
"n_val_episodes": int(n_val), "windows_requested": int(a.windows), "horizons": {}}
if str(a.cache).rstrip("/") != str(train_cache).rstrip("/") and train_cache:
res["CACHE_MISMATCH"] = f"checkpoint was trained on {train_cache}"
for h in hs:
pool = [e for e in corpus.val_eps if ep_len[e] >= h + 1]
row = {"n_episodes_long_enough": len(pool),
"frac_val_episodes_usable": (len(pool) / n_val) if n_val else None}
if not pool:
row.update({"lat_rmse": None, "lat_rmse_naive": None, "lat_ratio": None,
"n_windows": 0,
"reason": f"no held-out episode reaches {h + 1} frames; this horizon "
f"cannot be measured on this task and no number is reported"})
res["horizons"][str(h)] = row
print(f"[td_fid] h={h}: NO WINDOWS ({len(pool)}/{n_val} episodes long enough)", flush=True)
continue
wins = corpus.val_episode_rows(a.windows, rng, min_len=h + 1)
O = np.stack([corpus.d.obs_rows(r) for r, _ in wins], 1) # [h+1, n, 1545]
A = np.stack([np.asarray(corpus.d.act[r[:-1]], np.float32) for r, _ in wins], 1)
O = torch.from_numpy(O).to(a.device); A = torch.from_numpy(A).to(a.device)
with torch.no_grad():
z0 = m.encode(O[0], None)
z = z0.clone()
for t in range(h):
z = m.next(z, A[t], None)
zt = m.encode(O[h], None)
e = float((z - zt).norm(dim=-1).mean())
nv = float((z0 - zt).norm(dim=-1).mean())
row.update({"lat_rmse": e, "lat_rmse_naive": nv, "lat_ratio": e / max(nv, 1e-8),
"n_windows": len(wins)})
res["horizons"][str(h)] = row
print(f"[td_fid] h={h:4d} rmse {e:.4f} naive {nv:.4f} ratio {e / max(nv, 1e-8):.3f} "
f"n={len(wins)} windows from {len(pool)}/{n_val} val episodes", flush=True)
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
Path(a.out).write_text(json.dumps(res, indent=2))
print(f"[td_fid] wrote {a.out}", flush=True)
if __name__ == "__main__":
main()