File size: 22,714 Bytes
d18db74 | 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 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 | #!/usr/bin/env python
"""IFQL (implicit flow Q-learning) on an rsm_rise RISE task -- gen_q#264, the flagship baseline.
IFQL is the flow variant of IDQL: a flow-matching BC actor (unweighted) plus an IQL expectile critic with
an HL-Gauss two-hot value head; at action time it draws `num_samples` noises, integrates the flow with
`flow_steps` Euler steps and takes the arg-max Q. The agent itself is the VERBATIM ogbench_plus
implementation, vendored under impls/ (`impls/agents/ifql.py`, md5 a6152bff6837e24f2bf63fef36fbb0b6 ==
the upstream file); nothing in this script changes its losses, its network shapes or its defaults. What
this script supplies is the rsm_rise data loader, the fairness constants and the export.
OBSERVATION (primary variant, `--obs dino`): the pooled frozen-DINOv2 state of the CURRENT frame --
[agentview CLS|GeM (768) | wrist CLS|GeM (768) | eef_pos(3) eef_quat(4) gripper_qpos(2)] = 1545 -- z-scored
with the Stage-1 cache's feat_stats.npz, i.e. the EXACT input our successor scorer sees
(cache/<task>/{z.f16.npy,proprio.f32.npy,feat_stats.npz}, robomimic/algo/rsm_scorer.PooledDinoState).
`--obs pixels` is the secondary variant: the two 84x84 cameras stacked on the channel axis plus proprio,
encoded by ifql's own `impala_small` (needs --hdf5 and is much slower; not used for the paper numbers).
ACTION: the 7-d executed action of that frame (cache/<task>/act.f32.npy), single step, exactly as
published -- the flow actor is a per-step actor, not a chunked one.
REWARD (fairness rule, same as every other column of the flagship table): the binary data-provenance
label, 1 on every frame of an episode that came from the expert file and 0 on every frame of a
suboptimal/play episode. It is read from the source HDF5's `rewards` (constant within an episode; the
script asserts that) and cross-checked against the cache's own ep_success.
VALUE SCALE. IFQL's value head is HL-Gauss over the FIXED support [0, 1] (impls/utils/loss_utils.py:
HL_GAUSS_MIN_VALUE=0, HL_GAUSS_MAX_VALUE=1), because upstream rewards are sparse-at-goal so that
V in [0,1]. Our provenance reward is DENSE (1 on every expert frame), so the raw n-step return
sum_{k<200} gamma^k r is ~200 and every expert state would clip to the top bin -- a constant critic with
no ranking at all. The reward is therefore multiplied by (1 - discount) (`--reward-scale auto`), which is
a strictly monotone rescaling of the identical reward signal: the fixed point becomes
V = (1-gamma) * E[sum gamma^k r] in [0, 1], i.e. the discounted AVERAGE provenance label = "how expert-like
does the future from here look", the same quantity the RSM membership head estimates. Rankings are
unchanged by the rescale, so the fairness rule ("same reward as every other method") is preserved; only
the axis the two-hot head has to represent changes. `--reward-scale 1.0` restores the raw sum for a
control.
n-STEP RETURNS: computed inside each episode exactly as impls/utils/datasets.Dataset.get_n_step_returns
(stop at the episode's last frame, bootstrap from the frame `steps-1` ahead).
TERMINAL CONVENTION (`--terminal`, default `truncate`): a demonstration ends because the demonstration
ends, not because the MDP reached an absorbing state, so the last transition is TRUNCATED and keeps
masks = 1, bootstrapping off the final observation -- the standard convention, and the one ogbench uses
for its own non-goal-reaching trajectories. That is also what makes the value usable here: it puts the
fixed point at V = r, so V spans the whole HL-Gauss support [0, 1]. Treating the end as a true terminal
(`--terminal terminate`, masks = 0) instead caps the return at (1 - gamma^L) ~= 0.023-0.036 for our
230-370-frame episodes at gamma = 0.9999, which is 2-4 of the 101 bins: the provenance gap survives but
the differences between 128 candidate actions at one state fall below one bin and the critic cannot rank
at all. Every run records its realised Q/V range in IFQL.json (`value_spread.q_range_in_bins`) so this
is checkable rather than assumed.
STEP BUDGET: `--steps` gradient steps at IFQL's own batch size 256. Our RISE/IDQL policies (S0A,
S0Aidql) train for num_epochs=5000 x epoch_every_n_steps=100 = 500 000 gradient steps at batch 64, so
--steps 500000 matches them step for step (and gives IFQL 4x their sample presentations).
RESUME: these runs sit on the PREEMPTABLE queue and LSF requeues a preempted job, so the trainer writes
a rolling `params_latest.pkl` + `resume.json` every `--resume-every` steps (25 000, ~2 min of work) and
continues from it on restart. Without that a preemption threw away up to the whole 500k-step run -- 5 of
the first 21 trainings restarted from step 1 before this existed. `train.seed` still fixes the network
initialisation, so a resumed run is the SAME arm; only the batch order after the restart differs, and the
data rng is re-seeded with (seed, start_step) so the resumed run does not replay batches it already saw.
`--no-resume` ignores the rolling checkpoint.
OUTPUT (--out): params_<step>.pkl (flax state dict, for resuming / re-export) and, at the end,
`ifql_bundle.pt` -- a TORCH file holding every weight as a plain numpy array plus the config and the
feat_stats path. Eval runs inside the RISE robomimic env, whose python has no JAX, so both the critic
backend (robomimic/algo/ifql_torch.py) and the flow actor read that bundle in torch. Numerical parity of
the two implementations is asserted by scripts/ifql_parity.py.
usage (LSF only -- never on the login node):
scripts/rr_ifql.sh <task> <seed> [extra train_ifql.py args]
"""
from __future__ import annotations
import argparse
import json
import os
import pickle
import sys
import time
from pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE / "impls")) # so `utils.*` / `agents.*` resolve as upstream expects
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
SD_FLOOR_DEFAULT, Z_CLIP_DEFAULT = 0.01, 10.0
# --------------------------------------------------------------------------- data
def load_cache(cache: Path, hdf5: str | None, verbose=True):
"""The DINO cache of one task -> (x [N,1545] float32 z-scored, a [N,7], rewards [N], ep_from, ep_to)."""
meta = np.load(cache / "meta.npz", allow_pickle=True)
ep_from, ep_to = np.asarray(meta["ep_from"]), np.asarray(meta["ep_to"])
ep_succ = np.asarray(meta["ep_success"]).astype(np.float32)
ep_src = [str(s) for s in np.asarray(meta["ep_src"])]
z = np.load(cache / "z.f16.npy", mmap_mode="r")
pr = np.load(cache / "proprio.f32.npy", mmap_mode="r")
a = np.load(cache / "act.f32.npy").astype(np.float32)
n = z.shape[0]
assert pr.shape[0] == n == a.shape[0], (z.shape, pr.shape, a.shape)
feat = np.concatenate([np.asarray(z, np.float32), np.asarray(pr, np.float32)], 1)
st = np.load(cache / "feat_stats.npz")
mu, sd = np.asarray(st["mu"], np.float32), np.asarray(st["sd"], np.float32)
sd_floor, z_clip = SD_FLOOR_DEFAULT, Z_CLIP_DEFAULT
if "sd_floor" in st.files:
sd_floor = float(st["sd_floor"])
if "z_clip" in st.files:
z_clip = float(st["z_clip"])
pack = cache / "PACK.json"
if pack.is_file():
pk = json.loads(pack.read_text())
sd_floor = float(pk.get("sd_floor", sd_floor))
z_clip = float(pk.get("z_clip", z_clip))
x = (feat - mu) / np.maximum(sd, sd_floor)
if z_clip and z_clip > 0:
x = np.clip(x, -z_clip, z_clip)
x = x.astype(np.float32)
# ---- provenance reward, from the SOURCE hdf5 (`rewards`), laid out in cache frame order -------------
src = hdf5 or json.loads((cache / "PACK.json").read_text())["src"]
rew = np.zeros(n, np.float32)
import h5py
with h5py.File(src, "r") as f:
for k, i0, i1 in zip(ep_src, ep_from, ep_to):
r = np.asarray(f[f"data/{k}/rewards"], np.float32)
L = int(i1 - i0)
assert len(r) >= L, f"{k}: hdf5 has {len(r)} rewards, cache wants {L}"
u = np.unique(r[:L])
assert u.size == 1, f"{k}: rewards are not constant over the episode ({u[:5]}) -- the "
rew[i0:i1] = float(u[0])
# cross-check against the cache's own episode label (rewards.max() > 0)
got = np.array([rew[i0] > 0 for i0 in ep_from], np.float32)
assert np.array_equal(got, (ep_succ > 0).astype(np.float32)), "hdf5 rewards disagree with meta.ep_success"
if verbose:
print(f"[ifql] {n} frames, {len(ep_from)} episodes, {int(got.sum())} expert-provenance "
f"({100 * got.mean():.1f}%), state {x.shape[1]}-d, action {a.shape[1]}-d", flush=True)
return x, a, rew, ep_from.astype(np.int64), ep_to.astype(np.int64)
class EpisodeDataset:
"""n-step transitions over episodes laid end to end, matching impls/utils/datasets.Dataset.
TERMINAL CONVENTION (`terminal`), which decides what the value function can even represent here:
"truncate" (default, and the faithful reading of the published agent). A robomimic demonstration
ends because the demonstration ends, not because the MDP reached an absorbing state -- that is
truncation, and the standard convention, which ogbench also follows, is masks = 1 for a truncated
transition, bootstrapping from the final observation. The Bellman fixed point at the last frame is
then V = (1-gamma) r + gamma V => V = r, so V(s) is the probability that the future from s looks
like expert data and spans the whole HL-Gauss support [0, 1]. This is exactly the quantity the RSM
membership head estimates, which is what makes the two columns comparable.
"terminate". masks = 0 on the last frame, so the return is the truncated sum
sum_{k<L-t} gamma^k (1-gamma) r ~= (1 - gamma^(L-t)) r. With the published gamma = 0.9999 and our
230-370-frame episodes that is at most 0.023-0.036, i.e. the ENTIRE value range occupies 2-4 of the
101 HL-Gauss bins (bin width 0.0099, target sigma 0.0074). The provenance gap is still just about
representable, but the differences BETWEEN 128 candidate actions at one state -- which is the only
thing the ranking uses -- fall below one bin, so the critic is crippled as a ranker for a reason
that has nothing to do with IFQL. Kept only as a control.
"""
def __init__(self, x, a, r, ep_from, ep_to, discount, n_step, reward_scale, terminal="truncate"):
self.x, self.a = x, a
self.r = (r * float(reward_scale)).astype(np.float32)
self.size = x.shape[0]
self.discount, self.n_step = float(discount), int(n_step)
self.terminal = terminal
term = np.empty(self.size, np.int64)
masks = np.ones(self.size, np.float32)
nxt = np.arange(self.size, dtype=np.int64)
for i0, i1 in zip(ep_from, ep_to):
term[i0:i1] = i1 - 1
if terminal == "terminate":
masks[i1 - 1] = 0.0
nxt[i0:i1] = np.minimum(np.arange(i0, i1) + 1, i1 - 1)
self.term, self.masks, self.next_idx = term, masks, nxt
def sample(self, batch_size, rng):
idxs = rng.integers(0, self.size, size=batch_size)
term = self.term[idxs]
steps = np.minimum(self.n_step, term - idxs + 1).astype(np.int32)
offs = np.arange(self.n_step)
ridx = np.minimum(idxs[:, None] + offs[None, :], term[:, None])
valid = offs[None, :] < steps[:, None]
rd = (self.discount ** offs).astype(np.float32)
n_step_rewards = (self.r[ridx] * valid * rd).sum(1).astype(np.float32)
bootstrap = np.where(valid, self.masks[ridx], 1.0).prod(1).astype(np.float32)
discounts = ((self.discount ** steps) * bootstrap).astype(np.float32)
boot = idxs + steps - 1 # the frame we bootstrap FROM
return dict(
observations=self.x[idxs],
actions=self.a[idxs],
next_observations=self.x[self.next_idx[boot]],
rewards=n_step_rewards,
discounts=discounts,
masks=bootstrap,
)
# --------------------------------------------------------------------------- export
def _to_numpy_tree(t):
import jax
return jax.tree_util.tree_map(lambda v: np.asarray(v), t)
def flatten_params(params, prefix=""):
"""nested flax params -> {'a/b/c': ndarray}"""
out = {}
for k, v in params.items():
key = f"{prefix}{k}"
if hasattr(v, "items"):
out.update(flatten_params(v, key + "/"))
else:
out[key] = np.asarray(v)
return out
def export_bundle(agent, cfg, out_path, feat_stats, task, seed, step, obs_mode):
import torch
flat = flatten_params(_to_numpy_tree(agent.network.params))
bundle = {
"kind": "ifql_bundle_v1",
"params": {k: torch.from_numpy(np.asarray(v, np.float32)) for k, v in flat.items()},
"config": {k: (list(v) if isinstance(v, tuple) else v) for k, v in dict(cfg).items()},
"feat_stats": str(feat_stats),
"task": task, "seed": int(seed), "step": int(step), "obs_mode": obs_mode,
"hl_gauss": {"num_bins": 101, "min": 0.0, "max": 1.0, "sigma_ratio": 0.75},
"source": "rsm_rise/code/ifql/train_ifql.py (gen_q#264)",
}
os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
tmp = str(out_path) + ".tmp"
torch.save(bundle, tmp)
os.replace(tmp, out_path)
print(f"[ifql] exported {len(flat)} arrays -> {out_path}", flush=True)
return sorted(flat)
# --------------------------------------------------------------------------- main
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--task", required=True)
ap.add_argument("--cache", default="", help="default cache/<task>")
ap.add_argument("--hdf5", default="", help="source hdf5 for `rewards` (default: the cache's PACK.json src)")
ap.add_argument("--out", required=True)
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--steps", type=int, default=500_000,
help="gradient steps; 500000 = S0A/S0Aidql's 5000 epochs x 100 steps/epoch")
ap.add_argument("--obs", default="dino", choices=["dino", "pixels"])
ap.add_argument("--num-samples", type=int, default=128,
help="candidate budget at action time (ifql default 32; the flagship uses 128)")
ap.add_argument("--terminal", default="truncate", choices=["truncate", "terminate"],
help="how an episode's last frame is treated; see EpisodeDataset. 'truncate' "
"(default) bootstraps from the final observation, so V spans [0,1]")
ap.add_argument("--reward-scale", default="auto",
help="'auto' = (1 - discount) so the HL-Gauss [0,1] support holds the value of a DENSE "
"provenance reward; a float overrides it")
ap.add_argument("--save-every", type=int, default=100_000)
ap.add_argument("--resume-every", type=int, default=25_000,
help="overwrite the rolling resume checkpoint every N steps. These runs sit on the "
"PREEMPTABLE queue and the job is requeued on preemption, so without a resume a "
"kill throws away up to the whole 500k-step run -- 5 of the first 21 trainings "
"restarted from step 1 before this existed. 0 disables it.")
ap.add_argument("--no-resume", action="store_true",
help="ignore any rolling checkpoint and start from step 1")
ap.add_argument("--log-every", type=int, default=5_000)
ap.add_argument("--wandb-name", default="")
ap.add_argument("--set", action="append", default=[], help="override an ifql get_config() key: k=v")
a = ap.parse_args()
cache = Path(a.cache or (ROOT / "cache" / a.task))
out = Path(a.out); out.mkdir(parents=True, exist_ok=True)
if a.obs != "dino":
raise SystemExit("--obs pixels is the secondary variant and is not wired in this script yet; "
"it needs the hdf5 image loader, not the DINO cache (see the module docstring)")
import jax, jax.numpy as jnp
print(f"[ifql] jax {jax.__version__} devices={jax.devices()}", flush=True)
from agents.ifql import IFQLAgent, get_config
cfg = get_config()
cfg["num_samples"] = int(a.num_samples)
for kv in a.set:
k, v = kv.split("=", 1)
cur = cfg[k]
cfg[k] = type(cur)(v) if not isinstance(cur, bool) else v.lower() in ("1", "true", "yes")
rs = (1.0 - float(cfg["discount"])) if a.reward_scale == "auto" else float(a.reward_scale)
x, act, rew, ep_from, ep_to = load_cache(cache, a.hdf5 or None)
ds = EpisodeDataset(x, act, rew, ep_from, ep_to, cfg["discount"], cfg["n_step"], rs,
terminal=a.terminal)
print(f"[ifql] reward_scale={rs:g} discount={cfg['discount']} expectile={cfg['expectile']} n_step={cfg['n_step']} "
f"terminal={a.terminal} batch={cfg['batch_size']} steps={a.steps} "
f"num_samples={cfg['num_samples']}", flush=True)
rng = np.random.default_rng(a.seed)
b0 = ds.sample(4, rng)
agent = IFQLAgent.create(a.seed, b0["observations"], b0["actions"], cfg)
# ---- RESUME (rolling checkpoint) --------------------------------------------------------------
# `train.seed` still defines the network initialisation, so the resumed run is the same arm; only the
# BATCH ORDER differs after a restart, which is a sampling stream and not a result-defining seed.
# The data rng is re-seeded with (seed, start_step) so a resumed run does not replay the batches it
# already consumed.
from utils.flax_utils import save_resume_checkpoint, restore_agent_file, LATEST_PARAMS, RESUME_STATE
start = 1
_latest, _rstate = out / LATEST_PARAMS, out / RESUME_STATE
if not a.no_resume and _latest.is_file() and _rstate.is_file():
try:
_st = json.loads(_rstate.read_text())
_k = int(_st["step"])
if 0 < _k < a.steps:
agent = restore_agent_file(agent, str(_latest))
start = _k + 1
rng = np.random.default_rng([a.seed, _k])
print(f"[ifql] RESUMED from {_latest} at step {_k} -> continuing at {start}/{a.steps}",
flush=True)
elif _k >= a.steps:
print(f"[ifql] rolling checkpoint is already at step {_k} >= {a.steps}; "
f"restoring it and skipping straight to the export", flush=True)
agent = restore_agent_file(agent, str(_latest))
start = a.steps + 1
except Exception as e:
print(f"[ifql] rolling checkpoint unusable ({e!r}) -- starting from step 1", flush=True)
wb = None
if a.wandb_name and os.environ.get("RSM_WANDB_ENTITY"):
try:
import wandb
wb = wandb.init(entity=os.environ["RSM_WANDB_ENTITY"].split("/")[0],
project=os.environ.get("RSM_WANDB_PROJECT", "rsm_rise"),
name=a.wandb_name, group=a.task, config=dict(cfg), reinit=True)
except Exception as e:
print(f"[ifql] wandb off ({e!r})", flush=True)
t0 = time.time()
for step in range(start, a.steps + 1):
batch = ds.sample(cfg["batch_size"], rng)
agent, info = agent.update(batch)
if step % a.log_every == 0 or step == 1:
info = {k: float(v) for k, v in info.items()}
el = time.time() - t0
_done = step - start + 1
_rate = _done / max(el, 1e-6)
print(f"[ifql] step {step}/{a.steps} ({_rate:.0f} it/s, eta "
f"{(a.steps - step) / max(_rate, 1e-6) / 60:.1f} min) "
+ " ".join(f"{k}={v:.4f}" for k, v in sorted(info.items())), flush=True)
if wb is not None:
wb.log(info, step=step)
if a.resume_every and (step % a.resume_every == 0) and step != a.steps:
save_resume_checkpoint(agent, str(out), step)
if step % a.save_every == 0 or step == a.steps:
import flax
os.makedirs(out, exist_ok=True)
with open(out / f"params_{step}.pkl", "wb") as f:
pickle.dump({"agent": flax.serialization.to_state_dict(agent)}, f)
keys = export_bundle(agent, cfg, out / "ifql_bundle.pt", cache / "feat_stats.npz",
a.task, a.seed, a.steps, a.obs)
try:
diag = ds.sample(4096, np.random.default_rng(12345))
q_diag = np.asarray(agent.network.select("critic")(diag["observations"], actions=diag["actions"]))
v_diag = np.asarray(agent.network.select("value")(diag["observations"]))
q_diag = q_diag.mean(0) if q_diag.ndim > 1 else q_diag
value_spread = {
"q_min": float(q_diag.min()), "q_max": float(q_diag.max()), "q_mean": float(q_diag.mean()),
"q_std": float(q_diag.std()), "v_min": float(v_diag.min()), "v_max": float(v_diag.max()),
"hl_gauss_bin_width": 1.0 / 101,
"q_range_in_bins": float((q_diag.max() - q_diag.min()) * 101),
"note": "Q/V over 4096 logged transitions. q_range_in_bins << 10 means the two-hot head "
"has almost no resolution left for ranking candidates at one state (see --terminal).",
}
except Exception as e:
value_spread = {"error": repr(e)}
print(f"[ifql] value spread: {value_spread}", flush=True)
(out / "IFQL.json").write_text(json.dumps({
"task": a.task, "seed": a.seed, "steps": a.steps, "obs": a.obs,
"config": {k: (list(v) if isinstance(v, tuple) else v) for k, v in dict(cfg).items()},
"reward_scale": rs, "reward": "binary data-provenance label (1 = expert file), from hdf5 `rewards`",
"terminal": a.terminal,
# VALUE SPREAD. The HL-Gauss head can only rank as finely as its bins: if the realised Q range
# covers a couple of the 101 bins, the critic cannot separate 128 candidate actions at one state
# whatever it learned. Recorded per run so the failure is visible in the artefact rather than
# having to be inferred from the loss curves.
"value_spread": value_spread,
"cache": str(cache), "feat_stats": str(cache / "feat_stats.npz"),
"step_budget_match": "500000 gradient steps = S0A/S0Aidql num_epochs 5000 x epoch_every_n_steps 100",
"param_keys": keys, "wall_time_s": time.time() - t0,
}, indent=2))
print(f"[ifql] done in {(time.time() - t0) / 60:.1f} min", flush=True)
if __name__ == "__main__":
main()
|