"""IS THE WORLD MODEL ACTUALLY BAD, OR IS `fid/obs_ratio_h1` MEASURING SAMPLING NOISE? `train_df.fidelity` (train_df.py:85) draws **one** diffusion sample, `n_plans=1`, and compares its RMSE against the truth to a **deterministic** stay-put control. That comparison is structurally biased against any stochastic predictor: for a PERFECTLY CALIBRATED sampler whose posterior equals the truth's, E||x_sample - x_true||^2 = ||E[x] - x_true||^2 + Var(x_sample) = 2 * Var, while the best deterministic predictor scores only `Var`. So a flawless generative model plateaus at ratio sqrt(2) = 1.414 against a stay-put control of the same quality -- and threading plateaus at 1.51. This script separates the two terms. For K in {1,2,4,8,16,64} it averages K independent samples from the SAME conditioning state and re-measures the RMSE, giving mse(K) = bias2 + var/K (the Monte-Carlo law) so a straight line in 1/K reads off `bias2` (the model's real error, K -> inf) and `var` (the sampling noise the old metric was charging to the model). Reported per horizon: ratio_K1 the old number, for continuity ratio_Kmax the posterior-mean estimate against the same stay-put control ratio_inf the 1/K -> 0 extrapolation, i.e. the model's dynamics error with sampling noise removed var_frac var / mse(1), the fraction of the old metric that was sampling noise If ratio_inf < 1 the model DOES beat stay-put and "the world model has no short-horizon dynamics" (FINDING A/B's premise) is an artifact of the instrument. If ratio_inf >= 1 the model is genuinely worse than standing still and the diagnosis stands. Either way the number is decisive, and it costs one GPU-minute rather than a 100k-step training run. """ from __future__ import annotations import argparse, json, os, sys import numpy as np import torch sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from df_data import DFCacheData, OBS_DIM # noqa: E402 from df_probe import load_df # noqa: E402 from df_plan import plan_bundles # noqa: E402 from train_df import split_window # noqa: E402 (one definition of the window layout) @torch.no_grad() def main(): p = argparse.ArgumentParser() p.add_argument("--ckpt", required=True) p.add_argument("--cache", required=True) p.add_argument("--out", required=True) p.add_argument("--n-states", type=int, default=64) p.add_argument("--kmax", type=int, default=64) p.add_argument("--seed", type=int, default=0) a = p.parse_args() dev = "cuda" if torch.cuda.is_available() else "cpu" model, meta, step = load_df(a.ckpt, dev) data = DFCacheData(a.cache, frame_stack=int(meta["frame_stack"]), n_tokens=int(meta["n_tokens"]), seed=int(meta.get("seed", 0))) rng = np.random.default_rng(a.seed) # The window layout is the checkpoint's own, read out of its meta, so a --cond-history model is # measured through the conditioning it was trained with and a default model is bit-identical to # every number already in status/nb/df_fidmean/. align = str(meta.get("act_align", "ours")) cond_history = int(meta.get("cond_history", 0)) bundle, mask = data.sample(a.n_states, rng, split="val", device=dev) cond_obs, body, m = split_window(bundle, mask, int(meta["frame_stack"]), align, cond_history) T = body.shape[0] init_obs = cond_obs if cond_obs.dim() == 2 else cond_obs[:, -1] # stay-put control true_obs = body[:, :, :OBS_DIM] # [T, B, C] # one draw of KMAX samples per state; every K is a prefix of it, so all K share the same draws plan = plan_bundles(model, cond_obs, horizon_frames=T, guidance_scale=0.0, gamma=0.0, n_plans=a.kmax, device=dev)["plan"][..., :OBS_DIM] # [T, B, K, C] Ks = [k for k in (1, 2, 4, 8, 16, 64) if k <= a.kmax] horizons = [1, 2, 4, 8, 10, 20, 50] res = dict(ckpt=a.ckpt, cache=a.cache, step=step, n_states=int(a.n_states), kmax=a.kmax, frame_stack=int(meta["frame_stack"]), chan_share=meta.get("chan_share", ""), act_align=align, cond_history=cond_history, beta_schedule=str(meta.get("beta_schedule", "linear")), objective=str(meta.get("objective", "pred_x0")), n_tokens=int(meta.get("n_tokens", -1)), seed=int(meta.get("seed", 0)), train_steps=int(meta.get("steps", -1)), Ks=Ks, per_h={}) for H in horizons: h = min(H, T) - 1 if h < 0 or m[h].sum() == 0: continue w = m[h].bool() tgt = true_obs[h][w] # [b, C] naive = ((init_obs[w] - tgt) ** 2).mean(-1).mean().item() # MSE, stay-put row = {"naive_mse": naive, "naive_rmse": naive ** 0.5, "mse": {}, "rmse": {}, "ratio": {}} for K in Ks: pm = plan[h][w][:, :K, :].mean(1) # posterior-mean estimate over K draws mse = ((pm - tgt) ** 2).mean(-1).mean().item() row["mse"][str(K)] = mse row["rmse"][str(K)] = mse ** 0.5 row["ratio"][str(K)] = (mse ** 0.5) / max(naive ** 0.5, 1e-8) # mse(K) = bias2 + var/K -> least squares in x = 1/K x = np.array([1.0 / K for K in Ks]); y = np.array([row["mse"][str(K)] for K in Ks]) A = np.stack([np.ones_like(x), x], 1) bias2, var = np.linalg.lstsq(A, y, rcond=None)[0] bias2 = float(max(bias2, 0.0)); var = float(max(var, 0.0)) row["bias2"] = bias2 row["var"] = var row["ratio_inf"] = (bias2 ** 0.5) / max(naive ** 0.5, 1e-8) row["var_frac"] = var / max(row["mse"]["1"], 1e-12) # the sqrt(2) prediction: a calibrated sampler with bias2 == naive would sit here row["fit_resid"] = float(np.abs(A @ np.array([bias2, var]) - y).max()) res["per_h"][str(H)] = row os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True) with open(a.out, "w") as f: json.dump(res, f, indent=1) for H, r in res["per_h"].items(): print(f"h{H:>3s} naive {r['naive_rmse']:.4f} | ratio K=1 {r['ratio']['1']:.3f} " f"K={Ks[-1]} {r['ratio'][str(Ks[-1])]:.3f} inf {r['ratio_inf']:.3f} " f"| var_frac {r['var_frac']:.3f} resid {r['fit_resid']:.2e}") print("[df_fidmean] wrote", a.out) if __name__ == "__main__": main()