rsm_rise code snapshot (HF_PUSH_ALL)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- README.md+1-1
- code_src/df_rise/_deps/PROVENANCE.txtAdded+22
- code_src/df_rise/_deps/rotary_embedding_torch/__init__.pyAdded+6
- code_src/df_rise/_deps/rotary_embedding_torch/flash_attn_with_rotary.pyAdded+597
- code_src/df_rise/_deps/rotary_embedding_torch/flash_fused_rotary.pyAdded+529
- code_src/df_rise/_deps/rotary_embedding_torch/rotary_embedding_torch.pyAdded+350
- code_src/df_rise/df_actprobe.pyAdded+132
- code_src/df_rise/df_core.pyAdded+242
- code_src/df_rise/df_data.pyAdded+145
- code_src/df_rise/df_fidmean.pyAdded+118
- code_src/df_rise/df_guid_l2.pyAdded+112
- code_src/df_rise/df_idm.pyAdded+457
- code_src/df_rise/df_idm_probe.pyAdded+231
- code_src/df_rise/df_plan.pyAdded+200
- code_src/df_rise/df_policy.pyAdded+432
- code_src/df_rise/df_poolcmp.pyAdded+156
- code_src/df_rise/df_poolcmp2.pyAdded+464
- code_src/df_rise/df_probe.pyAdded+164
- code_src/df_rise/df_value.pyAdded+241
- code_src/df_rise/smoke_df_plan.pyAdded+195
- code_src/df_rise/train_df.pyAdded+325
- code_src/ifql/impls/__init__.pyAdded
- code_src/ifql/impls/agents/__init__.pyAdded
- code_src/ifql/impls/agents/ifql.pyAdded+285
- code_src/ifql/impls/utils/__init__.pyAdded
- code_src/ifql/impls/utils/encoders.pyAdded+108
- code_src/ifql/impls/utils/flax_utils.pyAdded+337
- code_src/ifql/impls/utils/loss_utils.pyAdded+56
- code_src/ifql/impls/utils/networks.pyAdded+378
- code_src/ifql/train_ifql.pyAdded+395
- code_src/rise_code/README.mdAdded+84
- code_src/rise_code/environment.yamlAdded+50
- code_src/rise_code/scripts/collect_human_demonstrations.pyAdded+4
- code_src/rise_code/scripts/combine_datasets.pyAdded+4
- code_src/rise_code/scripts/dataset_states_to_obs.pyAdded+4
- code_src/rise_code/scripts/eval.pyAdded+4
- code_src/rise_code/scripts/playback_dataset.pyAdded+4
- code_src/rise_code/scripts/train_robomimic.pyAdded+4
- code_src/rise_code/setup.pyAdded+8
- code_src/rise_code/sim_pipeline/__init__.pyAdded+35
- code_src/rise_code/sim_pipeline/configs/__init__.pyAdded
- code_src/rise_code/sim_pipeline/configs/_data_collection/data_collection.pyAdded+47
- code_src/rise_code/sim_pipeline/configs/_data_summary/data_summary.pyAdded+6
- code_src/rise_code/sim_pipeline/configs/_diffusion/base_diffusion.pyAdded+14
- code_src/rise_code/sim_pipeline/configs/_diffusion/diffusion_image.pyAdded+14
- code_src/rise_code/sim_pipeline/configs/_diffusion/tycho_diffusion.pyAdded+14
- code_src/rise_code/sim_pipeline/configs/_discriminator/robomimic_discriminator.pyAdded+15
- code_src/rise_code/sim_pipeline/configs/_env_configs/ood_pushing.pyAdded+10
- code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/hook_expert_lowdim.pyAdded+14
- code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/pushing_expert_lowdim.pyAdded+14
8 unmodified lines91011121314158 unmodified lines| folder | what it is ||---|---|| `gen_q_rsm/` | `git archive` of github.com/williamd4112/gen_q, branch `rsm_rise_data`, commit `1c1e6d32273b541e41229609b76f0f1acfb0efe7` (`rsm_libero/` = RSM trainer + scorer, `rsm_rise/pipeline/` = RISE glue, `rsm_rise/pipeline/hf_ckpt.py` = checkpoint fetcher) || `frozen/rsm_libero_freeze_20261002/` | the verbatim RSM code the flagship sim tables were produced with (FREEZE_COMMIT 95842af1); set `RSM_LIBERO_DIR` to it || `frozen/rsm_libero_rsmpi/` | RSM policy-iteration (RSM-pi) variant || `frozen/rsm_libero_snap_20261030/` | later RSM snapshot (2026-10-30, source only) |8 unmodified lines91011121314158 unmodified lines| folder | what it is ||---|---|| `gen_q_rsm/` | `git archive` of github.com/williamd4112/gen_q, branch `rsm_rise_data`, commit `9719bde3b01a3a1355e026648cdc55a8a552bc1b` (`rsm_libero/` = RSM trainer + scorer, `rsm_rise/pipeline/` = RISE glue, `rsm_rise/pipeline/hf_ckpt.py` = checkpoint fetcher) || `frozen/rsm_libero_freeze_20261002/` | the verbatim RSM code the flagship sim tables were produced with (FREEZE_COMMIT 95842af1); set `RSM_LIBERO_DIR` to it || `frozen/rsm_libero_rsmpi/` | RSM policy-iteration (RSM-pi) variant || `frozen/rsm_libero_snap_20261030/` | later RSM snapshot (2026-10-30, source only) |
12345678910111213141516171819202122gen_q#274 (stream NEW_BASELINES) -- why this directory exists.
The Diffusion Forcing PLANNER runs inside the RISE eval process, i.e. under $ROOT/env (python 3.10,torch 2.5.1), NOT under venv_df (python 3.12) where the DF trainer runs. The upstream import chain code/diffusion_forcing/algorithms/diffusion_forcing/models/diffusion.py:8 -> models/unet3d.py:6 -> `from rotary_embedding_torch import RotaryEmbedding`is unconditional, and $ROOT/env does not ship rotary_embedding_torch. That is exactly what killedevery DF eval cell in LSF 1880432 (ModuleNotFoundError, 3 retries per cell, all four slots).
Fix, chosen so that NO shared environment is mutated (the gen_q#273 stream trains in $ROOT/env andvenv_rsm; installing a package into either of them is not this stream's to do): rotary_embedding_torch 0.9.1 -- PURE PYTHON, deps torch + einops only, both already in $ROOT/env (torch 2.5.1 provides torch.amp.autocast; einops 0.8.2) -- copied verbatim from venv_df/lib/python3.12/site-packages/rotary_embedding_torch and put on sys.path ONLY inside eval.py's `if RR_DF_CKPT:` block, so a cell with RR_DF_CKPT unset still takes a byte-identical code path. No file in code/diffusion_forcing is edited.
NOTE ON SCIENCE: unet3d is not used by our port (our bundle is 1-D and uses the transformerbackbone); the import is merely on the module path. Supplying the real package rather than stubbingit keeps the vendored checkout honest -- if upstream code ever does reach RotaryEmbedding, it getsthe real implementation.copied 2026-09-23, source venv_df (pip install rotary_embedding_torch==0.9.1).123456from rotary_embedding_torch.rotary_embedding_torch import ( apply_rotary_emb, RotaryEmbedding, apply_learned_rotations, broadcat)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597import mathimport torchfrom torch import catfrom torch import Tensorfrom einops import rearrange, repeat
try: import triton import triton.language as tl TRITON_AVAILABLE = Trueexcept ImportError: TRITON_AVAILABLE = False triton = None tl = None
from rotary_embedding_torch.rotary_embedding_torch import rotate_half
# helpers
def exists(v): return v is not None
def default(v, d): return v if exists(v) else d
# reference flash attention
def reference_flash_attention( q, k, v, cos = None, sin = None, pos_mask = None, attn_mask = None, is_causal = True): device, dtype = q.device, q.dtype batch, heads_q, seq_len_q, dim = q.shape _, heads_kv, seq_len_k, _ = k.shape
if heads_q != heads_kv: groups = heads_q // heads_kv k = repeat(k, 'b h n d -> b (h g) n d', g = groups) v = repeat(v, 'b h n d -> b (h g) n d', g = groups)
# attention similarity
sim = torch.einsum('b h i d, b h j d -> b h i j', q, k)
# rotary embeddings
if exists(cos) and exists(sin): rot_dim = cos.shape[-1]
q_rot = (q[..., :rot_dim] * cos) + (rotate_half(q[..., :rot_dim]) * sin) k_rot = (k[..., :rot_dim] * cos) + (rotate_half(k[..., :rot_dim]) * sin)
q_rot = cat((q_rot, q[..., rot_dim:]), dim = -1) k_rot = cat((k_rot, k[..., rot_dim:]), dim = -1)
sim_rot = torch.einsum('b h i d, b h j d -> b h i j', q_rot, k_rot)
# apply positional mask if provided
if exists(pos_mask): is_pos_2d = torch.logical_and(pos_mask[:, None], pos_mask[None, :]) sim = torch.where(is_pos_2d, sim_rot, sim) else: sim = sim_rot
sim = sim * (dim ** -0.5)
# masks
if exists(attn_mask): sim = sim + attn_mask
if is_causal: causal_mask = torch.ones((seq_len_q, seq_len_k), device = device, dtype = torch.bool).tril() sim = torch.where(causal_mask, sim, float('-inf'))
# aggregate values
attn = sim.softmax(dim = -1)
return torch.einsum('b h i j, b h j d -> b h i d', attn, v)
def _dummy_kernel(*args, **kwargs): pass
# triton forward and backward kernels
if TRITON_AVAILABLE: @triton.autotune( configs=[ triton.Config({'BLOCK_M': 32, 'BLOCK_N': 32}, num_stages=2, num_warps=4), triton.Config({'BLOCK_M': 64, 'BLOCK_N': 32}, num_stages=1, num_warps=4), ], key=['N_CTX_Q', 'N_CTX_K', 'BLOCK_DMODEL'] ) @triton.jit def _flash_rotary_fwd_kernel( Q, K, V, sm_scale, Cos, Sin, Out, Lse, PosMask, AttnMask, stride_ab, stride_ah, stride_am, stride_an, stride_qm, stride_qh, stride_qn, stride_qk, stride_km, stride_kh, stride_kn, stride_kk, stride_vm, stride_vh, stride_vn, stride_vk, stride_cz, stride_ch, stride_cn, stride_ck, stride_om, stride_oh, stride_on, stride_ok, batch, q_heads, kv_heads, N_CTX_Q, N_CTX_K, BLOCK_DMODEL: tl.constexpr, ROTARY_DIM: tl.constexpr, IS_CAUSAL: tl.constexpr, HAS_POS_MASK: tl.constexpr, HAS_ATTN_MASK: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr ): start_m = tl.program_id(0) off_hz = tl.program_id(1)
off_z = off_hz // q_heads off_h = off_hz % q_heads off_h_kv = off_h // (q_heads // kv_heads)
q_offset = off_z * stride_qm + off_h * stride_qh k_offset = off_z * stride_km + off_h_kv * stride_kh v_offset = off_z * stride_vm + off_h_kv * stride_vh c_offset = off_z * stride_cz + off_h * stride_ch
offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) offs_n = tl.arange(0, BLOCK_N) offs_k = tl.arange(0, BLOCK_DMODEL)
q_ptrs = Q + q_offset + offs_m[:, None] * stride_qn + offs_k[None, :] * stride_qk q = tl.load(q_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < BLOCK_DMODEL), other=0.0)
offs_k_swapped = offs_k ^ 1 rot_sign = ((offs_k % 2) * 2 - 1)
q_swapped_ptrs = Q + q_offset + offs_m[:, None] * stride_qn + offs_k_swapped[None, :] * stride_qk q_swapped = tl.load(q_swapped_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < BLOCK_DMODEL), other=0.0)
cos_q_ptrs = Cos + c_offset + offs_m[:, None] * stride_cn + offs_k[None, :] * stride_ck sin_q_ptrs = Sin + c_offset + offs_m[:, None] * stride_cn + offs_k[None, :] * stride_ck cos_q = tl.load(cos_q_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < ROTARY_DIM), other=1.0) sin_q = tl.load(sin_q_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < ROTARY_DIM), other=0.0)
q_rot = q * cos_q + q_swapped * rot_sign[None, :] * sin_q
if HAS_POS_MASK: pos_m_ptrs = PosMask + offs_m pos_m = tl.load(pos_m_ptrs, mask=offs_m < N_CTX_Q, other=0).to(tl.int1)
m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf") l_i = tl.zeros([BLOCK_M], dtype=tl.float32) acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32)
for start_n in range(0, N_CTX_K, BLOCK_N): offs_n_curr = start_n + offs_n
k_ptrs = K + k_offset + offs_n_curr[None, :] * stride_kn + offs_k[:, None] * stride_kk k = tl.load(k_ptrs, mask=(offs_n_curr[None, :] < N_CTX_K) & (offs_k[:, None] < BLOCK_DMODEL), other=0.0)
k_swapped_ptrs = K + k_offset + offs_n_curr[None, :] * stride_kn + offs_k_swapped[:, None] * stride_kk k_swapped = tl.load(k_swapped_ptrs, mask=(offs_n_curr[None, :] < N_CTX_K) & (offs_k[:, None] < BLOCK_DMODEL), other=0.0)
cos_k_ptrs = Cos + c_offset + offs_n_curr[None, :] * stride_cn + offs_k[:, None] * stride_ck sin_k_ptrs = Sin + c_offset + offs_n_curr[None, :] * stride_cn + offs_k[:, None] * stride_ck cos_k = tl.load(cos_k_ptrs, mask=(offs_n_curr[None, :] < N_CTX_K) & (offs_k[:, None] < ROTARY_DIM), other=1.0) sin_k = tl.load(sin_k_ptrs, mask=(offs_n_curr[None, :] < N_CTX_K) & (offs_k[:, None] < ROTARY_DIM), other=0.0)
k_rot = k * cos_k + k_swapped * rot_sign[:, None] * sin_k
sim_rot = tl.dot(q_rot, k_rot, allow_tf32=False) * sm_scale
if HAS_POS_MASK: sim_unrot = tl.dot(q, k, allow_tf32=False) * sm_scale pos_k_ptrs = PosMask + offs_n_curr pos_k = tl.load(pos_k_ptrs, mask=offs_n_curr < N_CTX_K, other=0).to(tl.int1) is_both = pos_m[:, None] & pos_k[None, :] sim = tl.where(is_both, sim_rot, sim_unrot) else: sim = sim_rot
if HAS_ATTN_MASK: attn_mask_ptrs = AttnMask + off_z * stride_ab + off_h * stride_ah + offs_m[:, None] * stride_am + offs_n_curr[None, :] * stride_an attn_mask_val = tl.load(attn_mask_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_n_curr[None, :] < N_CTX_K), other=float("-inf")) sim += attn_mask_val
if IS_CAUSAL: causal_mask = offs_m[:, None] >= offs_n_curr[None, :] sim = tl.where(causal_mask, sim, float("-inf"))
sim = tl.where(offs_n_curr[None, :] < N_CTX_K, sim, float("-inf"))
m_ij = tl.maximum(m_i, tl.max(sim, 1)) p = tl.math.exp(sim - m_ij[:, None]) p = tl.where(sim == float("-inf"), 0.0, p) l_ij = tl.sum(p, 1) alpha = tl.math.exp(m_i - m_ij) alpha = tl.where(m_i == float("-inf"), 0.0, alpha) l_i = l_i * alpha + l_ij acc = acc * alpha[:, None]
v_ptrs = V + v_offset + offs_n_curr[:, None] * stride_vn + offs_k[None, :] * stride_vk v = tl.load(v_ptrs, mask=(offs_n_curr[:, None] < N_CTX_K) & (offs_k[None, :] < BLOCK_DMODEL), other=0.0) acc += tl.dot(p.to(V.dtype.element_ty), v, allow_tf32=False) m_i = m_ij
l_i_safe = tl.where(l_i == 0.0, 1.0, l_i) acc = acc / l_i_safe[:, None]
# write back lse lse_ptrs = Lse + off_hz * N_CTX_Q + offs_m tl.store(lse_ptrs, m_i + tl.math.log(l_i_safe), mask=offs_m < N_CTX_Q)
out_offset = off_z * stride_om + off_h * stride_oh out_ptrs = Out + out_offset + offs_m[:, None] * stride_on + offs_k[None, :] * stride_ok tl.store(out_ptrs, acc.to(Q.dtype.element_ty), mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < BLOCK_DMODEL))
@triton.autotune( configs=[ triton.Config({'BLOCK_M': 32, 'BLOCK_N': 32}, num_stages=1, num_warps=4), triton.Config({'BLOCK_M': 64, 'BLOCK_N': 32}, num_stages=1, num_warps=4), ], key=['N_CTX_Q', 'N_CTX_K', 'BLOCK_DMODEL'], reset_to_zero=['DQ', 'DK', 'DV'] ) @triton.jit def _flash_rotary_bwd_kernel( Q, K, V, sm_scale, Cos, Sin, Out, DO, Lse, DQ, DK, DV, PosMask, AttnMask, stride_ab, stride_ah, stride_am, stride_an, stride_qm, stride_qh, stride_qn, stride_qk, stride_km, stride_kh, stride_kn, stride_kk, stride_vm, stride_vh, stride_vn, stride_vk, stride_cz, stride_ch, stride_cn, stride_ck, stride_om, stride_oh, stride_on, stride_ok, stride_dom, stride_doh, stride_don, stride_dok, batch, q_heads, kv_heads, N_CTX_Q, N_CTX_K, BLOCK_DMODEL: tl.constexpr, ROTARY_DIM: tl.constexpr, IS_CAUSAL: tl.constexpr, HAS_POS_MASK: tl.constexpr, HAS_ATTN_MASK: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr ): start_n = tl.program_id(0) off_hz = tl.program_id(1)
off_z = off_hz // q_heads off_h = off_hz % q_heads off_h_kv = off_h // (q_heads // kv_heads)
offs_n = start_n * BLOCK_N + tl.arange(0, BLOCK_N) offs_k = tl.arange(0, BLOCK_DMODEL)
q_offset = off_z * stride_qm + off_h * stride_qh k_offset = off_z * stride_km + off_h_kv * stride_kh v_offset = off_z * stride_vm + off_h_kv * stride_vh o_offset = off_z * stride_om + off_h * stride_oh c_offset = off_z * stride_cz + off_h * stride_ch
k_ptrs = K + k_offset + offs_n[:, None] * stride_kn + offs_k[None, :] * stride_kk v_ptrs = V + v_offset + offs_n[:, None] * stride_vn + offs_k[None, :] * stride_vk dk_ptrs = DK + k_offset + offs_n[:, None] * stride_kn + offs_k[None, :] * stride_kk dv_ptrs = DV + v_offset + offs_n[:, None] * stride_vn + offs_k[None, :] * stride_vk
k = tl.load(k_ptrs, mask=(offs_n[:, None] < N_CTX_K) & (offs_k[None, :] < BLOCK_DMODEL), other=0.0) v = tl.load(v_ptrs, mask=(offs_n[:, None] < N_CTX_K) & (offs_k[None, :] < BLOCK_DMODEL), other=0.0)
offs_k_swapped = offs_k ^ 1 rot_sign = ((offs_k % 2) * 2 - 1)
k_swapped_ptrs = K + k_offset + offs_n[:, None] * stride_kn + offs_k_swapped[None, :] * stride_kk k_swapped = tl.load(k_swapped_ptrs, mask=(offs_n[:, None] < N_CTX_K) & (offs_k[None, :] < BLOCK_DMODEL), other=0.0)
cos_k_ptrs = Cos + c_offset + offs_n[:, None] * stride_cn + offs_k[None, :] * stride_ck sin_k_ptrs = Sin + c_offset + offs_n[:, None] * stride_cn + offs_k[None, :] * stride_ck
cos_k = tl.load(cos_k_ptrs, mask=(offs_n[:, None] < N_CTX_K) & (offs_k[None, :] < ROTARY_DIM), other=1.0) sin_k = tl.load(sin_k_ptrs, mask=(offs_n[:, None] < N_CTX_K) & (offs_k[None, :] < ROTARY_DIM), other=0.0)
k_rot = k * cos_k + k_swapped * rot_sign[None, :] * sin_k k_rot_swapped = k_swapped * cos_k - k * rot_sign[None, :] * sin_k
dv = tl.zeros([BLOCK_N, BLOCK_DMODEL], dtype=tl.float32) dk_rot = tl.zeros([BLOCK_N, BLOCK_DMODEL], dtype=tl.float32) dk_rot_swapped = tl.zeros([BLOCK_N, BLOCK_DMODEL], dtype=tl.float32) if HAS_POS_MASK: dk_unrot = tl.zeros([BLOCK_N, BLOCK_DMODEL], dtype=tl.float32)
if IS_CAUSAL: start_m = (start_n * BLOCK_N // BLOCK_M) * BLOCK_M else: start_m = 0
do_offset = off_z * stride_dom + off_h * stride_doh offs_m_init = start_m + tl.arange(0, BLOCK_M) q_ptrs = Q + q_offset + offs_m_init[:, None] * stride_qn + offs_k[None, :] * stride_qk do_ptrs = DO + do_offset + offs_m_init[:, None] * stride_don + offs_k[None, :] * stride_dok out_ptrs = Out + o_offset + offs_m_init[:, None] * stride_on + offs_k[None, :] * stride_ok dq_ptrs = DQ + q_offset + offs_m_init[:, None] * stride_qn + offs_k[None, :] * stride_qk lse_ptrs = Lse + off_hz * N_CTX_Q + offs_m_init
if HAS_POS_MASK: pos_k_ptrs = PosMask + offs_n pos_k = tl.load(pos_k_ptrs, mask=offs_n < N_CTX_K, other=0).to(tl.int1)
for m in range(start_m, N_CTX_Q, BLOCK_M): offs_m = m + tl.arange(0, BLOCK_M)
q = tl.load(q_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < BLOCK_DMODEL), other=0.0) q_swapped_ptrs = Q + q_offset + offs_m[:, None] * stride_qn + offs_k_swapped[None, :] * stride_qk q_swapped = tl.load(q_swapped_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < BLOCK_DMODEL), other=0.0)
cos_q_ptrs = Cos + c_offset + offs_m[:, None] * stride_cn + offs_k[None, :] * stride_ck sin_q_ptrs = Sin + c_offset + offs_m[:, None] * stride_cn + offs_k[None, :] * stride_ck cos_q = tl.load(cos_q_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < ROTARY_DIM), other=1.0) sin_q = tl.load(sin_q_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < ROTARY_DIM), other=0.0)
q_rot = q * cos_q + q_swapped * rot_sign[None, :] * sin_q q_rot_swapped = q_swapped * cos_q - q * rot_sign[None, :] * sin_q
do = tl.load(do_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < BLOCK_DMODEL), other=0.0) out = tl.load(out_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < BLOCK_DMODEL), other=0.0) lse = tl.load(lse_ptrs, mask=offs_m < N_CTX_Q, other=0.0)
sim_rot = tl.dot(q_rot, tl.trans(k_rot), allow_tf32=False) * sm_scale
if HAS_POS_MASK: sim_unrot = tl.dot(q, tl.trans(k), allow_tf32=False) * sm_scale pos_m_ptrs = PosMask + offs_m pos_m = tl.load(pos_m_ptrs, mask=offs_m < N_CTX_Q, other=0).to(tl.int1) is_both = pos_m[:, None] & pos_k[None, :] sim = tl.where(is_both, sim_rot, sim_unrot) else: sim = sim_rot
if HAS_ATTN_MASK: attn_mask_ptrs = AttnMask + off_z * stride_ab + off_h * stride_ah + offs_m[:, None] * stride_am + offs_n[None, :] * stride_an attn_mask_val = tl.load(attn_mask_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_n[None, :] < N_CTX_K), other=float("-inf")) sim += attn_mask_val
if IS_CAUSAL: causal_mask = offs_m[:, None] >= offs_n[None, :] sim = tl.where(causal_mask, sim, float("-inf"))
sim = tl.where(offs_n[None, :] < N_CTX_K, sim, float("-inf")) sim = tl.where(offs_m[:, None] < N_CTX_Q, sim, float("-inf"))
p = tl.math.exp(sim - lse[:, None]) p = tl.where(sim == float("-inf"), 0.0, p)
dp = tl.dot(do, tl.trans(v), allow_tf32=False) Di = tl.sum(do * out, axis=1) ds = p * (dp - Di[:, None]) ds = tl.where(sim == float("-inf"), 0.0, ds)
dv += tl.dot(tl.trans(p.to(V.dtype.element_ty)), do, allow_tf32=False)
if HAS_POS_MASK: is_both_f32 = tl.where(is_both, 1.0, 0.0) ds_rot = ds * is_both_f32 ds_unrot = ds * (1.0 - is_both_f32)
dk_rot += tl.dot(tl.trans(ds_rot.to(Q.dtype.element_ty)), q_rot, allow_tf32=False) * sm_scale dk_rot_swapped += tl.dot(tl.trans(ds_rot.to(Q.dtype.element_ty)), q_rot_swapped, allow_tf32=False) * sm_scale dk_unrot += tl.dot(tl.trans(ds_unrot.to(Q.dtype.element_ty)), q, allow_tf32=False) * sm_scale
dq_rot_chunk = tl.dot(ds_rot.to(K.dtype.element_ty), k_rot, allow_tf32=False) * sm_scale dq_rot_chunk_swapped = tl.dot(ds_rot.to(K.dtype.element_ty), k_rot_swapped, allow_tf32=False) * sm_scale dq_chunk = dq_rot_chunk * cos_q - dq_rot_chunk_swapped * rot_sign[None, :] * sin_q
dq_unrot_chunk = tl.dot(ds_unrot.to(K.dtype.element_ty), k, allow_tf32=False) * sm_scale dq_chunk += dq_unrot_chunk else: dk_rot += tl.dot(tl.trans(ds.to(Q.dtype.element_ty)), q_rot, allow_tf32=False) * sm_scale dk_rot_swapped += tl.dot(tl.trans(ds.to(Q.dtype.element_ty)), q_rot_swapped, allow_tf32=False) * sm_scale
dq_rot_chunk = tl.dot(ds.to(K.dtype.element_ty), k_rot, allow_tf32=False) * sm_scale dq_rot_chunk_swapped = tl.dot(ds.to(K.dtype.element_ty), k_rot_swapped, allow_tf32=False) * sm_scale dq_chunk = dq_rot_chunk * cos_q - dq_rot_chunk_swapped * rot_sign[None, :] * sin_q
tl.atomic_add(dq_ptrs, dq_chunk.to(DQ.dtype.element_ty), mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < BLOCK_DMODEL))
q_ptrs += BLOCK_M * stride_qn do_ptrs += BLOCK_M * stride_don out_ptrs += BLOCK_M * stride_on dq_ptrs += BLOCK_M * stride_qn lse_ptrs += BLOCK_M
dk = dk_rot * cos_k - dk_rot_swapped * rot_sign[None, :] * sin_k if HAS_POS_MASK: dk += dk_unrot
tl.atomic_add(dk_ptrs, dk.to(Q.dtype.element_ty), mask=(offs_n[:, None] < N_CTX_K) & (offs_k[None, :] < BLOCK_DMODEL)) tl.atomic_add(dv_ptrs, dv.to(Q.dtype.element_ty), mask=(offs_n[:, None] < N_CTX_K) & (offs_k[None, :] < BLOCK_DMODEL))else: _flash_rotary_fwd_kernel = _dummy_kernel _flash_rotary_bwd_kernel = _dummy_kernel
# fused attention autograd function
class FlashAttentionFused(torch.autograd.Function): @staticmethod def forward( ctx, q, k, v, cos, sin, pos_mask = None, attn_mask = None, is_causal = True ): device, dtype = q.device, q.dtype batch, heads_q, seq_len_q, dim = q.shape _, heads_kv, seq_len_k, _ = k.shape
sm_scale = dim ** -0.5
# contiguous
q = q.contiguous() k = k.contiguous() v = v.contiguous() cos = cos.contiguous() sin = sin.contiguous()
# output buffers
out = torch.empty_like(q) lse = torch.empty((batch, heads_q, seq_len_q), device = device, dtype = torch.float32)
# triton kernel config
grid = lambda META: ( triton.cdiv(seq_len_q, META['BLOCK_M']), batch * heads_q, 1 )
stride_cz = cos.stride(0) if cos.size(0) > 1 else 0 stride_ch = cos.stride(1) if cos.size(1) > 1 else 0 stride_cn = cos.stride(2) stride_ck = cos.stride(3)
# optional masks
has_pos_mask = exists(pos_mask) if has_pos_mask: pos_mask = pos_mask.contiguous()
has_attn_mask = exists(attn_mask) stride_ab = stride_ah = stride_am = stride_an = 0
if has_attn_mask: attn_mask = attn_mask.contiguous() stride_ab, stride_ah, stride_am, stride_an = attn_mask.stride()
_flash_rotary_fwd_kernel[grid]( q, k, v, sm_scale, cos, sin, out, lse, pos_mask, attn_mask, stride_ab, stride_ah, stride_am, stride_an, q.stride(0), q.stride(1), q.stride(2), q.stride(3), k.stride(0), k.stride(1), k.stride(2), k.stride(3), v.stride(0), v.stride(1), v.stride(2), v.stride(3), stride_cz, stride_ch, stride_cn, stride_ck, out.stride(0), out.stride(1), out.stride(2), out.stride(3), batch, heads_q, heads_kv, seq_len_q, seq_len_k, BLOCK_DMODEL=dim, ROTARY_DIM=cos.shape[-1], IS_CAUSAL=is_causal, HAS_POS_MASK=has_pos_mask, HAS_ATTN_MASK=has_attn_mask )
ctx.save_for_backward(q, k, v, out, lse, cos, sin, pos_mask, attn_mask) ctx.sm_scale = sm_scale ctx.is_causal = is_causal ctx.has_pos_mask = has_pos_mask ctx.has_attn_mask = has_attn_mask return out
@staticmethod def backward(ctx, dout): q, k, v, out, lse, cos, sin, pos_mask, attn_mask = ctx.saved_tensors
dq = torch.zeros_like(q) dk = torch.zeros_like(k) dv = torch.zeros_like(v)
batch, heads_q, seq_len_q, dim = q.shape _, heads_kv, seq_len_k, _ = k.shape
grid = lambda META: ( triton.cdiv(seq_len_k, META['BLOCK_N']), batch * heads_q, 1 )
stride_cz = cos.stride(0) if cos.size(0) > 1 else 0 stride_ch = cos.stride(1) if cos.size(1) > 1 else 0 stride_cn = cos.stride(2) stride_ck = cos.stride(3)
stride_ab = stride_ah = stride_am = stride_an = 0 if ctx.has_attn_mask: stride_ab, stride_ah, stride_am, stride_an = attn_mask.stride()
_flash_rotary_bwd_kernel[grid]( q, k, v, ctx.sm_scale, cos, sin, out, dout, lse, dq, dk, dv, pos_mask, attn_mask, stride_ab, stride_ah, stride_am, stride_an, q.stride(0), q.stride(1), q.stride(2), q.stride(3), k.stride(0), k.stride(1), k.stride(2), k.stride(3), v.stride(0), v.stride(1), v.stride(2), v.stride(3), stride_cz, stride_ch, stride_cn, stride_ck, out.stride(0), out.stride(1), out.stride(2), out.stride(3), dout.stride(0), dout.stride(1), dout.stride(2), dout.stride(3), batch, heads_q, heads_kv, seq_len_q, seq_len_k, BLOCK_DMODEL=dim, ROTARY_DIM=cos.shape[-1], IS_CAUSAL=ctx.is_causal, HAS_POS_MASK=ctx.has_pos_mask, HAS_ATTN_MASK=ctx.has_attn_mask ) return dq, dk, dv, None, None, None, None, None
# factory
def get_flash_attention_fused(force_reference = False): def inner( q, k, v, cos = None, sin = None, pos_mask = None, attn_mask = None, is_causal = True, rotary_pos_emb = None, rotary_pos_emb_indices = None ): device, dtype = q.device, q.dtype batch, heads_q, seq_len_q, dim = q.shape _, heads_kv, seq_len_k, _ = k.shape
# handle rotary positional embeddings natively
if exists(rotary_pos_emb): rotary_pos_emb = rotary_pos_emb.to(device)
if exists(rotary_pos_emb_indices): if rotary_pos_emb.ndim > 2: rotary_pos_emb = rearrange(rotary_pos_emb, '... d -> (...) d')
padded_freqs = torch.zeros((seq_len_q, rotary_pos_emb.shape[-1]), device = device, dtype = dtype) padded_freqs[rotary_pos_emb_indices] = rotary_pos_emb rotary_pos_emb = padded_freqs
pos_mask = torch.zeros(seq_len_q, device = device, dtype = torch.bool) pos_mask[rotary_pos_emb_indices] = True
cos = rearrange(rotary_pos_emb.cos(), '... n d -> ... 1 1 n d') sin = rearrange(rotary_pos_emb.sin(), '... n d -> ... 1 1 n d')
assert exists(cos) and exists(sin), 'either cos/sin or rotary_pos_emb must be provided'
# handle attention mask formatting
if exists(attn_mask): if attn_mask.dtype == torch.bool: attn_mask_float = torch.zeros_like(attn_mask, dtype = dtype) attn_mask_float[~attn_mask] = -float('inf') attn_mask = attn_mask_float
attn_mask = rearrange(attn_mask, 'b j -> b 1 1 j') if attn_mask.ndim == 2 else rearrange(attn_mask, 'b i j -> b 1 i j') attn_mask = attn_mask.expand(batch, heads_q, seq_len_q, seq_len_k)
# dispatch to reference if requested or triton unavailable
if force_reference or not TRITON_AVAILABLE: return reference_flash_attention(q, k, v, cos, sin, pos_mask, attn_mask, is_causal)
return FlashAttentionFused.apply(q, k, v, cos, sin, pos_mask, attn_mask, is_causal) return inner
flash_attn_with_rotary = get_flash_attention_fused(force_reference = False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529import mathimport torchfrom torch import Tensorfrom einops import rearrange, repeat
try: import triton import triton.language as tl TRITON_AVAILABLE = Trueexcept ImportError: TRITON_AVAILABLE = False triton = None tl = None
# helpers
def exists(v): return v is not None
def rotate_half_backward(x): x = rearrange(x, '... (d r) -> ... d r', r=2) x1, x2 = x.unbind(dim=-1) x = torch.stack((-x2, x1), dim=-1) return rearrange(x, '... d r -> ... (d r)')
# reference flash attention
def reference_flash_attention(q, k, v, cos=None, sin=None, pos_mask=None, attn_mask=None, is_causal=True): sim = torch.einsum('b h i d, b h j d -> b h i j', q, k)
if exists(cos) and exists(sin): rot_dim = cos.shape[-1]
q_rot = (q[..., :rot_dim] * cos) + (rotate_half_backward(q[..., :rot_dim]) * sin) k_rot = (k[..., :rot_dim] * cos) + (rotate_half_backward(k[..., :rot_dim]) * sin)
q_rot = torch.cat((q_rot, q[..., rot_dim:]), dim=-1) k_rot = torch.cat((k_rot, k[..., rot_dim:]), dim=-1)
sim_rot = torch.einsum('b h i d, b h j d -> b h i j', q_rot, k_rot)
if exists(pos_mask): is_pos_2d = pos_mask[:, None] & pos_mask[None, :] sim = torch.where(is_pos_2d, sim_rot, sim) else: sim = sim_rot
sim = sim * (q.shape[-1] ** -0.5)
if exists(attn_mask): sim = sim + attn_mask
if is_causal: causal_mask = torch.ones((q.shape[2], k.shape[2]), device=q.device, dtype=torch.bool).tril() sim = torch.where(causal_mask, sim, float('-inf'))
return torch.einsum('b h i j, b h j d -> b h i d', sim.softmax(dim=-1), v)
def _dummy_kernel(*args, **kwargs): pass
# triton forward and backward kernels
if TRITON_AVAILABLE: @triton.autotune( configs=[ triton.Config({'BLOCK_M': 32, 'BLOCK_N': 32}, num_stages=2, num_warps=4), triton.Config({'BLOCK_M': 64, 'BLOCK_N': 32}, num_stages=1, num_warps=4), ], key=['N_CTX_Q', 'N_CTX_K', 'BLOCK_DMODEL'] ) @triton.jit def _flash_rotary_fwd_kernel( Q, K, V, sm_scale, Cos, Sin, Out, Lse, PosMask, AttnMask, stride_ab, stride_ah, stride_am, stride_an, stride_qm, stride_qh, stride_qn, stride_qk, stride_km, stride_kh, stride_kn, stride_kk, stride_vm, stride_vh, stride_vn, stride_vk, stride_cz, stride_ch, stride_cn, stride_ck, stride_om, stride_oh, stride_on, stride_ok, batch, heads, N_CTX_Q, N_CTX_K, BLOCK_DMODEL: tl.constexpr, ROTARY_DIM: tl.constexpr, IS_CAUSAL: tl.constexpr, HAS_POS_MASK: tl.constexpr, HAS_ATTN_MASK: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr ): start_m = tl.program_id(0) off_hz = tl.program_id(1)
off_z = off_hz // heads off_h = off_hz % heads
q_offset = off_z * stride_qm + off_h * stride_qh k_offset = off_z * stride_km + off_h * stride_kh v_offset = off_z * stride_vm + off_h * stride_vh c_offset = off_z * stride_cz + off_h * stride_ch
offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) offs_n = tl.arange(0, BLOCK_N) offs_k = tl.arange(0, BLOCK_DMODEL)
q_ptrs = Q + q_offset + offs_m[:, None] * stride_qn + offs_k[None, :] * stride_qk q = tl.load(q_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < BLOCK_DMODEL), other=0.0)
offs_k_swapped = offs_k ^ 1 rot_sign = ((offs_k % 2) * 2 - 1)
q_swapped_ptrs = Q + q_offset + offs_m[:, None] * stride_qn + offs_k_swapped[None, :] * stride_qk q_swapped = tl.load(q_swapped_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < BLOCK_DMODEL), other=0.0)
cos_q_ptrs = Cos + c_offset + offs_m[:, None] * stride_cn + offs_k[None, :] * stride_ck sin_q_ptrs = Sin + c_offset + offs_m[:, None] * stride_cn + offs_k[None, :] * stride_ck cos_q = tl.load(cos_q_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < ROTARY_DIM), other=1.0) sin_q = tl.load(sin_q_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < ROTARY_DIM), other=0.0)
q_rot = q * cos_q + q_swapped * rot_sign[None, :] * sin_q
if HAS_POS_MASK: pos_m_ptrs = PosMask + offs_m pos_m = tl.load(pos_m_ptrs, mask=offs_m < N_CTX_Q, other=0).to(tl.int1)
m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf") l_i = tl.zeros([BLOCK_M], dtype=tl.float32) acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32)
for start_n in range(0, N_CTX_K, BLOCK_N): offs_n_curr = start_n + offs_n
k_ptrs = K + k_offset + offs_n_curr[None, :] * stride_kn + offs_k[:, None] * stride_kk k = tl.load(k_ptrs, mask=(offs_n_curr[None, :] < N_CTX_K) & (offs_k[:, None] < BLOCK_DMODEL), other=0.0)
k_swapped_ptrs = K + k_offset + offs_n_curr[None, :] * stride_kn + offs_k_swapped[:, None] * stride_kk k_swapped = tl.load(k_swapped_ptrs, mask=(offs_n_curr[None, :] < N_CTX_K) & (offs_k[:, None] < BLOCK_DMODEL), other=0.0)
cos_k_ptrs = Cos + c_offset + offs_n_curr[None, :] * stride_cn + offs_k[:, None] * stride_ck sin_k_ptrs = Sin + c_offset + offs_n_curr[None, :] * stride_cn + offs_k[:, None] * stride_ck cos_k = tl.load(cos_k_ptrs, mask=(offs_n_curr[None, :] < N_CTX_K) & (offs_k[:, None] < ROTARY_DIM), other=1.0) sin_k = tl.load(sin_k_ptrs, mask=(offs_n_curr[None, :] < N_CTX_K) & (offs_k[:, None] < ROTARY_DIM), other=0.0)
k_rot = k * cos_k + k_swapped * rot_sign[:, None] * sin_k
sim_rot = tl.dot(q_rot, k_rot, allow_tf32=False) * sm_scale
if HAS_POS_MASK: sim_unrot = tl.dot(q, k, allow_tf32=False) * sm_scale pos_k_ptrs = PosMask + offs_n_curr pos_k = tl.load(pos_k_ptrs, mask=offs_n_curr < N_CTX_K, other=0).to(tl.int1) is_both = pos_m[:, None] & pos_k[None, :] sim = tl.where(is_both, sim_rot, sim_unrot) else: sim = sim_rot
if HAS_ATTN_MASK: attn_mask_ptrs = AttnMask + off_z * stride_ab + off_h * stride_ah + offs_m[:, None] * stride_am + offs_n_curr[None, :] * stride_an attn_mask_val = tl.load(attn_mask_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_n_curr[None, :] < N_CTX_K), other=float("-inf")) sim += attn_mask_val
if IS_CAUSAL: causal_mask = offs_m[:, None] >= offs_n_curr[None, :] sim = tl.where(causal_mask, sim, float("-inf"))
sim = tl.where(offs_n_curr[None, :] < N_CTX_K, sim, float("-inf"))
m_ij = tl.maximum(m_i, tl.max(sim, 1)) p = tl.math.exp(sim - m_ij[:, None]) p = tl.where(sim == float("-inf"), 0.0, p) l_ij = tl.sum(p, 1) alpha = tl.math.exp(m_i - m_ij) alpha = tl.where(m_i == float("-inf"), 0.0, alpha) l_i = l_i * alpha + l_ij acc = acc * alpha[:, None]
v_ptrs = V + v_offset + offs_n_curr[:, None] * stride_vn + offs_k[None, :] * stride_vk v = tl.load(v_ptrs, mask=(offs_n_curr[:, None] < N_CTX_K) & (offs_k[None, :] < BLOCK_DMODEL), other=0.0) acc += tl.dot(p.to(V.dtype.element_ty), v, allow_tf32=False) m_i = m_ij
l_i_safe = tl.where(l_i == 0.0, 1.0, l_i) acc = acc / l_i_safe[:, None]
# write back lse lse_ptrs = Lse + off_hz * N_CTX_Q + offs_m tl.store(lse_ptrs, m_i + tl.math.log(l_i_safe), mask=offs_m < N_CTX_Q)
out_offset = off_z * stride_om + off_h * stride_oh out_ptrs = Out + out_offset + offs_m[:, None] * stride_on + offs_k[None, :] * stride_ok tl.store(out_ptrs, acc.to(Q.dtype.element_ty), mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < BLOCK_DMODEL))
@triton.autotune( configs=[ triton.Config({'BLOCK_M': 32, 'BLOCK_N': 32}, num_stages=1, num_warps=4), triton.Config({'BLOCK_M': 64, 'BLOCK_N': 32}, num_stages=1, num_warps=4), ], key=['N_CTX_Q', 'N_CTX_K', 'BLOCK_DMODEL'], reset_to_zero=['DQ'] ) @triton.jit def _flash_rotary_bwd_kernel( Q, K, V, sm_scale, Cos, Sin, Out, DO, Lse, DQ, DK, DV, PosMask, AttnMask, stride_ab, stride_ah, stride_am, stride_an, stride_qm, stride_qh, stride_qn, stride_qk, stride_km, stride_kh, stride_kn, stride_kk, stride_vm, stride_vh, stride_vn, stride_vk, stride_cz, stride_ch, stride_cn, stride_ck, stride_om, stride_oh, stride_on, stride_ok, stride_dom, stride_doh, stride_don, stride_dok, batch, heads, N_CTX_Q, N_CTX_K, BLOCK_DMODEL: tl.constexpr, ROTARY_DIM: tl.constexpr, IS_CAUSAL: tl.constexpr, HAS_POS_MASK: tl.constexpr, HAS_ATTN_MASK: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr ): start_n = tl.program_id(0) off_hz = tl.program_id(1)
off_z = off_hz // heads off_h = off_hz % heads
offs_n = start_n * BLOCK_N + tl.arange(0, BLOCK_N) offs_k = tl.arange(0, BLOCK_DMODEL)
q_offset = off_z * stride_qm + off_h * stride_qh k_offset = off_z * stride_km + off_h * stride_kh v_offset = off_z * stride_vm + off_h * stride_vh o_offset = off_z * stride_om + off_h * stride_oh c_offset = off_z * stride_cz + off_h * stride_ch
k_ptrs = K + k_offset + offs_n[:, None] * stride_kn + offs_k[None, :] * stride_kk v_ptrs = V + v_offset + offs_n[:, None] * stride_vn + offs_k[None, :] * stride_vk dk_ptrs = DK + k_offset + offs_n[:, None] * stride_kn + offs_k[None, :] * stride_kk dv_ptrs = DV + v_offset + offs_n[:, None] * stride_vn + offs_k[None, :] * stride_vk
k = tl.load(k_ptrs, mask=(offs_n[:, None] < N_CTX_K) & (offs_k[None, :] < BLOCK_DMODEL), other=0.0) v = tl.load(v_ptrs, mask=(offs_n[:, None] < N_CTX_K) & (offs_k[None, :] < BLOCK_DMODEL), other=0.0)
offs_k_swapped = offs_k ^ 1 rot_sign = ((offs_k % 2) * 2 - 1)
k_swapped_ptrs = K + k_offset + offs_n[:, None] * stride_kn + offs_k_swapped[None, :] * stride_kk k_swapped = tl.load(k_swapped_ptrs, mask=(offs_n[:, None] < N_CTX_K) & (offs_k[None, :] < BLOCK_DMODEL), other=0.0)
cos_k_ptrs = Cos + c_offset + offs_n[:, None] * stride_cn + offs_k[None, :] * stride_ck sin_k_ptrs = Sin + c_offset + offs_n[:, None] * stride_cn + offs_k[None, :] * stride_ck
cos_k = tl.load(cos_k_ptrs, mask=(offs_n[:, None] < N_CTX_K) & (offs_k[None, :] < ROTARY_DIM), other=1.0) sin_k = tl.load(sin_k_ptrs, mask=(offs_n[:, None] < N_CTX_K) & (offs_k[None, :] < ROTARY_DIM), other=0.0)
k_rot = k * cos_k + k_swapped * rot_sign[None, :] * sin_k k_rot_swapped = k_swapped * cos_k - k * rot_sign[None, :] * sin_k
dv = tl.zeros([BLOCK_N, BLOCK_DMODEL], dtype=tl.float32) dk_rot = tl.zeros([BLOCK_N, BLOCK_DMODEL], dtype=tl.float32) dk_rot_swapped = tl.zeros([BLOCK_N, BLOCK_DMODEL], dtype=tl.float32) if HAS_POS_MASK: dk_unrot = tl.zeros([BLOCK_N, BLOCK_DMODEL], dtype=tl.float32)
if IS_CAUSAL: start_m = (start_n * BLOCK_N // BLOCK_M) * BLOCK_M else: start_m = 0
do_offset = off_z * stride_dom + off_h * stride_doh offs_m_init = start_m + tl.arange(0, BLOCK_M) q_ptrs = Q + q_offset + offs_m_init[:, None] * stride_qn + offs_k[None, :] * stride_qk do_ptrs = DO + do_offset + offs_m_init[:, None] * stride_don + offs_k[None, :] * stride_dok out_ptrs = Out + o_offset + offs_m_init[:, None] * stride_on + offs_k[None, :] * stride_ok dq_ptrs = DQ + q_offset + offs_m_init[:, None] * stride_qn + offs_k[None, :] * stride_qk lse_ptrs = Lse + off_hz * N_CTX_Q + offs_m_init
if HAS_POS_MASK: pos_k_ptrs = PosMask + offs_n pos_k = tl.load(pos_k_ptrs, mask=offs_n < N_CTX_K, other=0).to(tl.int1)
for m in range(start_m, N_CTX_Q, BLOCK_M): offs_m = m + tl.arange(0, BLOCK_M)
q = tl.load(q_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < BLOCK_DMODEL), other=0.0) q_swapped_ptrs = Q + q_offset + offs_m[:, None] * stride_qn + offs_k_swapped[None, :] * stride_qk q_swapped = tl.load(q_swapped_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < BLOCK_DMODEL), other=0.0)
cos_q_ptrs = Cos + c_offset + offs_m[:, None] * stride_cn + offs_k[None, :] * stride_ck sin_q_ptrs = Sin + c_offset + offs_m[:, None] * stride_cn + offs_k[None, :] * stride_ck cos_q = tl.load(cos_q_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < ROTARY_DIM), other=1.0) sin_q = tl.load(sin_q_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < ROTARY_DIM), other=0.0)
q_rot = q * cos_q + q_swapped * rot_sign[None, :] * sin_q q_rot_swapped = q_swapped * cos_q - q * rot_sign[None, :] * sin_q
do = tl.load(do_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < BLOCK_DMODEL), other=0.0) out = tl.load(out_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < BLOCK_DMODEL), other=0.0) lse = tl.load(lse_ptrs, mask=offs_m < N_CTX_Q, other=0.0)
sim_rot = tl.dot(q_rot, tl.trans(k_rot), allow_tf32=False) * sm_scale
if HAS_POS_MASK: sim_unrot = tl.dot(q, tl.trans(k), allow_tf32=False) * sm_scale pos_m_ptrs = PosMask + offs_m pos_m = tl.load(pos_m_ptrs, mask=offs_m < N_CTX_Q, other=0).to(tl.int1) is_both = pos_m[:, None] & pos_k[None, :] sim = tl.where(is_both, sim_rot, sim_unrot) else: sim = sim_rot
if HAS_ATTN_MASK: attn_mask_ptrs = AttnMask + off_z * stride_ab + off_h * stride_ah + offs_m[:, None] * stride_am + offs_n[None, :] * stride_an attn_mask_val = tl.load(attn_mask_ptrs, mask=(offs_m[:, None] < N_CTX_Q) & (offs_n[None, :] < N_CTX_K), other=float("-inf")) sim += attn_mask_val
if IS_CAUSAL: causal_mask = offs_m[:, None] >= offs_n[None, :] sim = tl.where(causal_mask, sim, float("-inf"))
sim = tl.where(offs_n[None, :] < N_CTX_K, sim, float("-inf")) sim = tl.where(offs_m[:, None] < N_CTX_Q, sim, float("-inf"))
p = tl.math.exp(sim - lse[:, None]) p = tl.where(sim == float("-inf"), 0.0, p)
dp = tl.dot(do, tl.trans(v), allow_tf32=False) Di = tl.sum(do * out, axis=1) ds = p * (dp - Di[:, None]) ds = tl.where(sim == float("-inf"), 0.0, ds)
dv += tl.dot(tl.trans(p.to(V.dtype.element_ty)), do, allow_tf32=False)
if HAS_POS_MASK: is_both_f32 = tl.where(is_both, 1.0, 0.0) ds_rot = ds * is_both_f32 ds_unrot = ds * (1.0 - is_both_f32)
dk_rot += tl.dot(tl.trans(ds_rot.to(Q.dtype.element_ty)), q_rot, allow_tf32=False) * sm_scale dk_rot_swapped += tl.dot(tl.trans(ds_rot.to(Q.dtype.element_ty)), q_rot_swapped, allow_tf32=False) * sm_scale dk_unrot += tl.dot(tl.trans(ds_unrot.to(Q.dtype.element_ty)), q, allow_tf32=False) * sm_scale
dq_rot_chunk = tl.dot(ds_rot.to(K.dtype.element_ty), k_rot, allow_tf32=False) * sm_scale dq_rot_chunk_swapped = tl.dot(ds_rot.to(K.dtype.element_ty), k_rot_swapped, allow_tf32=False) * sm_scale dq_chunk = dq_rot_chunk * cos_q - dq_rot_chunk_swapped * rot_sign[None, :] * sin_q
dq_unrot_chunk = tl.dot(ds_unrot.to(K.dtype.element_ty), k, allow_tf32=False) * sm_scale dq_chunk += dq_unrot_chunk else: dk_rot += tl.dot(tl.trans(ds.to(Q.dtype.element_ty)), q_rot, allow_tf32=False) * sm_scale dk_rot_swapped += tl.dot(tl.trans(ds.to(Q.dtype.element_ty)), q_rot_swapped, allow_tf32=False) * sm_scale
dq_rot_chunk = tl.dot(ds.to(K.dtype.element_ty), k_rot, allow_tf32=False) * sm_scale dq_rot_chunk_swapped = tl.dot(ds.to(K.dtype.element_ty), k_rot_swapped, allow_tf32=False) * sm_scale dq_chunk = dq_rot_chunk * cos_q - dq_rot_chunk_swapped * rot_sign[None, :] * sin_q
tl.atomic_add(dq_ptrs, dq_chunk.to(DQ.dtype.element_ty), mask=(offs_m[:, None] < N_CTX_Q) & (offs_k[None, :] < BLOCK_DMODEL))
q_ptrs += BLOCK_M * stride_qn do_ptrs += BLOCK_M * stride_don out_ptrs += BLOCK_M * stride_on dq_ptrs += BLOCK_M * stride_qn lse_ptrs += BLOCK_M
dk = dk_rot * cos_k - dk_rot_swapped * rot_sign[None, :] * sin_k if HAS_POS_MASK: dk += dk_unrot
tl.store(dk_ptrs, dk.to(Q.dtype.element_ty), mask=(offs_n[:, None] < N_CTX_K) & (offs_k[None, :] < BLOCK_DMODEL)) tl.store(dv_ptrs, dv.to(Q.dtype.element_ty), mask=(offs_n[:, None] < N_CTX_K) & (offs_k[None, :] < BLOCK_DMODEL))else: _flash_rotary_fwd_kernel = _dummy_kernel _flash_rotary_bwd_kernel = _dummy_kernel
# fused attention autograd function
class FlashAttentionFused(torch.autograd.Function): @staticmethod def forward(ctx, q, k, v, cos, sin, pos_mask=None, attn_mask=None, is_causal=True): q = q.contiguous() k = k.contiguous() v = v.contiguous() cos = cos.contiguous() sin = sin.contiguous()
batch, heads, seq_len_q, dim = q.shape _, _, seq_len_k, _ = k.shape sm_scale = dim ** -0.5
out = torch.empty_like(q) lse = torch.empty((batch, heads, seq_len_q), device=q.device, dtype=torch.float32)
grid = lambda META: ( triton.cdiv(seq_len_q, META['BLOCK_M']), batch * heads, 1 )
stride_cz = cos.stride(0) if cos.size(0) > 1 else 0 stride_ch = cos.stride(1) if cos.size(1) > 1 else 0 stride_cn = cos.stride(2) stride_ck = cos.stride(3)
has_pos_mask = pos_mask is not None if has_pos_mask: pos_mask = pos_mask.contiguous()
has_attn_mask = attn_mask is not None stride_ab = stride_ah = stride_am = stride_an = 0 if has_attn_mask: attn_mask = attn_mask.contiguous() stride_ab, stride_ah, stride_am, stride_an = attn_mask.stride()
_flash_rotary_fwd_kernel[grid]( q, k, v, sm_scale, cos, sin, out, lse, pos_mask, attn_mask, stride_ab, stride_ah, stride_am, stride_an, q.stride(0), q.stride(1), q.stride(2), q.stride(3), k.stride(0), k.stride(1), k.stride(2), k.stride(3), v.stride(0), v.stride(1), v.stride(2), v.stride(3), stride_cz, stride_ch, stride_cn, stride_ck, out.stride(0), out.stride(1), out.stride(2), out.stride(3), batch, heads, seq_len_q, seq_len_k, BLOCK_DMODEL=dim, ROTARY_DIM=cos.shape[-1], IS_CAUSAL=is_causal, HAS_POS_MASK=has_pos_mask, HAS_ATTN_MASK=has_attn_mask )
ctx.save_for_backward(q, k, v, out, lse, cos, sin, pos_mask, attn_mask) ctx.sm_scale = sm_scale ctx.is_causal = is_causal ctx.has_pos_mask = has_pos_mask ctx.has_attn_mask = has_attn_mask return out
@staticmethod def backward(ctx, dout): q, k, v, out, lse, cos, sin, pos_mask, attn_mask = ctx.saved_tensors
dq = torch.zeros_like(q) dk = torch.empty_like(k) dv = torch.empty_like(v)
batch, heads, seq_len_q, dim = q.shape _, _, seq_len_k, _ = k.shape
grid = lambda META: ( triton.cdiv(seq_len_k, META['BLOCK_N']), batch * heads, 1 )
stride_cz = cos.stride(0) if cos.size(0) > 1 else 0 stride_ch = cos.stride(1) if cos.size(1) > 1 else 0 stride_cn = cos.stride(2) stride_ck = cos.stride(3)
stride_ab = stride_ah = stride_am = stride_an = 0 if ctx.has_attn_mask: stride_ab, stride_ah, stride_am, stride_an = attn_mask.stride()
_flash_rotary_bwd_kernel[grid]( q, k, v, ctx.sm_scale, cos, sin, out, dout, lse, dq, dk, dv, pos_mask, attn_mask, stride_ab, stride_ah, stride_am, stride_an, q.stride(0), q.stride(1), q.stride(2), q.stride(3), k.stride(0), k.stride(1), k.stride(2), k.stride(3), v.stride(0), v.stride(1), v.stride(2), v.stride(3), stride_cz, stride_ch, stride_cn, stride_ck, out.stride(0), out.stride(1), out.stride(2), out.stride(3), dout.stride(0), dout.stride(1), dout.stride(2), dout.stride(3), batch, heads, seq_len_q, seq_len_k, BLOCK_DMODEL=dim, ROTARY_DIM=cos.shape[-1], IS_CAUSAL=ctx.is_causal, HAS_POS_MASK=ctx.has_pos_mask, HAS_ATTN_MASK=ctx.has_attn_mask ) return dq, dk, dv, None, None, None, None, None
# factory
def get_flash_attention_fused(force_reference=False): def inner(q, k, v, cos=None, sin=None, pos_mask=None, attn_mask=None, is_causal=True, rotary_pos_emb=None, rotary_pos_emb_indices=None): batch, heads, seq_len_q, _ = q.shape _, _, seq_len_k, _ = k.shape if exists(rotary_pos_emb): if exists(rotary_pos_emb_indices): if rotary_pos_emb.ndim > 2: rotary_pos_emb = rearrange(rotary_pos_emb, '... d -> (...) d')
padded_freqs = torch.zeros((seq_len_q, rotary_pos_emb.shape[-1]), device=q.device, dtype=q.dtype) padded_freqs[rotary_pos_emb_indices] = rotary_pos_emb rotary_pos_emb = padded_freqs
pos_mask = torch.zeros(seq_len_q, device=q.device, dtype=torch.bool) pos_mask[rotary_pos_emb_indices] = True
cos = rearrange(rotary_pos_emb.cos(), '... n d -> ... 1 1 n d') sin = rearrange(rotary_pos_emb.sin(), '... n d -> ... 1 1 n d')
assert exists(cos) and exists(sin), 'either cos/sin or rotary_pos_emb must be provided'
if exists(attn_mask): if attn_mask.dtype == torch.bool: attn_mask_float = torch.zeros_like(attn_mask, dtype=q.dtype) attn_mask_float[~attn_mask] = -float('inf') attn_mask = attn_mask_float attn_mask = rearrange(attn_mask, 'b j -> b 1 1 j') if attn_mask.ndim == 2 else rearrange(attn_mask, 'b i j -> b 1 i j') attn_mask = attn_mask.expand(batch, heads, seq_len_q, seq_len_k)
if force_reference or not TRITON_AVAILABLE: return reference_flash_attention(q, k, v, cos, sin, pos_mask, attn_mask, is_causal)
return FlashAttentionFused.apply(q, k, v, cos, sin, pos_mask, attn_mask, is_causal) return inner
flash_attention_fused = get_flash_attention_fused(force_reference=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350from __future__ import annotationsfrom math import pi, log
import torchfrom torch.amp import autocastfrom torch.nn import Module, ModuleListfrom torch import nn, einsum, broadcast_tensors, is_tensor, tensor, Tensor
from einops import rearrange, repeat
from typing import Literal
# helper functions
def exists(val): return val is not None
def default(val, d): return val if exists(val) else d
# broadcat, as tortoise-tts was using it
def broadcat(tensors, dim = -1): broadcasted_tensors = broadcast_tensors(*tensors) return torch.cat(broadcasted_tensors, dim = dim)
def slice_at_dim(t, dim_slice: slice, *, dim): dim += (t.ndim if dim < 0 else 0) colons = [slice(None)] * t.ndim colons[dim] = dim_slice return t[tuple(colons)]
# rotary embedding helper functions
def rotate_half(x): x = rearrange(x, '... (d r) -> ... d r', r = 2) x1, x2 = x.unbind(dim = -1) x = torch.stack((-x2, x1), dim = -1) return rearrange(x, '... d r -> ... (d r)')
@autocast('cuda', enabled = False)def apply_rotary_emb( freqs, t, start_index = 0, scale = 1., seq_dim = -2, freqs_seq_dim = None): dtype = t.dtype
if not exists(freqs_seq_dim): if freqs.ndim == 2 or t.ndim == 3: freqs_seq_dim = 0
if t.ndim == 3 or exists(freqs_seq_dim): seq_len = t.shape[seq_dim] freqs = slice_at_dim(freqs, slice(-seq_len, None), dim = freqs_seq_dim)
rot_dim = freqs.shape[-1] end_index = start_index + rot_dim
assert rot_dim <= t.shape[-1], f'feature dimension {t.shape[-1]} is not of sufficient size to rotate in all the positions {rot_dim}'
# Split t into three parts: left, middle (to be transformed), and right t_left = t[..., :start_index] t_middle = t[..., start_index:end_index] t_right = t[..., end_index:]
# Apply rotary embeddings without modifying t in place t_transformed = (t_middle * freqs.cos() * scale) + (rotate_half(t_middle) * freqs.sin() * scale)
out = torch.cat((t_left, t_transformed, t_right), dim=-1)
return out.type(dtype)
# learned rotation helpers
def apply_learned_rotations(rotations, t, start_index = 0, freq_ranges = None): if exists(freq_ranges): rotations = einsum('..., f -> ... f', rotations, freq_ranges) rotations = rearrange(rotations, '... r f -> ... (r f)')
rotations = repeat(rotations, '... n -> ... (n r)', r = 2) return apply_rotary_emb(rotations, t, start_index = start_index)
# classes
class RotaryEmbedding(Module): def __init__( self, dim, custom_freqs: Tensor | None = None, freqs_for: Literal['lang', 'pixel', 'constant'] = 'lang', theta = 10000, max_freq = 10, num_freqs = 1, learned_freq = False, use_xpos = False, xpos_scale_base = 512, interpolate_factor = 1., theta_rescale_factor = 1., seq_before_head_dim = False, cache_if_possible = True, cache_max_seq_len = 8192 ): super().__init__() # proposed by reddit user bloc97, to rescale rotary embeddings to longer sequence length without fine-tuning # has some connection to NTK literature # https://www.reddit.com/r/LocalLLaMA/comments/14lz7j5/ntkaware_scaled_rope_allows_llama_models_to_have/
theta *= theta_rescale_factor ** (dim / (dim - 2))
self.freqs_for = freqs_for
if exists(custom_freqs): freqs = custom_freqs elif freqs_for == 'lang': freqs = 1. / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim)) elif freqs_for == 'pixel': freqs = torch.linspace(1., max_freq / 2, dim // 2) * pi elif freqs_for == 'constant': freqs = torch.ones(num_freqs).float()
self.cache_if_possible = cache_if_possible self.cache_max_seq_len = cache_max_seq_len
self.register_buffer('cached_freqs', torch.zeros(cache_max_seq_len, dim), persistent = False) self.cached_freqs_seq_len = 0
self.freqs = nn.Parameter(freqs, requires_grad = learned_freq)
self.learned_freq = learned_freq
# dummy for device
self.register_buffer('dummy', torch.tensor(0), persistent = False)
# default sequence dimension
self.seq_before_head_dim = seq_before_head_dim self.default_seq_dim = -3 if seq_before_head_dim else -2
# interpolation factors
assert interpolate_factor >= 1. self.interpolate_factor = interpolate_factor
# xpos
self.use_xpos = use_xpos
if not use_xpos: return
scale = (torch.arange(0, dim, 2) + 0.4 * dim) / (1.4 * dim) self.scale_base = xpos_scale_base
self.register_buffer('scale', scale, persistent = False) self.register_buffer('cached_scales', torch.zeros(cache_max_seq_len, dim), persistent = False) self.cached_scales_seq_len = 0
# add apply_rotary_emb as static method
self.apply_rotary_emb = staticmethod(apply_rotary_emb)
@property def device(self): return self.dummy.device
def get_seq_pos(self, seq_len, device = None, dtype = None, offset = 0): device = default(device, self.device) dtype = default(dtype, self.cached_freqs.dtype)
return (torch.arange(seq_len, device = device, dtype = dtype) + offset) / self.interpolate_factor
def rotate_queries_or_keys(self, t, seq_dim = None, offset = 0, scale = None): seq_dim = default(seq_dim, self.default_seq_dim)
assert not self.use_xpos or exists(scale), 'you must use `.rotate_queries_and_keys` method instead and pass in both queries and keys, for length extrapolatable rotary embeddings'
device, dtype, seq_len = t.device, t.dtype, t.shape[seq_dim]
seq = self.get_seq_pos(seq_len, device = device, dtype = dtype, offset = offset)
freqs = self.forward(seq, seq_len = seq_len, offset = offset)
if seq_dim == -3: freqs = rearrange(freqs, 'n d -> n 1 d')
return apply_rotary_emb(freqs, t, scale = default(scale, 1.), seq_dim = seq_dim)
def rotate_queries_with_cached_keys(self, q, k, seq_dim = None, offset = 0): dtype, device, seq_dim = q.dtype, q.device, default(seq_dim, self.default_seq_dim)
q_len, k_len = q.shape[seq_dim], k.shape[seq_dim] assert q_len <= k_len
q_scale = k_scale = 1.
if self.use_xpos: seq = self.get_seq_pos(k_len, dtype = dtype, device = device)
q_scale = self.get_scale(seq[-q_len:]).type(dtype) k_scale = self.get_scale(seq).type(dtype)
rotated_q = self.rotate_queries_or_keys(q, seq_dim = seq_dim, scale = q_scale, offset = k_len - q_len + offset) rotated_k = self.rotate_queries_or_keys(k, seq_dim = seq_dim, scale = k_scale ** -1)
rotated_q = rotated_q.type(q.dtype) rotated_k = rotated_k.type(k.dtype)
return rotated_q, rotated_k
def rotate_queries_and_keys(self, q, k, seq_dim = None): seq_dim = default(seq_dim, self.default_seq_dim)
assert self.use_xpos device, dtype, seq_len = q.device, q.dtype, q.shape[seq_dim]
seq = self.get_seq_pos(seq_len, dtype = dtype, device = device)
freqs = self.forward(seq, seq_len = seq_len) scale = self.get_scale(seq, seq_len = seq_len).to(dtype)
if seq_dim == -3: freqs = rearrange(freqs, 'n d -> n 1 d') scale = rearrange(scale, 'n d -> n 1 d')
rotated_q = apply_rotary_emb(freqs, q, scale = scale, seq_dim = seq_dim) rotated_k = apply_rotary_emb(freqs, k, scale = scale ** -1, seq_dim = seq_dim)
rotated_q = rotated_q.type(q.dtype) rotated_k = rotated_k.type(k.dtype)
return rotated_q, rotated_k
def get_scale( self, t: Tensor, seq_len: int | None = None, offset = 0 ): assert self.use_xpos
should_cache = ( self.cache_if_possible and exists(seq_len) and (offset + seq_len) <= self.cache_max_seq_len )
if ( should_cache and \ exists(self.cached_scales) and \ (seq_len + offset) <= self.cached_scales_seq_len ): return self.cached_scales[offset:(offset + seq_len)]
scale = 1. if self.use_xpos: power = (t - len(t) // 2) / self.scale_base scale = self.scale ** rearrange(power, 'n -> n 1') scale = repeat(scale, 'n d -> n (d r)', r = 2)
if should_cache and offset == 0: self.cached_scales[:seq_len] = scale.detach() self.cached_scales_seq_len = seq_len
return scale
def get_axial_freqs( self, *dims, offsets: ( tuple[int | float, ...] | Tensor | None ) = None ): Colon = slice(None) all_freqs = []
# handle offset
if exists(offsets): if not is_tensor(offsets): offsets = tensor(offsets)
assert len(offsets) == len(dims)
# get frequencies for each axis
for ind, dim in enumerate(dims):
offset = 0 if exists(offsets): offset = offsets[ind]
if self.freqs_for == 'pixel': pos = torch.linspace(-1, 1, steps = dim, device = self.device) else: pos = torch.arange(dim, device = self.device)
pos = pos + offset
freqs = self.forward(pos, seq_len = dim)
all_axis = [None] * len(dims) all_axis[ind] = Colon
new_axis_slice = (Ellipsis, *all_axis, Colon) all_freqs.append(freqs[new_axis_slice])
# concat all freqs
all_freqs = broadcast_tensors(*all_freqs) return torch.cat(all_freqs, dim = -1)
@autocast('cuda', enabled = False) def forward( self, t: Tensor, seq_len: int | None = None, offset = 0 ): should_cache = ( self.cache_if_possible and not self.learned_freq and exists(seq_len) and self.freqs_for != 'pixel' and (offset + seq_len) <= self.cache_max_seq_len )
if ( should_cache and \ exists(self.cached_freqs) and \ (offset + seq_len) <= self.cached_freqs_seq_len ): return self.cached_freqs[offset:(offset + seq_len)].detach()
freqs = self.freqs
freqs = einsum('..., f -> ... f', t.type(freqs.dtype), freqs) freqs = repeat(freqs, '... n -> ... (n r)', r = 2)
if should_cache and offset == 0: self.cached_freqs[:seq_len] = freqs.detach() self.cached_freqs_seq_len = seq_len
return freqs123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132"""DOES DF'S ACTION CHANNEL PREDICT THE EXPERT'S ACTION, AND IS IT ALIGNED? (gen_q#274)
Run 28 measured random-of-128 == argmax == 0.000 on RISE. Both arms sample from DF's OWN actiondistribution and execute it, so 0.000 says DF's actions are non-functional REGARDLESS of selection --the planner's ranking is not what is being tested there. This probe tests the action path alone, onheld-out episodes, with no environment and no success number.
Q1 IS THE ACTION HEAD INFORMATIVE AT ALL? R2 = 1 - MSE(pred) / MSE(predict the dataset's mean action), per channel and pooled. R2 <= 0 means the action channel carries no information about what the expert did, and 0.000 success is fully explained without any reference to the planner, the guidance, or the world model. Reported for a single sample and for the K-sample mean (the action a policy should execute is the posterior mean, not one draw -- see df_fidmean.py).
Q2 IS IT ALIGNED? `df_data.sample` builds bundle[t] = (obs_t, act_t, rew) -- act_t is the action taken AT obs_t (df_data.py:123-124). `plan_bundles` conditions on bundle[0] and predicts frames 1..T. `best_actions` (df_plan.py:141) then returns plan[0:execute_frames]'s actions, which are a_1..a_8, and df_policy executes them starting from s_0. If bundle[t]'s action is a_t, the first action executed at s_0 should be a_0 -- so the chunk may be one frame early. This scores the predicted action at plan index h against the data's action at bundle[h+1+lag] for lag in {-2,-1,0,+1,+2} and reports which lag maximises R2. If the best lag is not 0, the executed chunk is misaligned and that is an integration bug, not a fact about the method.
A misalignment cannot be diagnosed from success rate (every cell reads 0.000) nor fromact_absmax/act_clip_frac (a shifted expert action is still in the box), which is why it needs its ownmeasurement."""from __future__ import annotationsimport argparse, json, os, sysimport numpy as npimport torch
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from df_data import DFCacheData, OBS_DIM, ACT_DIM # noqa: E402from df_probe import load_df # noqa: E402from df_plan import plan_bundles # noqa: E402
A0, A1 = OBS_DIM, OBS_DIM + ACT_DIM
@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=128) p.add_argument("--kmax", type=int, default=32) p.add_argument("--execute-frames", type=int, default=8) 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) T = data.T bundle, mask = data.sample(a.n_states, rng, split="val", device=dev) # [W, B, BUNDLE_DIM] init_obs = bundle[0, :, :OBS_DIM] plan = plan_bundles(model, init_obs, horizon_frames=T, guidance_scale=0.0, gamma=0.0, n_plans=a.kmax, device=dev)["plan"] # [T, B, K, C] pred_act = plan[..., A0:A1] # [T, B, K, ACT_DIM]
# the baseline every R2 is against: the dataset's own mean action (a constant predictor) mean_act = torch.as_tensor(np.asarray(data.act, np.float32).mean(0), device=dev) # [ACT_DIM]
res = dict(ckpt=a.ckpt, cache=a.cache, step=step, n_states=int(a.n_states), kmax=a.kmax, execute_frames=a.execute_frames, frame_stack=int(meta["frame_stack"]), train_steps=int(meta.get("steps", -1)), mean_act=[float(v) for v in mean_act.cpu()], per_lag={}, per_h={})
def r2(pred, tgt): """1 - MSE(pred)/MSE(constant mean-action predictor), pooled and per channel.""" num = ((pred - tgt) ** 2).mean(0) # [ACT_DIM] den = ((mean_act[None, :] - tgt) ** 2).mean(0) return (1.0 - num.sum() / den.sum().clamp_min(1e-12)).item(), \ [(1.0 - n / d).item() for n, d in zip(num, den.clamp_min(1e-12))]
# ---- Q2: alignment. score the EXECUTED chunk (plan indices 0..execute_frames-1) at each lag ---- for lag in (-2, -1, 0, 1, 2): P, Tg = [], [] for h in range(a.execute_frames): j = h + 1 + lag # bundle index the plan index h is being scored against if j < 0 or j >= bundle.shape[0]: continue w = mask[j].bool() if w.sum() == 0: continue P.append(pred_act[h][w].mean(1)) # K-sample mean, the action a policy should execute Tg.append(bundle[j][w, A0:A1]) if not P: continue pooled, per_ch = r2(torch.cat(P), torch.cat(Tg)) res["per_lag"][str(lag)] = {"r2_pooled_Kmean": pooled, "r2_per_channel_Kmean": per_ch, "n": int(sum(x.shape[0] for x in P))} best = max(res["per_lag"], key=lambda k: res["per_lag"][k]["r2_pooled_Kmean"]) if res["per_lag"] else None res["best_lag"] = best res["as_implemented_lag"] = 0 res["misaligned"] = (best is not None and int(best) != 0)
# ---- Q1: informativeness per plan index, single sample vs K-sample mean, at lag 0 ---- for h in range(min(a.execute_frames, T)): j = h + 1 if j >= bundle.shape[0]: continue w = mask[j].bool() if w.sum() == 0: continue tgt = bundle[j][w, A0:A1] one, _ = r2(pred_act[h][w][:, 0, :], tgt) km, per_ch = r2(pred_act[h][w].mean(1), tgt) res["per_h"][str(h)] = {"r2_single_sample": one, "r2_Kmean": km, "r2_per_channel_Kmean": per_ch, "pred_std_over_K": pred_act[h][w].std(1).mean().item(), "tgt_std": tgt.std(0).mean().item(), "n": int(w.sum())}
os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True) with open(a.out, "w") as f: json.dump(res, f, indent=1) print("[df_actprobe] step", step, "R2 vs mean-action baseline (K-sample mean):") for lag, r in sorted(res["per_lag"].items(), key=lambda kv: int(kv[0])): flag = " <-- as implemented" if int(lag) == 0 else "" star = " *BEST*" if lag == best else "" print(f" lag {int(lag):+d} R2 {r['r2_pooled_Kmean']:+.4f} (n={r['n']}){flag}{star}") for h, r in sorted(res["per_h"].items(), key=lambda kv: int(kv[0])): print(f" plan idx {h:>2s} R2 single {r['r2_single_sample']:+.4f} Kmean {r['r2_Kmean']:+.4f}" f" predstd/tgtstd {r['pred_std_over_K']/max(r['tgt_std'],1e-9):.2f}") print("[df_actprobe] wrote", a.out)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242"""Diffusion Forcing on the rsm_rise corpora -- model wrapper and planner (gen_q#274).
The DIFFUSION MODEL IS UPSTREAM'S, imported from the vendored checkout, not reimplemented: code/diffusion_forcing @ 475e0bcab87545e48b24b39fb46a81fe59d80594 (main branch, 2025-02-22) algorithms/diffusion_forcing/models/diffusion.py -> Diffusion (noise schedule, training objective, sample_step, guidance) algorithms/diffusion_forcing/models/transformer.py -> Transformer (the 1-D backbone)What this file adds is exactly the glue #274 asks for: our corpus's bundle layout, the independentper-token noise levels and pyramid scheduling matrix copied from upstream's `df_base.py`, and aplanner whose guidance points at the binary data-provenance reward.
THE REWARD-GUIDANCE BRANCH IS NOT UPSTREAM CODE, AND THAT IS A FINDING, NOT AN OVERSIGHT.Upstream's planner (`algorithms/diffusion_forcing/df_planning.py:148-190`) offers two guidancebranches. The one it ships and tunes is GOAL guidance -- MSE toward a known goal observation,Diffuser-style. The reward branch, `if self.use_reward:` at :180, opens with
raise NotImplementedError("reward guidance not officially supported yet, although implemented")
so the released code has no working reward guidance. We cannot use the goal branch: a goalobservation is privileged information no other column in tab:flagship receives (the project alreadyruled the env-replay goal classifier "privileged goal labels", LAUNCH_MATRIX 2026-09-18 13:05). Sothe reward branch is the only fair one, and we implement it from the recipe upstream left in the deadcode beneath that raise -- reconstruction weight on the conditioning frames, gamma^j on the horizon,zero on the padding -- with our gamma rather than its hard-coded 0.997. Any DF number we publishmust carry this sentence."""from __future__ import annotations
import osimport sys
import numpy as npimport torchimport torch.nn as nn
DF_REPO = os.environ.get("DF_REPO", "/proj/dmfexp/zwhong/rsm_rise/code/diffusion_forcing")DF_COMMIT = "475e0bcab87545e48b24b39fb46a81fe59d80594"
from df_data import OBS_DIM, ACT_DIM, BUNDLE_DIM # noqa: E402
def _upstream(): """Import upstream's `models/diffusion.py` VERBATIM, without executing its package __init__.
`algorithms/diffusion_forcing/__init__.py` imports df_video, which pulls in lightning, cv2 and the whole hydra experiment runner -- none of which the model code needs. So the models/ directory is registered as a synthetic package (`df_models`) and diffusion.py is loaded from its path; its relative imports (`.unet3d`, `.transformer`, `.utils`) resolve inside that package. Nothing in the vendored checkout is edited, so `git -C code/diffusion_forcing status` stays clean and the commit hash above remains the whole provenance of this model.""" import importlib.util as _iu import types as _types if "df_models.diffusion" in sys.modules: return sys.modules["df_models.diffusion"].Diffusion base = os.path.join(DF_REPO, "algorithms", "diffusion_forcing", "models") if not os.path.isdir(base): raise RuntimeError(f"vendored Diffusion Forcing not found at {DF_REPO} " f"(expected commit {DF_COMMIT})") pkg = _types.ModuleType("df_models") pkg.__path__ = [base] sys.modules["df_models"] = pkg spec = _iu.spec_from_file_location("df_models.diffusion", os.path.join(base, "diffusion.py")) mod = _iu.module_from_spec(spec) sys.modules["df_models.diffusion"] = mod spec.loader.exec_module(mod) return mod.Diffusion
def default_cfg(network_size=256, num_layers=12, attn_heads=4, dim_feedforward=1024, timesteps=1000, sampling_timesteps=50, frame_stack=8, frame_skip=1, beta_schedule="linear", objective="pred_x0"): """Upstream `df_planning.yaml` on top of `df_base.yaml`, with only the size raised.
Changed from upstream, and why: network_size 128 -> 256, dim_feedforward 512 -> 1024. Upstream's maze2d bundle is 6-d (obs 4 + act 2); ours is 1553-d, because the observation is the 1545-d pooled DINOv2 state every other column reads. A 128-wide trunk is a 15x bottleneck on that input. This is the ONLY architectural change and it is swept (see `--network-size`) rather than assumed. Everything else -- linear beta schedule, pred_x0, DDIM eta 0, stabilization_level 10, non-causal with independent per-token noise, pyramid scheduling -- is upstream's planning recipe.
DF_MAKEITWORK mug-WM sweep (2026-09-24): `beta_schedule` and `objective` became PARAMETERS so the noise schedule and the loss parameterisation can be swept. The DEFAULTS ARE UNCHANGED ("linear" / "pred_x0"), so every checkpoint already on disk and every caller that does not pass them is bit-identical to before. Both are upstream's own options, read straight out of `code/diffusion_forcing/.../models/diffusion.py` (:84-91 linear|cosine|sigmoid, :165-178 pred_noise|pred_x0|pred_v) -- no new model code, and nothing task-specific. """ from omegaconf import OmegaConf return OmegaConf.create(dict( timesteps=timesteps, sampling_timesteps=sampling_timesteps, beta_schedule=beta_schedule, schedule_fn_kwargs={}, objective=objective, use_fused_snr=False, snr_clip=5.0, cum_snr_decay=0.98 ** (frame_stack * frame_skip), # df_base.py:36 does this adjustment ddim_sampling_eta=0.0, clip_noise=20.0, stabilization_level=10, architecture=dict(network_size=network_size, num_layers=num_layers, attn_heads=attn_heads, dim_feedforward=dim_feedforward), ))
class DFRise(nn.Module): """Bundle = [obs (1545) | act (7) | reward (1)], frame_stack frames per token."""
def __init__(self, frame_stack=8, n_tokens=8, mean=None, std=None, cfg=None, uncertainty_scale=1.0, scheduling_matrix="pyramid"): super().__init__() Diffusion = _upstream() self.frame_stack, self.n_tokens = int(frame_stack), int(n_tokens) self.cfg = cfg if cfg is not None else default_cfg(frame_stack=frame_stack) self.timesteps = int(self.cfg.timesteps) self.sampling_timesteps = int(self.cfg.sampling_timesteps) self.uncertainty_scale = float(uncertainty_scale) self.scheduling_matrix = scheduling_matrix self.x_stacked_shape = [self.frame_stack * BUNDLE_DIM] self.diffusion_model = Diffusion(x_shape=self.x_stacked_shape, external_cond_dim=0, is_causal=False, cfg=self.cfg) if mean is None: mean, std = np.zeros(BUNDLE_DIM, np.float32), np.ones(BUNDLE_DIM, np.float32) self.register_buffer("data_mean", torch.as_tensor(np.asarray(mean, np.float32))) self.register_buffer("data_std", torch.as_tensor(np.asarray(std, np.float32)))
# ---- normalisation / (un)stacking ------------------------------------- def norm(self, x): # x [..., C] return (x - self.data_mean) / self.data_std
def unnorm(self, x): return x * self.data_std + self.data_mean
def stack(self, x): # [T, B, C] -> [T/fs, B, fs*C] T, B, C = x.shape assert T % self.frame_stack == 0, (T, self.frame_stack) return x.view(T // self.frame_stack, self.frame_stack, B, C).permute(0, 2, 1, 3).reshape( T // self.frame_stack, B, self.frame_stack * C)
def unstack(self, x): # [t, B, fs*C] -> [t*fs, B, C] t, B, _ = x.shape return x.view(t, B, self.frame_stack, BUNDLE_DIM).permute(0, 2, 1, 3).reshape( t * self.frame_stack, B, BUNDLE_DIM)
# ---- training --------------------------------------------------------- def make_sequence(self, bundle, init_obs): """bundle [T,B,C] (real frames), init_obs [B,OBS] -> xs [1+T/fs, B, fs*C], upstream layout.
Token 0 is the CONDITIONING token: the current observation repeated frame_stack times with the action and reward channels zeroed after normalisation (df_planning.py:69-71). Tokens 1.. are the plan. Training and planning therefore see the same layout.
init_obs [B, OBS_DIM] -- upstream's layout, the default, bit-identical to every checkpoint on disk: ONE observation repeated frame_stack times, so the conditioning token carries NO velocity. init_obs [B, fs, OBS_DIM] -- DF_MAKEITWORK's `--cond-history 1`: the agent's OWN last frame_stack observations, oldest first. Strictly less information than the other columns get (DINO-WM and every frame-stacking policy already read an observation history) and the executing policy has it for free; the action and reward channels are still zeroed exactly as above, so nothing about the plan's targets changes.""" B = bundle.shape[1] if init_obs.dim() == 3: assert init_obs.shape[1] == self.frame_stack, (init_obs.shape, self.frame_stack) init = torch.zeros(self.frame_stack, B, BUNDLE_DIM, device=bundle.device, dtype=bundle.dtype) init[:, :, :OBS_DIM] = init_obs.permute(1, 0, 2) init = self.norm(init) init[:, :, OBS_DIM:] = 0.0 init_tok = init # [fs, B, C] else: init = torch.zeros(B, BUNDLE_DIM, device=bundle.device, dtype=bundle.dtype) init[:, :OBS_DIM] = init_obs init = self.norm(init) init[:, OBS_DIM:] = 0.0 init_tok = init.unsqueeze(0).repeat(self.frame_stack, 1, 1) # [fs, B, C] xs = torch.cat([init_tok, self.norm(bundle)], dim=0) return self.stack(xs)
def noise_levels(self, xs, token_mask=None): """Upstream df_base.py:172 `random_all`: an INDEPENDENT uniform noise level per token. Tokens with no real frame are pinned to full noise, as upstream does with its mask.""" t, B = xs.shape[:2] k = torch.randint(0, self.timesteps, (t, B), device=xs.device) if token_mask is not None: k = torch.where(token_mask.bool(), k, torch.full_like(k, self.timesteps - 1)) return k
def loss(self, xs, k, weight=None, chan_w=None): """weight [t,B,fs] is upstream's per-FRAME hook; chan_w [BUNDLE_DIM] is a per-CHANNEL one.
Why a per-channel hook exists (gen_q#274 run 28). Our bundle is obs 1545 | act 7 | reward 1, and a bare `loss.mean()` over it gives the 7 action channels that actually touch the environment 0.45% of the gradient and the reward channel the guidance reads 0.064%. DF's OWN working planning configuration is obs 4 | act 2 | reward 1 -- 28.6% and 14.3%. So the uniform mean is a 63x / 222x gradient deficit against the configuration the method is published in, and it is an artefact of the fairness condition (train on the same 1545-d DINOv2 corpus as DINO-WM), not a choice DF makes. chan_w=None reproduces the old reduction exactly, so every landed number stays comparable.""" xs_pred, loss = self.diffusion_model(xs, None, k) loss = loss.view(loss.shape[0], loss.shape[1], self.frame_stack, BUNDLE_DIM) if weight is not None: # [t, B, fs] loss = loss * weight.unsqueeze(-1) if chan_w is not None: # [BUNDLE_DIM] loss = loss * chan_w return xs_pred, loss.mean()
# ---- sampling --------------------------------------------------------- def set_sampling_timesteps(self, S): """Override the DDIM step count S at INFERENCE time (gen_q#282, DF_VALUE, additive).
Nothing about the trained weights depends on S: `timesteps` (1000) is the training noise schedule and S only decides how many of those levels the sampler visits (diffusion.py:310 builds `real_steps` from it, and :101 sets `is_ddim_sampling`). It is the single biggest cost knob in this route -- the pyramid schedule runs `S + (K-1)*uncertainty_scale + 1` denoiser calls over K plan tokens, so at K=2 the height is S+2 and S is essentially the whole cost.
WHY THIS EXISTS. Measured on the spread gate (LSF 1892978, the SAME code path a cell runs): one 128-candidate decision costs ~7.6 s at H=10/M=8 and ~30 s at H=200/M=64. An eval cell is 50 episodes x 50 decisions = 2500 decisions, so the full `H x M x agg` grid at S=50 is GPU-months, not GPU-hours. Lowering S is only legitimate if the CANDIDATE RANKING is unchanged, which is a measurable thing -- see scripts/nb/dfval_spread.py --ddim. Never lower S on the strength of the speedup alone.
S is not written into the checkpoint and this mutates only the live module, so a process that never calls it is bit-identical to before.""" S = int(S) if not 1 <= S <= self.timesteps: raise ValueError(f"sampling_timesteps {S} outside [1, {self.timesteps}]") self.sampling_timesteps = S self.diffusion_model.sampling_timesteps = S self.diffusion_model.is_ddim_sampling = S < self.timesteps return self
def scheduling(self, horizon_tokens): """Upstream df_base.py:199 pyramid / :192 full_sequence.""" S = self.sampling_timesteps if self.scheduling_matrix == "full_sequence": return np.arange(S, -1, -1)[:, None].repeat(horizon_tokens, axis=1) height = S + int((horizon_tokens - 1) * self.uncertainty_scale) + 1 m = np.zeros((height, horizon_tokens), dtype=np.int64) for i in range(height): for t in range(horizon_tokens): m[i, t] = S + int(t * self.uncertainty_scale) - i return np.clip(m, 0, S)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145"""Diffusion Forcing corpus adapter (gen_q#274).
CORPUS. The SAME DINOv2 cache every other scorer in tab:flagship reads -- `cache/<task>`: z.f16.npy [N, 1536] frozen DINOv2 ViT-S/14 cls+GeM features, 2 cameras x 2 channels proprio.f32.npy [N, 9] robot0_eef_pos / _quat / gripper_qpos act.f32.npy [N, 7] the OSC action actually executed meta.npz ep_from / ep_to / ep_len / ep_success (+ ep_src into the source HDF5)No pixels are read. DINO-WM trains on the TOKEN form of this same cache (cache/<task>/tokens);Diffusion Forcing here trains on the POOLED 1545-d form, which is the same frames, the same episodesand the same encoder -- stated explicitly because #274 requires saying which of the two we used.
STATE DEFINITION is the project's, not a new one (data.py:245): x = clip((feat - mu) / max(sd, sd_floor), -z_clip, z_clip), feat = concat(z, proprio)with mu / sd / sd_floor / z_clip read from the cache's own feat_stats.npz. A DF-specificnormalisation on top of that would make DF's inputs incomparable with every other column's.
REWARD is the binary data-provenance label -- `ep_success`, constant over an episode, 1 on everyframe of an expert episode -- i.e. exactly what `train_rsm.py --reward-mode dense` feeds themembership head and exactly what RISE's own 0/1 critic label is (LAUNCH_MATRIX, 2026-09-18 13:05).No shaped reward and no goal signal: #274's fairness condition.
CONSEQUENCE, stated because it changes how DF's guidance must be read: a per-episode-constant label carries no WITHIN-episode temporal signal. Guiding toward it does not mean "move toward the goal"; it means "generate a trajectory that looks like it came from the expert partition". That is the same information every other column gets, which is the point, but it is NOT the dense step-reward DF's maze2d planner was designed around, and the guidance term degenerates to a single scalar per plan rather than a per-step return. Reported, not hidden.
SPLIT is the one `LiberoRSMData(seed=seed)` uses -- np.random.default_rng(seed).permutation(n_ep),first max(1, 0.1*n_ep) episodes held out (data.py:124-126) -- so DF's validation episodes are theepisodes every other scorer held out.
WINDOWS. DF consumes (t b (fs c)) tokens: `frame_stack` consecutive frames per token, `n_tokens`tokens per sequence. A window is drawn inside ONE episode (never across a boundary) and is padded atthe tail with the episode's last frame, with a `mask` marking the padded frames so the loss and thefidelity metric ignore them."""from __future__ import annotations
from pathlib import Path
import numpy as npimport torch
OBS_DIM, ACT_DIM, REW_DIM = 1545, 7, 1BUNDLE_DIM = OBS_DIM + ACT_DIM + REW_DIM # 1553
class DFCacheData: def __init__(self, cache, frame_stack: int = 8, n_tokens: int = 8, val_frac: float = 0.1, seed: int = 0, in_ram: bool = True): self.root = Path(cache) m = np.load(self.root / "meta.npz", allow_pickle=True) self.ep_from = m["ep_from"].astype(np.int64) self.ep_to = m["ep_to"].astype(np.int64) self.ep_len = m["ep_len"].astype(np.int64) self.ep_success = m["ep_success"].astype(np.float32) self.n_ep = len(self.ep_len) self.adim = int(m["adim"]) assert self.adim == ACT_DIM, f"{cache}: adim {self.adim} != {ACT_DIM}"
mode = None if in_ram else "r" self.z = np.load(self.root / "z.f16.npy", mmap_mode=mode) self.pr = np.load(self.root / "proprio.f32.npy", mmap_mode=mode) self.act = np.load(self.root / "act.f32.npy", mmap_mode=mode) assert self.z.shape[0] == self.pr.shape[0] == self.act.shape[0], "cache arrays disagree on N" assert self.z.shape[1] + self.pr.shape[1] == OBS_DIM, \ f"{cache}: {self.z.shape[1]}+{self.pr.shape[1]} != {OBS_DIM}"
fs = np.load(self.root / "feat_stats.npz") self.mu = fs["mu"].astype(np.float32) self.sd = np.maximum(fs["sd"].astype(np.float32), float(fs["sd_floor"])) self.z_clip = float(fs["z_clip"])
self.frame_stack, self.n_tokens = int(frame_stack), int(n_tokens) # T is the PLAN length in frames (a whole number of tokens). A window holds T + 1 frames: # frame 0 is the conditioning observation that becomes token 0, frames 1..T are the plan, so # the plan is always divisible by frame_stack. self.T = self.frame_stack * self.n_tokens self.W = self.T + 1
rng = np.random.default_rng(seed) n_val = max(1, int(val_frac * self.n_ep)) perm = rng.permutation(self.n_ep) self.val_eps = np.sort(perm[:n_val]) self.train_eps = np.sort(perm[n_val:]) print(f"[df_data] {cache}: {self.n_ep} eps ({int(self.ep_success.sum())} expert), " f"{self.z.shape[0]} frames, split {len(self.train_eps)} train / {len(self.val_eps)} val, " f"plan T={self.T} frames (fs={self.frame_stack} x {self.n_tokens} tokens), " f"window {self.W} frames", flush=True)
# ---- state ------------------------------------------------------------- def obs_rows(self, rows): """cache row indices -> normalised 1545-d state, EXACTLY data.py's definition.""" feat = np.concatenate([np.asarray(self.z[rows], np.float32), np.asarray(self.pr[rows], np.float32)], axis=-1) x = (feat - self.mu) / self.sd if self.z_clip: np.clip(x, -self.z_clip, self.z_clip, out=x) return x
@staticmethod def normalize_feat(feat, mu, sd, z_clip): """The same map applied to a live env feature vector at planning time.""" x = (feat - mu) / sd if z_clip: x = np.clip(x, -z_clip, z_clip) return x
# ---- windows ----------------------------------------------------------- def sample(self, batch: int, rng, split: str = "train", device="cpu"): """-> bundle [W, B, 1553], mask [W, B] (1 = real frame, 0 = tail padding), W = T + 1.""" pool = self.train_eps if split == "train" else self.val_eps eps = pool[rng.integers(0, len(pool), size=batch)] bun = np.zeros((self.W, batch, BUNDLE_DIM), np.float32) msk = np.zeros((self.W, batch), np.float32) for b, e in enumerate(eps): L = int(self.ep_len[e]) # start uniformly in the episode; a window may run past the end and is padded there. s = int(rng.integers(0, max(1, L))) n = min(self.W, L - s) rows = self.ep_from[e] + np.arange(s, s + n) bun[:n, b, :OBS_DIM] = self.obs_rows(rows) bun[:n, b, OBS_DIM:OBS_DIM + ACT_DIM] = np.asarray(self.act[rows], np.float32) msk[:n, b] = 1.0 if n < self.W: # hold the last real frame, mask says it is padding bun[n:, b, :OBS_DIM + ACT_DIM] = bun[n - 1, b, :OBS_DIM + ACT_DIM] bun[:, b, -1] = self.ep_success[e] # provenance label on every frame of the window return (torch.from_numpy(bun).to(device), torch.from_numpy(msk).to(device))
def bundle_stats(self, n: int = 20000, seed: int = 0): """Per-channel mean/std of the bundle over TRAIN frames, for DF's own input normaliser. The obs channels are already unit-scale by construction, so this mostly matters for the action channels and the reward channel.""" rng = np.random.default_rng(seed) rows = np.concatenate([np.arange(self.ep_from[e], self.ep_to[e]) for e in self.train_eps]) take = rows if len(rows) <= n else rows[rng.choice(len(rows), n, replace=False)] take = np.sort(take) obs = self.obs_rows(take) act = np.asarray(self.act[take], np.float32) lab = np.repeat(self.ep_success[self.train_eps].mean(), 1).astype(np.float32) mean = np.concatenate([obs.mean(0), act.mean(0), lab]) std = np.concatenate([obs.std(0), act.std(0), np.array([max(self.ep_success[self.train_eps].std(), 1e-3)], np.float32)]) return mean.astype(np.float32), np.maximum(std, 1e-3).astype(np.float32)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118"""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 itsRMSE against the truth to a **deterministic** stay-put control. That comparison is structurallybiased against any stochastic predictor: for a PERFECTLY CALIBRATED sampler whose posterior equalsthe 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 atratio 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 fromthe 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 samplingnoise 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 genuinelyworse than standing still and the diagnosis stands. Either way the number is decisive, and it costsone GPU-minute rather than a 100k-step training run."""from __future__ import annotationsimport argparse, json, os, sysimport numpy as npimport torch
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from df_data import DFCacheData, OBS_DIM # noqa: E402from df_probe import load_df # noqa: E402from df_plan import plan_bundles # noqa: E402from 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112"""gen_q#274, stream DF_MAKEITWORK run 41 -- IS THE GUIDANCE KNOB ACTUALLY CONNECTED?
The brief's lead 2 names this test verbatim: "report the L2 between plans sampled at guidance 0and at guidance 5 from the same seed. If it is ~0, the parameter is inert and the sweep wasmeasuring nothing -- that has happened on this project before (an inert `plan_temp`)."
A bare cross-guidance L2 is NOT sufficient on its own, and this script refuses to report onealone. `plan_bundles` draws fresh diffusion noise per call, so two calls differ even at the SAMEguidance; a large cross-guidance L2 would prove nothing unless it is large COMPARED TO that. Soevery cross-guidance number here is published beside its own null:
* SIGNAL L2( plan(g) , plan(g0) ) with the diffusion noise draw HELD IDENTICAL across the two calls (torch.manual_seed set to the same value before each), so the only thing that differs between the two plans is the guidance scale. * NULL L2( plan(g0, seed s1) , plan(g0, seed s2) ) -- same guidance, different noise. This is how far apart two plans land for reasons that have nothing to do with the knob.
READING: signal / null >> 1 => the knob moves the plan far more than resampling does: connected. signal / null ~ 0 => inert; any sweep of it was measuring noise (the `plan_temp` bug). signal / null ~ 1 => the knob perturbs the plan no more than a reseed: uninformative.
FAIRNESS. Diagnostic only -- it produces no success rate and no ranking. It reads the val splitof the same cache the column trains on, uses DF's own predicted binary-provenance reward channelfor J, and never touches a simulator, a success bit, or an RSM/IQL critic (rules 1, 2, 7)."""import argparseimport jsonimport osimport sys
import numpy as npimport torch
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from df_data import DFCacheData, OBS_DIM # noqa: E402from df_probe import load_df # noqa: E402from df_plan import plan_bundles # noqa: E402
@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=32) p.add_argument("--guidance", type=float, action="append", default=[]) p.add_argument("--gamma", type=float, default=0.95) p.add_argument("--seed", type=int, default=0) p.add_argument("--noise-seed", type=int, default=1234) a = p.parse_args() guids = a.guidance or [0.0, 0.5, 1.0, 2.0, 5.0, 10.0] g0 = guids[0] 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) T = data.T bundle, _ = data.sample(a.n_states, rng, split="val", device=dev) init_obs = bundle[0, :, :OBS_DIM]
def draw(g, noise_seed): """One planning call with the diffusion noise draw pinned to `noise_seed`.""" torch.manual_seed(noise_seed) if dev == "cuda": torch.cuda.manual_seed_all(noise_seed) out = plan_bundles(model, init_obs, horizon_frames=T, guidance_scale=g, gamma=a.gamma, n_plans=a.kmax, device=dev) return out["plan"][..., :OBS_DIM].float(), out["J"].float() # [T,B,K,D], [B,K]
def l2(x, y): """mean over (h,b,k) of the per-vector L2 distance.""" return float(torch.linalg.vector_norm(x - y, dim=-1).mean())
P0, J0 = draw(g0, a.noise_seed) scale = float(torch.linalg.vector_norm(P0, dim=-1).mean())
# the NULL: same guidance, a different diffusion noise draw. Pn, _ = draw(g0, a.noise_seed + 777) null = l2(P0, Pn)
res = dict(ckpt=a.ckpt, cache=a.cache, df_step=step, n_states=int(init_obs.shape[0]), kmax=a.kmax, gamma=a.gamma, guidances=guids, g_ref=g0, plan_latent_rms_norm=scale, null_same_guidance_reseed_l2=null, note=("SIGNAL is plan(g) vs plan(g_ref) with the noise draw held identical; NULL is " "plan(g_ref) vs plan(g_ref) under a different noise draw. signal/null >> 1 " "means the guidance knob is connected. Diagnostic only: no success rate, no " "simulator, no success bit, no RSM/IQL contact."), by_guidance={}) print(f"[df_guid_l2] step {step} n_states {init_obs.shape[0]} K {a.kmax} " f"plan latent |P| {scale:.4f}") print(f"[df_guid_l2] NULL (g={g0} reseeded) L2 {null:.5f} ({null/max(scale,1e-9):.4f} of |P|)") for g in guids: Pg, Jg = draw(g, a.noise_seed) d = l2(Pg, P0) cell = dict(l2_vs_ref=d, l2_rel_to_plan_norm=d / max(scale, 1e-9), ratio_to_null=d / max(null, 1e-9), J_mean=float(Jg.mean()), J_spread=float((Jg.max(dim=1).values - Jg.min(dim=1).values).mean())) res["by_guidance"][str(g)] = cell print(f"[df_guid_l2] g={g:<5} SIGNAL L2 {d:.5f} = {cell['ratio_to_null']:.2f}x NULL " f"J_mean {cell['J_mean']:.3f} J_spread {cell['J_spread']:.3f}") os.makedirs(os.path.dirname(a.out), exist_ok=True) with open(a.out, "w") as f: json.dump(res, f, indent=2) print(f"[df_guid_l2] wrote {a.out}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457#!/usr/bin/env python"""INVERSE DYNAMICS MODEL -- the honest, learned analogue of upstream DF's hand-written maze2dcontroller (gen_q#274, stream DF_MAKEITWORK, run 36).
=====================================================================================DECLARE THE DESIGN CHOICE LOUDLY. This file changes the DF column from "DF emits actions" (the diffused-action channel of its own bundle)to "DF plans OBSERVATION LATENTS, a learned decoder emits actions".Every number produced with it must carry that sentence, in the report AND in the table caption,and BOTH arms must be published side by side.=====================================================================================
WHY THIS IS FAITHFUL TO HOW THE METHOD IS ACTUALLY RUN, NOT A DODGE.`code/diffusion_forcing/algorithms/diffusion_forcing/df_planning.py:272-320` (main branch, thecommit our RISE column imports) branches on `action_dim = len(cfg.action_mean)`:
use_diffused_action = False if self.action_dim != 2: print("Detected reduced observation/action space, using Diffuser like controller.") else: use_diffused_action = True ... for t in range(self.open_loop_horizon): if use_diffused_action: _, action, _ = self.split_bundle(plan[t]) else: plan_vel = plan[t,:,:2] - plan[t-1,:,:2] if t > 0 else plan[t,:,:2] - obs[:,:2] action = 12.5 * (plan[t,:,:2] - obs[:,:2]) + 1.2 * (plan_vel - obs[:,2:])
Upstream's RECOMMENDED maze2d recipe (README lines 71/126) passes`dataset.action_mean=[] dataset.action_std=[]`, so `action_dim = 0`, the model diffuses POSITIONSONLY, and the executed action comes from that **hand-written PD controller with gains 12.5 and 1.2**-- not from the model. Our own main-branch gate (LSF 1895313, 1024 episodes/cell, maze2d-medium)measured exactly this split: med_x PD controller on diffused positions 46.3 +- 1.5 normalised med_xva the model's own diffused actions 15.1 +- 1.1 normalisedand the paper's own "Diffuser w/ diffused action" floor is 13.5 +- 2.3. Upstream says it in theirown words in a COMMENTED-OUT README block (line 86): *"Here is also ckpt where we take diffusedactions ... We haven't got it working as well as original RNN version of diffusion forcing"*.
There is no analytic PD law from a planned 1545-d DINOv2 latent to a 7-DoF robomimic OSC action, sothe general form of upstream's controller is a LEARNED inverse dynamics model: a network that maps(observation_t, observation_{t+k}) -> the action(s) that get you from one to the other. DF thenplans in the channel our health numbers say is HEALTHY (observations) and the IDM decodes it. Thatis how Diffuser / UniPi-style systems execute plans.
=====================================================================================FAIRNESS -- exactly the same information every BC column gets, and nothing else.=====================================================================================INPUTS TO THE IDM, exhaustively: the project's normalised 1545-d state x = clip((concat(DINOv2 z, proprio) - mu) / max(sd, sd_floor), -z_clip, z_clip)read through `df_data.DFCacheData.obs_rows` from `cache/<task>` -- the SAME cache, the SAME frozenDINOv2 ViT-S/14 cls+GeM features, the SAME feat_stats, the SAME 9-d proprio (eef pos / quat /gripper qpos) every other column in tab:flagship reads. No pixels, no object poses, no simulatorstate, no goal, no success bit, no reward of any kind, no privileged anything.SUPERVISION: `cache/<task>/act.f32.npy`, the OSC action the dataset actually executed -- which isthe identical supervision every BC column is trained on.SPLIT: `DFCacheData(seed=<the DF arm's own seed>)`, i.e. the SAME held-out episodes every other DFdiagnostic (df_actprobe, df_poolcmp, fid/obs_*) validates on. The IDM never sees a val episode.The reward channel is NOT an input and NOT a target: an IDM has no use for it.
=====================================================================================THE THREE DECODER SHAPES, and why the stride matters more than the architecture.=====================================================================================`runs/<task>/wm/df_G0/health.jsonl` at step 40000 -- DF's observation-rollout RMSE as a RATIO to the"the state never changes" predictor (>= 1 means the roll-out carries no information):
task h=1 h=2 h=4 h=8 h=10 h=20 h=50 threading 1.485 1.358 1.167 0.981 1.012 1.006 0.910 mug 1.606 1.482 1.268 1.071 1.094 0.957 0.918
READ THAT BEFORE READING ANY R2 BELOW. The ONE-STEP planned latent delta is 1.5-1.6x WORSE thanstay-put. A `k1` IDM consumes exactly that delta, so it is being fed the noisiest thing DFproduces. The horizons where DF's observation channel is at or below 1.0 are h>=8. So the shapethat matches where the world model is actually healthy is a CHUNKED IDM that reads a plannedWAYPOINT and emits the whole 8-action chunk -- which is also precisely the cadence the harnessexecutes (`RR_DF_EXECUTE=8`, and upstream's own controller reads a planned waypoint per step.)
mode "k1" g(o_t, o_{t+1}) -> a_t applied autoregressively, 8x mode "k8" g(o_t, o_{t+8}) -> a_t .. a_{t+7} one planned waypoint, one chunk mode "kfull" g(o_t, o_{t+1}, ..., o_{t+8}) -> a_t .. a_{t+7} the whole planned subsequence
`kfull` is strictly the most informed of the three and `k1` the least; all three see ONLY plannedobservations. Which one is used in the env is chosen by a HELD-OUT, ENVIRONMENT-FREE metric(`df_idm_probe.py`'s R2 of decoded actions against the held-out expert action), never by a successrate, so no eval seed is ever consulted to pick a decoder.
NOISE AUGMENTATION (`--noise-rel`). At plan time the anchor o_t is the TRUE current observation(the encoder's output on the live frame) but o_{t+1..} are DF's PREDICTIONS, whose error is ~1.0xthe size of the true delta at h=8 (table above). Training on clean pairs alone builds a decoderthat has never seen an input as bad as the one it will get. So the non-anchor frames are corruptedwith per-dimension Gaussian noise of std `noise_rel * std(o_{t+k} - o_t)`; `noise_rel=1.0` matchesthe measured ratio. This is standard input augmentation on the model's OWN inputs -- it adds noinformation and touches no held-out data. `noise_rel=0.0` is the clean control.
FEATURISATION. Input is [anchor, delta_1, delta_2, ...] -- the anchor observation plus successivefirst differences -- because the action is a function of the MOTION and the deltas are ~100x smallerthan the state. Targets are standardised by the dataset's own per-channel action std so the 7 OSCchannels (6 continuous + 1 near-binary gripper) contribute comparably to the loss; predictions areun-standardised before they leave the model.
=====================================================================================REGISTERED READ-OUT -- written here BEFORE any number exists (run 36, 2026-09-24).=====================================================================================BAR 1, DECODER CAPACITY. `r2_oracle_val` = R2 of the IDM on TRUE held-out observation pairs,against the constant "dataset mean action" predictor (`df_actprobe`'s definition, verbatim). * >= 0.71 the decoder has real capacity (0.71 is the BEST number DF's own action head reaches, FINDING H: threading single 0.569 / K=32-mean 0.711; mug 0.283 / 0.474). * < 0.71 inverse dynamics is NOT learnable from this state at this stride, and the decoder cannot be the fix. SAY SO PLAINLY AND STOP.BAR 2, THE DECISIVE ONE (measured in `df_idm_probe.py`, not here). `r2_plan_Kmean` = R2 of theIDM's actions decoded from DF's OWN PLANNED latents, on the same held-out states, at the same planindices, K-sample mean -- against DF's own action head measured on those identical states in thesame script. * IDM-on-plan > DF-head on both tasks => the decoder swap is a real improvement and the eval is worth its GPU-hours. * IDM-on-plan <= DF-head on either task => the decoder is NOT the fix on that task. Report it, publish the eval anyway (it is already queued and resumable), and do not dress it up. * Expected in advance, and I am registering the pessimistic prior: because `fid/obs_ratio_h1` is 1.485 / 1.606, I expect `k1` to be the WORST of the three shapes and possibly at or below DF's own head; `k8`/`kfull` are the arms with a mechanism behind them.BAR 3, SUCCESS (the stream's mandate). Mean success over the two flagship tasks, canonical region,horizon 400, 50 episodes/cell, 3 policy x 3 eval seeds. A number is REPORTABLE only beside(a) random-of-N over the identical candidate pool, (b) the no-selection floor (n_plans=1),(c) per-cell score spread / ties-at-max / selection gap, (d) the BC-actor no-selection baselinealready on record (status/nb/df_table.txt:9,90 -- threading 0.000, mug 0.027). A scorer that tiesacross most candidates IS random-of-N however good its headline.
usage: python df_idm.py --cache cache/<task> --out runs/<task>/idm/<tag> --mode k8 --noise-rel 1.0"""from __future__ import annotations
import argparseimport jsonimport osimport sysimport timefrom pathlib import Path
import numpy as npimport torchimport torch.nn as nn
sys.path.insert(0, str(Path(__file__).resolve().parent))from df_data import DFCacheData, OBS_DIM, ACT_DIM # noqa: E402
MODES = { # mode -> (frame offsets fed to the net, number of actions predicted) "k1": ((0, 1), 1), "k8": ((0, 8), 8), "kfull": (tuple(range(0, 9)), 8),}
class IDM(nn.Module): """MLP inverse dynamics: [anchor obs, successive obs deltas] -> k standardised actions."""
def __init__(self, offsets, n_act, obs_dim=OBS_DIM, act_dim=ACT_DIM, hidden=1024, layers=3): super().__init__() self.offsets = tuple(int(o) for o in offsets) self.n_act = int(n_act) self.act_dim = int(act_dim) self.obs_dim = int(obs_dim) d_in = obs_dim * len(self.offsets) blocks, d = [], d_in for _ in range(int(layers)): blocks += [nn.Linear(d, hidden), nn.LayerNorm(hidden), nn.GELU()] d = hidden blocks += [nn.Linear(d, self.n_act * act_dim)] self.net = nn.Sequential(*blocks) # target standardisation, filled by fit_act_stats (buffers so they ride in the ckpt) self.register_buffer("act_mean", torch.zeros(act_dim)) self.register_buffer("act_std", torch.ones(act_dim))
# ---- featurisation ----------------------------------------------------- @staticmethod def featurise(obs_seq): """obs_seq [..., L, OBS_DIM] -> [..., L*OBS_DIM] = anchor followed by first differences.""" anchor = obs_seq[..., :1, :] deltas = obs_seq[..., 1:, :] - obs_seq[..., :-1, :] f = torch.cat([anchor, deltas], dim=-2) return f.reshape(*f.shape[:-2], f.shape[-2] * f.shape[-1])
def forward(self, obs_seq): """obs_seq [B, L, OBS_DIM] (L == len(self.offsets)) -> actions [B, n_act, ACT_DIM], in RAW dataset action units.""" y = self.net(self.featurise(obs_seq)) y = y.view(-1, self.n_act, self.act_dim) return y * self.act_std + self.act_mean
# --------------------------------------------------------------------------- dataclass IDMData: """Frame-level sampler over DFCacheData's OWN train/val episode split.
Holds the normalised state matrix in RAM as f16 (115k x 1545 -> 355 MB on threading) because every sample needs random rows of it; the f32 cast happens per batch. """
def __init__(self, cache, offsets, n_act, seed=0, val_frac=0.1, frame_stack=8, n_tokens=8): self.d = DFCacheData(cache, frame_stack=frame_stack, n_tokens=n_tokens, val_frac=val_frac, seed=seed, in_ram=True) self.offsets = tuple(int(o) for o in offsets) self.n_act = int(n_act) self.span = max(self.offsets) # frames of future the sample needs N = self.d.z.shape[0] print(f"[df_idm] materialising {N} x {OBS_DIM} normalised states as f16", flush=True) self.X = np.empty((N, OBS_DIM), np.float16) for s in range(0, N, 8192): e = min(N, s + 8192) self.X[s:e] = self.d.obs_rows(np.arange(s, e)).astype(np.float16) self.A = np.asarray(self.d.act, np.float32) # anchors: frame index t such that t+span and t+n_act-1 are inside the SAME episode need = max(self.span, self.n_act) self.anchors = {} for name, eps in (("train", self.d.train_eps), ("val", self.d.val_eps)): a = [] for e in eps: lo, hi = int(self.d.ep_from[e]), int(self.d.ep_to[e]) if hi - lo > need: a.append(np.arange(lo, hi - need)) self.anchors[name] = np.concatenate(a) if a else np.zeros(0, np.int64) print(f"[df_idm] {name}: {len(eps)} eps, {len(self.anchors[name])} anchors", flush=True) # per-dim std of the largest delta the net is fed -- the unit the noise augmentation uses rng = np.random.default_rng(0) t = self.anchors["train"] take = t if len(t) <= 20000 else t[rng.choice(len(t), 20000, replace=False)] self.delta_std = (self.X[take + self.span].astype(np.float32) - self.X[take].astype(np.float32)).std(0) self.act_mean = self.A[np.concatenate([np.arange(self.d.ep_from[e], self.d.ep_to[e]) for e in self.d.train_eps])].mean(0) self.act_std = np.maximum( self.A[np.concatenate([np.arange(self.d.ep_from[e], self.d.ep_to[e]) for e in self.d.train_eps])].std(0), 1e-3) print(f"[df_idm] delta_std mean {self.delta_std.mean():.4f} " f"act_std {np.round(self.act_std, 3).tolist()}", flush=True)
def batch(self, n, rng, split="train", device="cpu"): a = self.anchors[split] idx = a[rng.integers(0, len(a), size=n)] obs = np.stack([self.X[idx + o].astype(np.float32) for o in self.offsets], 1) # [n,L,D] act = np.stack([self.A[idx + j] for j in range(self.n_act)], 1) # [n,k,7] return (torch.from_numpy(obs).to(device), torch.from_numpy(act).to(device))
def all_val(self, device="cpu", cap=20000): a = self.anchors["val"] if len(a) > cap: a = a[np.linspace(0, len(a) - 1, cap).astype(np.int64)] obs = np.stack([self.X[a + o].astype(np.float32) for o in self.offsets], 1) act = np.stack([self.A[a + j] for j in range(self.n_act)], 1) return (torch.from_numpy(obs).to(device), torch.from_numpy(act).to(device))
# --------------------------------------------------------------------------- load / decodedef load_idm(d, device="cuda"): """<dir>/idm_last.pt -> (module in eval mode, its checkpoint dict). Self-describing.""" ck = torch.load(Path(d) / "idm_last.pt", map_location="cpu", weights_only=False) m = IDM(ck["offsets"], ck["n_act"], hidden=ck["hidden"], layers=ck["layers"]) m.load_state_dict(ck["model"]) return m.to(device).eval(), ck
def decode_plan(idm, ck, O, n_exec): """THE DF -> IDM BRIDGE, shared by the offline probe and the live policy so they cannot drift.
O [1+H, B, K, OBS_DIM] is the observation sequence of K candidate plans: O[0] is the TRUE current observation (what the encoder gives the policy right now), O[j] (j >= 1) is DF's PREDICTED observation at t+j. Returns the decoded actions a_t .. a_{t+n_exec-1} as [n_exec, B, K, ACT_DIM]. """ offs, n_act = tuple(ck["offsets"]), int(ck["n_act"]) Hp1, B, K, D = O.shape if max(offs) + (n_exec - 1 if n_act == 1 else 0) > Hp1 - 1: raise ValueError(f"IDM needs planned frames up to index " f"{max(offs) + (n_exec - 1 if n_act == 1 else 0)} but the plan has " f"{Hp1 - 1} -- raise the planning horizon") if n_act == 1: # autoregressive single-step decoder, stride = offs[1] st = offs[1] outs = [idm(torch.stack([O[h], O[h + st]], dim=2).reshape(B * K, 2, D) ).view(B, K, 1, ACT_DIM)[:, :, 0] for h in range(n_exec)] return torch.stack(outs, 0) seq = torch.stack([O[o] for o in offs], dim=2) # [B,K,L,D] a = idm(seq.reshape(B * K, seq.shape[2], D)).view(B, K, n_act, ACT_DIM) return a.permute(2, 0, 1, 3)[:n_exec].contiguous()
# --------------------------------------------------------------------------- metricdef r2_vs_mean_action(pred, tgt, mean_act): """df_actprobe.py's definition, verbatim: 1 - MSE(pred)/MSE(constant mean-action predictor).
pred/tgt [..., ACT_DIM]; pooled over channels by summing the numerators and denominators, so a channel with a big natural variance is not double-counted. Also returned per channel. """ p = pred.reshape(-1, pred.shape[-1]) t = tgt.reshape(-1, tgt.shape[-1]) num = ((p - t) ** 2).mean(0) den = ((mean_act[None, :] - t) ** 2).mean(0) pooled = (1.0 - num.sum() / den.sum().clamp_min(1e-12)).item() per_ch = [(1.0 - n / d).item() for n, d in zip(num, den.clamp_min(1e-12))] return pooled, per_ch
# --------------------------------------------------------------------------- traindef parse(): p = argparse.ArgumentParser() p.add_argument("--cache", required=True) p.add_argument("--out", required=True) p.add_argument("--mode", default="k8", choices=sorted(MODES)) p.add_argument("--noise-rel", type=float, default=1.0) p.add_argument("--hidden", type=int, default=1024) p.add_argument("--layers", type=int, default=3) p.add_argument("--steps", type=int, default=30000) p.add_argument("--batch", type=int, default=256) p.add_argument("--lr", type=float, default=3e-4) p.add_argument("--weight-decay", type=float, default=1e-4) p.add_argument("--warmup", type=int, default=1000) p.add_argument("--seed", type=int, default=0) # the DF arm whose split this must match; df_G0 was trained with --seed 0 p.add_argument("--split-seed", type=int, default=0) p.add_argument("--frame-stack", type=int, default=8) p.add_argument("--n-tokens", type=int, default=8) p.add_argument("--eval-every", type=int, default=2500) p.add_argument("--resume", type=int, default=1) return p.parse_args()
def main(): a = parse() offsets, n_act = MODES[a.mode] dev = "cuda" if torch.cuda.is_available() else "cpu" out = Path(a.out); out.mkdir(parents=True, exist_ok=True) ck_path = out / "idm_last.pt" js_path = out / "idm.json"
data = IDMData(a.cache, offsets, n_act, seed=a.split_seed, frame_stack=a.frame_stack, n_tokens=a.n_tokens) model = IDM(offsets, n_act, hidden=a.hidden, layers=a.layers).to(dev) model.act_mean.copy_(torch.as_tensor(data.act_mean, device=dev)) model.act_std.copy_(torch.as_tensor(data.act_std, device=dev)) mean_act = torch.as_tensor(data.act_mean, device=dev) noise_sd = torch.as_tensor(a.noise_rel * data.delta_std, device=dev)
opt = torch.optim.AdamW(model.parameters(), lr=a.lr, weight_decay=a.weight_decay) step0 = 0 if a.resume and ck_path.exists(): ck = torch.load(ck_path, map_location=dev, weights_only=False) model.load_state_dict(ck["model"]); opt.load_state_dict(ck["opt"]) step0 = int(ck["step"]) print(f"[df_idm] resumed {ck_path} at step {step0}", flush=True) if step0 >= a.steps: print(f"[df_idm] already at {step0} >= {a.steps} steps -- nothing to do", flush=True) if js_path.exists(): return rng = np.random.default_rng(a.seed + 1) torch.manual_seed(a.seed) astd = torch.as_tensor(data.act_std, device=dev) amean = torch.as_tensor(data.act_mean, device=dev)
val_obs, val_act = data.all_val(dev) print(f"[df_idm] mode={a.mode} offsets={offsets} n_act={n_act} noise_rel={a.noise_rel} " f"params={sum(p.numel() for p in model.parameters())} val_n={val_obs.shape[0]}", flush=True)
def evaluate(): model.eval() with torch.no_grad(): preds = [] for s in range(0, val_obs.shape[0], 4096): preds.append(model(val_obs[s:s + 4096])) pred = torch.cat(preds) pooled, per_ch = r2_vs_mean_action(pred, val_act, mean_act) per_j = [] for j in range(n_act): pj, _ = r2_vs_mean_action(pred[:, j], val_act[:, j], mean_act) per_j.append(pj) # the same thing with the noise the plan will actually carry, so the clean number is # never the only one on record no = val_obs.clone() no[:, 1:] = no[:, 1:] + torch.randn_like(no[:, 1:]) * noise_sd npreds = [] for s in range(0, no.shape[0], 4096): npreds.append(model(no[s:s + 4096])) npooled, _ = r2_vs_mean_action(torch.cat(npreds), val_act, mean_act) model.train() return pooled, per_ch, per_j, npooled
hist = [] t0 = time.time() model.train() for step in range(step0 + 1, a.steps + 1): lr = a.lr * min(1.0, step / max(1, a.warmup)) for g in opt.param_groups: g["lr"] = lr obs, act = data.batch(a.batch, rng, "train", dev) if a.noise_rel > 0: obs = obs.clone() obs[:, 1:] = obs[:, 1:] + torch.randn_like(obs[:, 1:]) * noise_sd pred = model(obs) loss = (((pred - act) / astd) ** 2).mean() opt.zero_grad(set_to_none=True) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) opt.step() if step % a.eval_every == 0 or step == a.steps: pooled, per_ch, per_j, npooled = evaluate() rec = dict(step=step, train_loss=float(loss.item()), r2_oracle_val=pooled, r2_oracle_val_noised=npooled, r2_per_action_index=per_j, r2_per_channel=per_ch, wall_s=time.time() - t0) hist.append(rec) print(f"[df_idm] step {step:>6d} loss {loss.item():.4f} " f"R2(val, true obs) {pooled:+.4f} R2(val, +plan-scale noise) {npooled:+.4f}", flush=True) torch.save(dict(model=model.state_dict(), opt=opt.state_dict(), step=step, mode=a.mode, offsets=list(offsets), n_act=n_act, hidden=a.hidden, layers=a.layers, noise_rel=a.noise_rel, delta_std=data.delta_std, act_mean=data.act_mean, act_std=data.act_std, args=vars(a)), ck_path)
if not hist: # resumed at/after --steps with the JSON missing (e.g. preempted between save and write): # re-measure rather than crash, so the payload is genuinely resumable. pooled, per_ch, per_j, npooled = evaluate() hist.append(dict(step=step0, train_loss=float("nan"), r2_oracle_val=pooled, r2_oracle_val_noised=npooled, r2_per_action_index=per_j, r2_per_channel=per_ch, wall_s=0.0)) else: pooled, per_ch, per_j, npooled = hist[-1]["r2_oracle_val"], hist[-1]["r2_per_channel"], \ hist[-1]["r2_per_action_index"], hist[-1]["r2_oracle_val_noised"] res = dict( cache=a.cache, out=a.out, mode=a.mode, offsets=list(offsets), n_act=n_act, noise_rel=a.noise_rel, steps=a.steps, hidden=a.hidden, layers=a.layers, split_seed=a.split_seed, n_train_eps=len(data.d.train_eps), n_val_eps=len(data.d.val_eps), n_train_anchors=int(len(data.anchors["train"])), n_val_anchors=int(len(data.anchors["val"])), params=int(sum(p.numel() for p in model.parameters())), # BAR 1 of the registered read-out r2_oracle_val=pooled, r2_oracle_val_noised=npooled, r2_per_action_index=per_j, r2_per_channel=per_ch, df_action_head_bar=dict(threading_single=0.569, threading_Kmean=0.711, mug_single=0.283, mug_Kmean=0.474, source="status/nb/df_actprobe/*.json, FINDING H"), bar1_pass=bool(pooled >= 0.711), delta_std_mean=float(data.delta_std.mean()), act_mean=[float(v) for v in data.act_mean], act_std=[float(v) for v in data.act_std], inputs="normalised 1545-d state (DINOv2 z 1536 + proprio 9) from cache/<task> ONLY; " "supervision = cache/<task>/act.f32.npy; no reward, no goal, no sim state", history=hist, ) js_path.write_text(json.dumps(res, indent=1)) print(f"[df_idm] wrote {js_path} BAR1 r2_oracle_val={pooled:+.4f} " f"(bar 0.711) pass={res['bar1_pass']}", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231#!/usr/bin/env python"""DOES DECODING DF'S PLANNED LATENTS WITH AN IDM BEAT DF'S OWN DIFFUSED ACTION CHANNEL?(gen_q#274, stream DF_MAKEITWORK, run 36.) Held-out episodes, NO environment, NO success number.
This is BAR 2 of the read-out registered in `df_idm.py`'s header, and it is the decisive one.It measures, ON THE SAME held-out states, in the SAME script, with the SAME R2 definition:
1. `df_head` DF's own diffused ACTION channel -- the arm every landed RISE DF cell executed. Scored at every lag in {-2,-1,0,+1,+2} the way `df_actprobe.py` does, and the BEST lag is the number the IDM must beat, so DF's own head is never handicapped by an indexing convention. (df_G0 is trained with `act_align=upstream`, so its bundle token h is (obs_{t+h+1}, a_{t+h}) and lag -1 in df_actprobe's indexing is the aligned one; both are reported.) 2. `idm_plan` the IDM decoding DF's PLANNED OBSERVATION LATENTS -- the proposed arm. The anchor is the TRUE current observation (exactly what the encoder gives the policy at planning time); every other frame is DF's prediction. Nothing else enters. 3. `idm_oracle` the IDM decoding the TRUE future observations on the same states. A DIAGNOSTIC UPPER BOUND ONLY -- it reads the future and can never be a policy. Labelled as such everywhere, exactly like `df_poolcmp.py`'s `r2_oracle`.
and, because a selection rule that ties across its own pool IS random-of-N however good its number,the OFFLINE form of the fairness controls, over the IDENTICAL candidate pool: `argmaxJ` / `random` / `Kmean` decoded R2, the selection gap (argmaxJ - random), the J spread, the fraction of states whose J ties at the max, and the pool's own action spread.
FAIRNESS. The held-out expert action is used ONLY as the R2 target and for the oracle diagnostic;it never reaches the planner, the guidance or the decoder. No RSM / IQL critic touches anycandidate (rule 7). No goal guidance. Guidance scale is swept over the same {0, 5} the rest of thestream uses; nothing privileged is added at any scale.
usage: python df_idm_probe.py --ckpt runs/<task>/wm/df_G0/ckpt_s40000.pt --cache cache/<task> \ --idm-dir runs/<task>/idm/k1_n0 --idm-dir runs/<task>/idm/k8_n1 ... \ --out status/nb/df_idm/<task>_probe.json"""from __future__ import annotations
import argparseimport jsonimport osimport sysfrom pathlib import Path
import numpy as npimport torch
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from df_data import DFCacheData, OBS_DIM, ACT_DIM # noqa: E402from df_probe import load_df # noqa: E402from df_plan import plan_bundles # noqa: E402from df_idm import MODES, load_idm, decode_plan as decode, r2_vs_mean_action # noqa: E402
A0, A1 = OBS_DIM, OBS_DIM + ACT_DIM
@torch.no_grad()def main(): p = argparse.ArgumentParser() p.add_argument("--ckpt", required=True) p.add_argument("--cache", required=True) p.add_argument("--idm-dir", action="append", default=[]) p.add_argument("--out", required=True) p.add_argument("--best-out", default="") p.add_argument("--n-states", type=int, default=64) p.add_argument("--kmax", type=int, default=32) p.add_argument("--execute-frames", type=int, default=8) p.add_argument("--guidance", type=float, action="append", default=[]) p.add_argument("--gamma", type=float, default=0.95) p.add_argument("--seed", type=int, default=0) a = p.parse_args() guids = a.guidance or [0.0, 5.0] 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) T = data.T bundle, mask = data.sample(a.n_states, rng, split="val", device=dev) # [W,B,C], W=T+1 init_obs = bundle[0, :, :OBS_DIM] B = init_obs.shape[0] mean_act = torch.as_tensor(np.asarray(data.act, np.float32).mean(0), device=dev) ne = int(a.execute_frames)
idms = [] for d in a.idm_dir: try: m, ck = load_idm(d, dev) except FileNotFoundError: print(f"[df_idm_probe] MISSING idm {d} -- skipped", flush=True) continue idms.append((Path(d).name, d, m, ck)) if not idms: raise SystemExit("[df_idm_probe] no IDM checkpoints found -- train first")
res = dict(ckpt=a.ckpt, cache=a.cache, df_step=step, n_states=B, kmax=a.kmax, execute_frames=ne, gamma=a.gamma, guidances=guids, frame_stack=int(meta["frame_stack"]), act_align=meta.get("act_align"), note=("DF plans observation latents; the IDM decodes them into actions. " "idm_oracle reads the TRUE future and is a DIAGNOSTIC UPPER BOUND, never a " "policy."), by_guidance={})
# true-future observation sequence for the oracle diagnostic: O_true[j] = obs_{t+j} O_true = bundle[:, :, :OBS_DIM] # [W,B,D] valid = mask.bool() # [W,B]
for g in guids: out = plan_bundles(model, init_obs, horizon_frames=T, guidance_scale=g, gamma=a.gamma, n_plans=a.kmax, device=dev) plan, J = out["plan"], out["J"] # [T,B,K,C], [B,K] K = plan.shape[2] P = plan[..., :OBS_DIM] # planned obs, P[h] = obs_{t+h+1} O = torch.cat([init_obs[None, :, None, :].expand(1, B, K, OBS_DIM), P], 0) # [T+1,B,K,D]
# ---- the candidate-selection controls, computed once per guidance -------------------- jn = J.detach().cpu().numpy() idx_max = J.argmax(-1) gen = torch.Generator(device=dev); gen.manual_seed(1234) idx_rnd = torch.randint(K, (B,), device=dev, generator=gen) ties = float(np.mean([(np.abs(r - r.max()) <= 1e-8).sum() for r in jn])) cell = dict(J_mean=float(jn.mean()), J_spread=float((jn.max(1) - jn.min(1)).mean()), J_std_within_state=float(jn.std(1).mean()), ties_at_max_mean=ties, ties_at_max_frac=float(ties / K), frac_states_all_tied=float(np.mean( [(np.abs(r - r.max()) <= 1e-8).sum() == K for r in jn])), n_candidates=int(K))
def score(actKBA, tag, store): """actKBA [ne,B,K,ACT] -> R2 of Kmean / argmaxJ / random picks against a_{t..t+ne-1}.""" ar = torch.arange(B, device=dev) picks = dict(Kmean=actKBA.mean(2), argmaxJ=actKBA[:, ar, idx_max], random=actKBA[:, ar, idx_rnd], single=actKBA[:, :, 0]) o = {} for name, pr in picks.items(): Pp, Tg = [], [] for h in range(ne): w = valid[h] if w.sum() == 0: continue Pp.append(pr[h][w]); Tg.append(bundle[h][w, A0:A1]) pooled, per_ch = r2_vs_mean_action(torch.cat(Pp), torch.cat(Tg), mean_act) o[name] = dict(r2=pooled, r2_per_channel=per_ch, n=int(sum(x.shape[0] for x in Pp))) o["selection_gap_argmaxJ_minus_random"] = o["argmaxJ"]["r2"] - o["random"]["r2"] o["pool_act_std_over_tgt"] = float( (actKBA.std(2).mean() / bundle[:ne][valid[:ne]][:, A0:A1].std(0).mean()).item()) store[tag] = o return o
arms = {} # ---- arm 1: DF's own diffused action channel, every lag (df_actprobe's protocol) ------- dfa = plan[..., A0:A1] # [T,B,K,ACT] per_lag = {} for lag in (-2, -1, 0, 1, 2): Pp, Tg = [], [] for h in range(ne): j = h + lag # plan index h predicts a_{t+h+lag} if j < 0 or j >= bundle.shape[0]: continue w = valid[j] if w.sum() == 0: continue Pp.append(dfa[h][w].mean(1)); Tg.append(bundle[j][w, A0:A1]) if not Pp: continue pooled, _ = r2_vs_mean_action(torch.cat(Pp), torch.cat(Tg), mean_act) per_lag[str(lag)] = dict(r2_Kmean=pooled, n=int(sum(x.shape[0] for x in Pp))) best_lag = max(per_lag, key=lambda k: per_lag[k]["r2_Kmean"]) if per_lag else None score(dfa[:ne], "df_head", arms) arms["df_head"]["per_lag_Kmean"] = per_lag arms["df_head"]["best_lag"] = best_lag arms["df_head"]["r2_best_lag_Kmean"] = per_lag[best_lag]["r2_Kmean"] if best_lag else None
# ---- arms 2/3: each IDM on planned latents, and on the true future (diagnostic) -------- for name, d, m, ck in idms: score(decode(m, ck, O, ne), f"idm_plan::{name}", arms) Ot = O_true[:, :, None, :].expand(-1, -1, 1, -1) # [W,B,1,D] arms[f"idm_oracle::{name}"] = {} oc = decode(m, ck, Ot, ne) # [ne,B,1,ACT] Pp, Tg = [], [] for h in range(ne): w = valid[h] if w.sum() == 0: continue Pp.append(oc[h][w][:, 0]); Tg.append(bundle[h][w, A0:A1]) pooled, per_ch = r2_vs_mean_action(torch.cat(Pp), torch.cat(Tg), mean_act) arms[f"idm_oracle::{name}"] = dict( r2=pooled, r2_per_channel=per_ch, n=int(sum(x.shape[0] for x in Pp)), DIAGNOSTIC_UPPER_BOUND="reads the TRUE future observation; never a policy")
cell["arms"] = arms res["by_guidance"][str(g)] = cell
dfb = arms["df_head"]["r2_best_lag_Kmean"] print(f"\n[df_idm_probe] guidance {g} DF head R2 (best lag {best_lag}) {dfb:+.4f} " f"| lag0 {arms['df_head']['Kmean']['r2']:+.4f}", flush=True) for name, *_ in idms: ip = arms[f"idm_plan::{name}"] io = arms[f"idm_oracle::{name}"] print(f" IDM {name:<12s} on-plan Kmean {ip['Kmean']['r2']:+.4f} " f"argmaxJ {ip['argmaxJ']['r2']:+.4f} random {ip['random']['r2']:+.4f} " f"gap {ip['selection_gap_argmaxJ_minus_random']:+.4f} " f"| oracle-obs {io['r2']:+.4f} (diagnostic)", flush=True)
# ---- BAR 2 verdict, decided on a held-out, environment-free metric only ------------------- g0 = str(guids[0]) base = res["by_guidance"][g0]["arms"]["df_head"] df_bar = max(v for v in [base["r2_best_lag_Kmean"], base["Kmean"]["r2"]] if v is not None) best, best_r2 = None, -1e9 for name, *_ in idms: r = res["by_guidance"][g0]["arms"][f"idm_plan::{name}"]["Kmean"]["r2"] if r > best_r2: best, best_r2 = name, r res["bar2"] = dict(df_head_bar=df_bar, best_idm=best, best_idm_r2_on_plan=best_r2, pass_=bool(best_r2 > df_bar), guidance_used=float(guids[0]), rule="IDM decoding DF's OWN planned latents must beat DF's own action head " "at its BEST lag, on the same held-out states, or the decoder is not " "the fix and that is what gets reported.") Path(a.out).parent.mkdir(parents=True, exist_ok=True) Path(a.out).write_text(json.dumps(res, indent=1)) if a.best_out: Path(a.best_out).parent.mkdir(parents=True, exist_ok=True) Path(a.best_out).write_text(f"{best}\n") print(f"\n[df_idm_probe] BAR2 df_head {df_bar:+.4f} best IDM {best} {best_r2:+.4f} " f"pass={res['bar2']['pass_']}\n[df_idm_probe] wrote {a.out}", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200"""Diffusion Forcing AS A PLANNER, guided by the binary data-provenance reward (gen_q#274).
This is upstream's `df_planning.py:plan()` loop -- the same pyramid scheduling matrix, the sameconditioning token, the same `diffusion_model.sample_step(..., guidance_fn=...)` -- with ONEsubstitution, and it is the substitution the issue asks for:
upstream guides toward a GOAL observation (`goal_guidance`, df_planning.py:148). we guide toward the REWARD channel.
Why the substitution is forced rather than chosen: a goal observation is privileged information noother column in tab:flagship receives, so a goal-guided DF would not be a fair baseline; andupstream's own reward branch is inert --
df_planning.py:180-182 else: # dense reward seeting, guide with reward raise NotImplementedError("reward guidance not officially supported yet, although implemented")
-- so there is no released reward-guidance code to run. The three lines beneath that raise are therecipe we implement: a reconstruction weight on the conditioning frames, a geometric weight over theplan horizon, zero on the padding. Upstream hard-codes 0.997; we use the cell's own gamma, because#274 asks for the horizon to be reported as H = 1/(1-gamma), the same family #273 sweeps.
GUIDANCE OBJECTIVE. With the plan's predicted x0 bundle decoded to (obs, act, r_hat): J = sum_j w_j * r_hat_j, w = [w_cond]*frame_stack + [gamma^j for j < H] + [0]*pad guidance_fn returns guidance_scale * J, and upstream's sample_step adds grad_x J to the denoiser's mean (models/diffusion.py:424-440).r_hat is DF's own predicted reward channel, trained on the provenance label -- so nothing outsidethe shared reward enters, and DF needs none of the project's separate reward heads.
CANDIDATES. `n_plans` independent plans are diffused in one batch from the same conditioningobservation and the executed one is argmax_J. This is NOT the shared 128-candidate set the valuecolumns rank -- DF proposes its own actions, which is what "run it as a planner" means -- so thenumber is disclosed with every score, per #274 ("never compare a 16-candidate planner to a128-candidate one silently").
PLANNER DIAGNOSTICS, returned on every call and logged per control step: J_mean / J_std / J_spread the guidance objective across the n_plans candidates (sample spread); J_iter J after each step of the scheduling matrix (per-iteration improvement); J_gain J_iter[-1] - J_iter[0].A cell whose J_spread is ~0 has a planner that is not discriminating between its own samples, and acell whose J_gain is <= 0 has guidance that is not working; both must be visible next to the score.
THE REWARD CHANNEL IS UNBOUNDED, AND `r_max` IS THE OPT-IN SATURATION (gen_q#274/#282, 2026-09-24).r_hat is not a bounded head: it is one raw continuous channel of the diffused bundle(df_core.py:94, "Bundle = [obs (1545) | act (7) | reward (1)]"), read back through`model.unnorm(...)` -- so the units of `plan` and of `objective` are RAW LABEL UNITS, the same unitsas DFCacheData's `ep_success`, which is BINARY and lives in {0, 1}. Nothing in the diffusion or inthe guidance constrains r_hat to that interval, so ascending J can be solved by pushing r_hat ABOVEthe label's own maximum, which is a region the model only ever extrapolates into.`r_max=None` (the default) is the original, unbounded objective -- byte-identical to every landednumber. `r_max=1.0` replaces r_hat by min(r_hat, 1.0) EVERYWHERE the objective is evaluated: in theJ returned for candidate ranking AND inside `guidance_fn`, whose gradient upstream takes with`torch.autograd.grad` (models/diffusion.py:424-440) -- and the gradient of `clamp` in the saturatedregion is exactly ZERO, which is the whole point: once a frame's predicted provenance has reached thelabel maximum, guidance stops pushing on it.FAIRNESS: 1.0 is the maximum of the binary data-provenance label itself, which is the reward everycolumn in tab:flagship shares. It is not privileged simulator state, not an outcome reward, not asuccess bit, and no RSM/IQL critic is involved. Only the DEFINITION of the shared reward is used."""from __future__ import annotations
import numpy as npimport torch
from df_data import OBS_DIM, ACT_DIM, BUNDLE_DIM
def _guidance_weights(frame_stack, horizon_frames, total_frames, gamma, w_cond=10.0, device="cpu"): """Upstream's dead-code recipe: [10]*frame_stack + [gamma**j]*horizon + [0]*pad.""" w = np.zeros(total_frames, np.float32) w[:frame_stack] = w_cond h = min(horizon_frames, total_frames - frame_stack) if gamma > 0: w[frame_stack:frame_stack + h] = gamma ** np.arange(h, dtype=np.float32) else: w[frame_stack:frame_stack + h] = 1.0 return torch.from_numpy(w).to(device)
@torch.no_grad()def plan_bundles(model, init_obs, horizon_frames, guidance_scale, gamma, n_plans=1, device="cuda", generator=None, w_cond=10.0, collect_iters=True, r_max=None): """init_obs [B, OBS_DIM] (already in the project's z-scored state units).
init_obs may also be [B, frame_stack, OBS_DIM] -- the agent's own last `frame_stack` observations, oldest first -- for a checkpoint trained with `--cond-history 1` (DF_MAKEITWORK mug-WM sweep, 2026-09-24). The 2-D path is untouched and bit-identical, so every landed number and every existing checkpoint reads exactly as before. See `DFRise.make_sequence` for why an observation history is not privileged information.
r_max: None = the original unbounded objective (default, bit-identical to every landed number); a float = saturate the predicted reward at that value in J and in the guidance gradient.
Returns dict: plan [horizon_frames, B, n_plans, BUNDLE_DIM] UNNORMALISED bundles (obs | act | r_hat) J [B, n_plans] guidance objective of each candidate at the end of diffusion J_iter [M, B, n_plans] the same objective after each scheduling-matrix step diag dict of the planner diagnostics described in the module docstring """ fs = model.frame_stack B = init_obs.shape[0] plan_tokens = int(np.ceil(horizon_frames / fs)) total_frames = fs * (1 + plan_tokens) sched = model.scheduling(plan_tokens) S = model.sampling_timesteps
# conditioning token: the current observation, actions/rewards zeroed after normalisation if init_obs.dim() == 3: # [B, fs, OBS_DIM] -- real observation history assert init_obs.shape[1] == fs, (init_obs.shape, fs) init = torch.zeros(B * n_plans, fs, BUNDLE_DIM, device=device) init[:, :, :OBS_DIM] = init_obs.repeat_interleave(n_plans, 0) init = model.norm(init) init[:, :, OBS_DIM:] = 0.0 init_tok = init.reshape(1, B * n_plans, fs * BUNDLE_DIM) else: init = torch.zeros(B * n_plans, BUNDLE_DIM, device=device) init[:, :OBS_DIM] = init_obs.repeat_interleave(n_plans, 0) init = model.norm(init) init[:, OBS_DIM:] = 0.0 init_tok = init.view(1, B * n_plans, 1, BUNDLE_DIM).repeat(1, 1, fs, 1).reshape( 1, B * n_plans, fs * BUNDLE_DIM)
clip = float(model.cfg.clip_noise) chunk = torch.randn((plan_tokens, B * n_plans, fs * BUNDLE_DIM), device=device, generator=generator).clamp(-clip, clip) plan = torch.cat([init_tok, chunk], 0)
wts = _guidance_weights(fs, horizon_frames, total_frames, gamma, w_cond, device)
def objective(x_stacked): """x_stacked [t, b, fs*C] (normalised x0) -> scalar sum over the batch of weighted r_hat.
`model.unnorm` puts r in RAW LABEL UNITS (the binary provenance label's own {0,1}), so the clamp below is stated in those units and nothing else has to be converted.""" r = model.unnorm(model.unstack(x_stacked))[..., -1] # [total_frames, b] if r_max is not None: r = r.clamp(max=float(r_max)) # zero gradient above r_max return (r * wts[:, None]).sum(0)
def guidance_fn(x0): return guidance_scale * objective(x0).sum()
gfn = guidance_fn if guidance_scale else None J_iter = [] if collect_iters: J_iter.append(objective(plan).view(B, n_plans).cpu().numpy()) for m in range(sched.shape[0] - 1): frm = torch.from_numpy(np.concatenate([[0], sched[m]])).to(device) to = torch.from_numpy(np.concatenate([[0], sched[m + 1]])).to(device) frm = frm[:, None].repeat(1, B * n_plans) to = to[:, None].repeat(1, B * n_plans) plan[1:] = model.diffusion_model.sample_step(plan, None, frm, to, guidance_fn=gfn)[1:] if collect_iters: J_iter.append(objective(plan).view(B, n_plans).cpu().numpy())
full = model.unnorm(model.unstack(plan)) # [total_frames, b, C] body = full[fs:fs + horizon_frames].view(horizon_frames, B, n_plans, BUNDLE_DIM) J = objective(plan).view(B, n_plans) # RAW (never clamped) predicted reward over the whole sequence, so the saturation diagnostic is # measurable in both arms: how much of the objective's weight sits above the label maximum. r_raw = full[..., -1] # [total_frames, b] r_ref = 1.0 if r_max is None else float(r_max) wpos = wts > 0 Ji = np.stack(J_iter) if collect_iters else None Jn = J.cpu().numpy() diag = dict(J_mean=float(Jn.mean()), J_std=float(Jn.std()), J_spread=float((Jn.max(1) - Jn.min(1)).mean()) if n_plans > 1 else 0.0, J_gain=float((Ji[-1] - Ji[0]).mean()) if Ji is not None else float("nan"), n_plans=int(n_plans), guidance_scale=float(guidance_scale), gamma=float(gamma), w_cond=float(w_cond), # so status/nb/df_jrange.py never has to assume 10.0 W_cond_total=float(w_cond) * int(fs), W_plan_total=float(wts[fs:].sum().item()), horizon_frames=int(horizon_frames), plan_tokens=int(plan_tokens), sampling_steps=int(S), sched_rows=int(sched.shape[0]), # --- reward-range diagnostics, in RAW label units (label max = 1.0) --- r_max=(None if r_max is None else float(r_max)), clamped=bool(r_max is not None), rhat_raw_mean=float(r_raw[wpos].mean().item()), rhat_raw_max=float(r_raw[wpos].max().item()), rhat_raw_min=float(r_raw[wpos].min().item()), rhat_raw_p99=float(torch.quantile(r_raw[wpos].flatten().float(), 0.99).item()), # fraction of the OBJECTIVE-CARRYING frames whose raw r_hat is above the label max frac_frames_above_rmax=float((r_raw[wpos] > r_ref).float().mean().item()), frac_cond_frames_above_rmax=float((r_raw[:fs] > r_ref).float().mean().item()), frac_plan_frames_above_rmax=float( (r_raw[fs:fs + horizon_frames] > r_ref).float().mean().item()), # share of J's weight that the clamp would remove / removed J_excess_above_rmax=float( (((r_raw - r_ref).clamp(min=0)) * wts[:, None]).sum(0).mean().item())) return dict(plan=body, J=J, J_iter=Ji, diag=diag)
def best_actions(out, execute_frames): """argmax_J candidate -> [execute_frames, B, ACT_DIM] actions to execute before replanning.""" plan, J = out["plan"], out["J"] idx = J.argmax(-1) # [B] B = plan.shape[1] sel = plan[:, torch.arange(B, device=plan.device), idx] # [H, B, C] return sel[:execute_frames, :, OBS_DIM:OBS_DIM + ACT_DIM], sel123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432"""Diffusion Forcing driving the REAL eval harness, as a planner (gen_q#274, order-of-work item 1).
WHY A WRAPPER AND NOT A SCORER BACKEND. Every other column in tab:flagship is a *value function*:RISE's diffusion policy proposes 128 action chunks and the column ranks them (rsm_planner.py:377,`plan_get_action`). Diffusion Forcing is not a value function -- #274 asks for it "as a planner", anda planner proposes its OWN actions. So DF cannot enter through `rsm_backend`; it replaces the actioninstead of ranking someone else's. That is also why its candidate count is reported separately andnever silently compared against a 128-candidate value column.
WHAT IS HELD FIXED, so the DF row is comparable with the RSM / DINO-WM / IDQL / IFQL rows: * the env, the initial-state distribution, the rollout loop, the horizon and the success test -- untouched, because we install ourselves by replacing `policy.policy.get_action` on the ALREADY CONSTRUCTED robomimic policy object (`install(policy, ...)` below). No harness file is edited, which also keeps this stream out of gen_q#273's way in rsm_planner.py / rsm_scorer.py. * the observation encoder -- `rsm_scorer.PooledDinoState`, the project's own frozen DINOv2 ViT-S/14 cls+GeM pooling with the task cache's feat_stats. DF sees exactly the state the RSM scorer sees. * the control rate -- DF executes `execute_frames` (default 8 = the project's hop/chunk) actions per plan and then replans, which is the same cadence at which the value columns commit a chunk. * the reward -- DF's own predicted reward channel, trained on the binary provenance label. Nothing outside the shared reward enters the guidance (df_plan.py's module docstring).
WHAT IS NOT UPSTREAM'S. The guidance is our implementation of the configuration upstream leaves as`raise NotImplementedError` (df_planning.py:180-182). Finding F1 in status/NEW_BASELINES_DONE; itmust be printed beside every DF number.
HEALTH, published beside every score (#274 item 3): * rollout fidelity vs the true future -- written by the TRAINER into health.jsonl (`fid/obs_rmse_h<H>` against `fid/obs_rmse_h<H>_naive`, the stay-put predictor). A ratio >= 1 means the model predicts nothing and the score is flagged, not published bare. * planner diagnostics -- accumulated here over every control step of every episode and written to the cell JSON: J_mean / J_std / J_spread (sample spread) and J_gain (per-iteration improvement). A cell with J_spread ~ 0 is not discriminating among its own samples; a cell with J_gain <= 0 has guidance that is not doing anything. Both are failure modes that would otherwise hide inside a plausible-looking success rate."""from __future__ import annotations
import jsonimport osimport sysfrom pathlib import Path
import numpy as npimport torch
sys.path.insert(0, str(Path(__file__).resolve().parent))
from df_core import DFRise # noqa: E402from df_data import OBS_DIM, ACT_DIM # noqa: E402from df_plan import plan_bundles, best_actions # noqa: E402
def load_df(ckpt, device="cuda"): """ckpt_s*.pt / ckpt_last.pt are self-describing: model, cfg, meta, mean, std, step.""" ck = torch.load(ckpt, map_location="cpu", weights_only=False) meta = ck["meta"] m = DFRise(frame_stack=int(meta["frame_stack"]), n_tokens=int(meta["n_tokens"]), mean=ck["mean"], std=ck["std"], cfg=ck["cfg"]) m.load_state_dict(ck["model"]) # the EMA weights return m.to(device).eval(), meta, int(ck.get("step", -1))
class DFPlannerPolicy: """Replaces `get_action` on a robomimic policy. Same signature, same units, same cadence."""
def __init__(self, ckpt, feat_stats, *, horizon_frames, guidance_scale, gamma, n_plans=128, execute_frames=8, device="cuda", seed=0, img_layout="chw", diag_path="", act_limit=1.0, select="argmax"): from robomimic.algo.rsm_scorer import PooledDinoState self.model, self.meta, self.step = load_df(ckpt, device) self.enc = PooledDinoState(feat_stats, img_layout=img_layout).to(device).eval() \ if _accepts_layout() else PooledDinoState(feat_stats).to(device).eval() self.device = device self.H = int(horizon_frames) self.guidance_scale = float(guidance_scale) self.gamma = float(gamma) self.n_plans = int(n_plans) # select="random" -- the RANDOM-OF-N CONTROL the owner requires beside every guidance arm # (blocker, 2026-09-23 19:45Z). IDENTICAL candidates: same model, same guidance scale, same # generator and the same n_plans bundle; only the pick among them changes from argmax_J to a # uniform draw. Without it, a guided arm that lands on the BC floor cannot be told apart # from a planner whose J does not order its own samples. self.select = str(select) # select="mean" -- run 32 (gen_q#274). NOT a selection rule: it is a DECODING rule, and it # is published as such. `df_actprobe` measured, on held-out episodes with no environment, # that DF's action head IS informative but that a SINGLE diffusion sample is a much worse # estimate of the expert action than the mean of several samples: # threading df_A s20000 R2 vs mean-action baseline single 0.569 -> K=32 mean 0.711 # mug df_A s20000 single 0.283 -> K=32 mean 0.474 # (status/nb/df_actprobe/*.json, `per_h["0"]`). The planner executes ONE sampled candidate # -- argmax_J or, in the control, a uniform draw -- so every landed DF cell has been acting # on the 0.569 estimator while the 0.711 one costs nothing extra: the n_plans candidates are # already drawn. Averaging them is the model's own posterior mean over its own samples. # NO NEW INFORMATION ENTERS: same checkpoint, same state, same reward, same candidates. # Its control is the single-sample arm, which is already measured (select=random, 0.000). # Because it does not rank, `J_rank_executed` is undefined and reported as -1. if self.select not in ("argmax", "random", "mean"): raise ValueError(f"select must be argmax|random|mean, got {select!r}") # w_cond -- the weight df_plan.py's guidance puts on EACH of the frame_stack conditioning # frames' reward channel. 10.0 is upstream's number, but upstream's reward-guidance block is # dead code that cannot execute (undefined `h`; `episode_return` never reduced to a scalar -- # df_planning.py:180-186), so the 10.0 has never been run by anyone and is a free # hyper-parameter here, not a published setting. It matters because its TOTAL weight is # w_cond*frame_stack = 80.0 against W_plan = 31.8 at H = 50, i.e. most of the guidance # gradient asks the denoiser to re-explain the CURRENT observation as expert-provenance # rather than to plan a better future (status/nb/df_jrange.txt). Default unchanged, so every # already-measured cell is reproduced byte-for-byte; RR_DF_WCOND=0 is the arm that tests it. self.w_cond = float(os.environ.get("RR_DF_WCOND", "10.0")) # ---- RR_DF_DECODE (run 36, stream DF_MAKEITWORK) -- ADDITIVE, default unchanged -------- # "diffused" (default) executes DF's OWN diffused action channel -- byte-identical to every # cell measured so far. "idm" executes a LEARNED INVERSE DYNAMICS DECODER applied to DF's # planned OBSERVATION latents. # # DECLARE IT LOUDLY, every time: with RR_DF_DECODE=idm this column is no longer "DF emits # actions", it is "DF plans states, a learned decoder emits actions". That is what # upstream's own headline maze2d numbers do -- df_planning.py:272-320 executes a HAND-WRITTEN # PD controller (gains 12.5 / 1.2) on diffused POSITIONS whenever action_dim != 2, which is # upstream's own recommended recipe (README 71/126, `dataset.action_mean=[]`), and our # main-branch gate measured 46.3 +- 1.5 for that arm against 15.1 +- 1.1 for the diffused- # action arm (LSF 1895313). There is no analytic PD law from a 1545-d DINOv2 latent to a # 7-DoF OSC action, so the general form of that controller is a learned IDM. Both arms are # published side by side and the swap is never silent: it is in the CELL NAME, in the diag # JSON below, and it must be in the table caption. # # NO NEW INFORMATION ENTERS. The IDM is trained on cache/<task>'s own (obs_t, obs_{t+k}) -> # act_t pairs -- the same corpus, the same frozen encoder, the same held-out split, and # actions as supervision, which is exactly what every BC column is trained on. It sees no # reward, no goal, no success bit and no simulator state (code/df_rise/df_idm.py's header # enumerates its inputs). At run time its anchor frame is the TRUE current observation from # the same PooledDinoState encoder every other column uses; every other frame it reads is # DF's own prediction. self.decode = str(os.environ.get("RR_DF_DECODE", "diffused")) if self.decode not in ("diffused", "idm"): raise ValueError(f"RR_DF_DECODE must be diffused|idm, got {self.decode!r}") self.idm = self.idm_ck = None self.idm_dir = "" if self.decode == "idm": from df_idm import load_idm self.idm_dir = os.environ.get("RR_DF_IDM", "") if not self.idm_dir: raise RuntimeError("RR_DF_DECODE=idm needs RR_DF_IDM=<idm run dir>") self.idm, self.idm_ck = load_idm(self.idm_dir, device) print(f"[gen_q#274 run36] DF -> IDM decoder: {self.idm_dir} mode={self.idm_ck['mode']} " f"offsets={self.idm_ck['offsets']} n_act={self.idm_ck['n_act']} " f"noise_rel={self.idm_ck['noise_rel']} idm_step={self.idm_ck['step']} -- " f"THIS COLUMN IS 'DF PLANS STATES, A LEARNED DECODER EMITS ACTIONS'") self.execute_frames = int(execute_frames) self.gen = torch.Generator(device=device); self.gen.manual_seed(int(seed)) self.diag_path = diag_path self.act_limit = float(act_limit) self.reset()
# ---- state ------------------------------------------------------------ def reset(self): # NOTE: no action queue is kept here on purpose -- `get_action` returns the whole chunk and # `rollout.py` executes it before calling again (see get_action's docstring). self._diag = [] # one record per PLAN (not per env step) # action-range health (gen_q#274 run 5). DF's action channel is a DIFFUSED CONTINUOUS # VARIABLE with nothing constraining it to the env's box: `best_actions` slices the raw # unnormalised bundle (df_plan.py:best_actions). The CPU smoke measured |a|_max = 2.48 on an # untrained model (status/nb/df_plan_smoke.txt, T6). robosuite clips to the action spec # anyway, so an unclipped DF is not unfair -- but it means the trajectory the planner scored # is NOT the trajectory the env executed, which silently breaks the guidance's own premise. # So we clamp to the same box the env enforces and PUBLISH how often it bit: a cell with a # high clip fraction is a cell whose planner is planning outside the action space. self._n_act = 0 # scalar action components emitted self._n_clip = 0 # how many of them were outside the box self._a_absmax = 0.0
# ---- resume: carry THIS planner's state across a preemption ------------ # FINDING AJ (stream DF_MAKEITWORK, 2026-09-24). The plan sampler's whole stochasticity is one # draw per plan from `self.gen` (df_plan.py:111), and `self.gen` is seeded ONCE in __init__ # (:148). eval.py's episode-level resume restores the env's numpy MT19937 state exactly # (eval.py:_rng_state_dump / _rng_state_load), so a resumed cell ran the RIGHT initial states # with the WRONG noise: episode k drew from the generator's INITIAL state instead of its # post-k-episodes state. Measured on # runs/threading_expert_play/eval_onactor/df274idm/ # E1-DFG0s40000-R0.95-20-plan-Ndf128-g0.0-idmk8_n10-DF274IDM-es1-sS0As0-s0.json # (resumed_from_episode=44): episodes 0..43 identical to the two fresh cells of that column, # episodes 44..49 0/6 successes against 3/6 fresh. # The health accumulators have the same shape of bug for REPORTING: nothing clears or carries # them either (this harness never calls robomimic's `start_episode`, so install()'s reset() # chain below never fires), so a resumed cell published TAIL-ONLY health as if it were the whole # cell -- `plans` read 300 against 2500 on the cell above. # So the resume carries both, through the same per-episode snapshot the numpy state uses. A # FRESH run never calls state_load(), which is why this leaves every landed cell reproducible # bit for bit. The generator's STATE is written in exactly two places -- manual_seed() in # __init__ (:148) and set_state() in state_load() below -- and is otherwise only CONSUMED, by # the plan draw (df_plan.py:112) and by the random-of-N pick (_random_actions / the IDM branch's # torch.randint). get_state() does not advance the stream, so snapshotting it every episode # costs a fresh run nothing and changes nothing. @staticmethod def _json_safe(rec): """A diag record with every value a JSON scalar.
plan_bundles already wraps every value in float()/int()/bool()/None (df_plan.py's `diag`), so this is a no-op today. It exists because this dict is now written into the .partial on EVERY episode: if a future diagnostic ever added a numpy scalar or a tensor, an unguarded json.dump would raise inside the per-episode snapshot and kill a RUNNING cell. Resume scaffolding must never be able to do that. """ out = {} for k, v in rec.items(): if v is None or isinstance(v, (bool, int, float, str)): out[str(k)] = v else: try: out[str(k)] = float(v) except Exception: out[str(k)] = repr(v) return out
def state_dump(self): """Everything of this planner that a resumed process must not restart from scratch.""" return { 'gen_device': str(self.device), # get_state() is a uint8 ByteTensor (CUDA: seed+offset, 16 B; CPU MT19937: 5056 B). 'gen_state_hex': bytes(self.gen.get_state().cpu().numpy().tobytes()).hex(), 'n_act': int(self._n_act), 'n_clip': int(self._n_clip), 'a_absmax': float(self._a_absmax), # The per-PLAN records verbatim, so the restored aggregate is computed by # diagnostics() over the same records in the same order a fresh run would have had -- # i.e. the resumed cell's health is identical, not merely close. ~30 JSON-safe scalars # per plan, 50 plans per episode; only ever written into "<cell>.json.partial". 'diag': [self._json_safe(d) for d in self._diag], }
def state_load(self, d): """Restore a state_dump(). True on success; False leaves the planner untouched.""" if not isinstance(d, dict) or not d.get('gen_state_hex'): return False # Parse EVERYTHING before mutating anything, so a malformed snapshot leaves this planner in # its fresh-from-__init__ state (the old behaviour, which the caller then warns about) # rather than half-restored. try: raw = bytes.fromhex(str(d['gen_state_hex'])) st = torch.frombuffer(bytearray(raw), dtype=torch.uint8).clone() n_act, n_clip = int(d.get('n_act', 0)), int(d.get('n_clip', 0)) a_absmax, diag = float(d.get('a_absmax', 0.0)), list(d.get('diag') or []) if not all(isinstance(r, dict) for r in diag): raise ValueError('diag is not a list of records') self.gen.set_state(st) except Exception as ex: print(f"[gen_q#274] DF resume: cannot restore the plan sampler's state ({ex!r}) -- " f"NOT restored") return False self._n_act, self._n_clip, self._a_absmax, self._diag = n_act, n_clip, a_absmax, diag return True
def diagnostics(self): """Aggregate over every plan of the cell -- what gets published beside the score.""" if not self._diag: return dict(n_plans=self.n_plans, plans=0) k = ["J_mean", "J_std", "J_spread", "J_gain"] out = {f"{x}": float(np.mean([d[x] for d in self._diag])) for x in k} out.update(bypassed_planner=getattr(self, "bypassed_planner", None), plans=len(self._diag), n_plans=self.n_plans, select=self.select, # run 36: which map from the chosen plan to the executed action was used. # "idm" means THIS CELL IS "DF plans states, a learned decoder emits actions". decode=self.decode, idm_dir=self.idm_dir, idm_mode=(self.idm_ck["mode"] if self.idm_ck else None), idm_offsets=(list(self.idm_ck["offsets"]) if self.idm_ck else None), idm_noise_rel=(float(self.idm_ck["noise_rel"]) if self.idm_ck else None), idm_step=(int(self.idm_ck["step"]) if self.idm_ck else None), guidance_scale=self.guidance_scale, gamma=self.gamma, horizon_frames=self.H, execute_frames=self.execute_frames, df_train_step=self.step, J_rank_executed=float(np.mean([d.get("J_rank_executed", 0.0) for d in self._diag])), J_spread_frac_zero=float(np.mean([d["J_spread"] <= 1e-8 for d in self._diag])), J_gain_frac_nonpositive=float(np.mean([d["J_gain"] <= 0 for d in self._diag])), act_limit=self.act_limit, act_absmax=self._a_absmax, act_clip_frac=(self._n_clip / self._n_act) if self._n_act else 0.0, act_components=self._n_act) if self.diag_path: Path(self.diag_path).write_text(json.dumps(out, indent=2)) return out
# ---- the harness entry point ----------------------------------------- @torch.no_grad() def get_action(self, obs_dict, goal_dict=None): """obs_dict [B, To, ...] exactly as robomimic hands it to the released get_action.
RETURNS AN ACTION CHUNK [B, execute_frames, ACT_DIM], which is the contract every IDQL cell in this project already runs under and NOT what an earlier revision of this file returned. Measured 2026-09-23 13:35Z (LSF 1881480): returning a single [B, ACT_DIM] action killed the cell at rollout_policies/robomimic_sampling_rollout_policy.py:94 actions = actions[:, 0, :] IndexError: too many indices for tensor of dimension 2 `get_policy_info` sets `action_chunking = True` for ROBOMIMIC+IDQL (eval.py:549-551) and `rollout.py:174-179` then queues `actions[:, i]` for i over the chunk axis -- i.e. the HARNESS owns the execute-k-then-replan cadence. Keeping a second queue in here would have made DF replan on a schedule no other column uses; the chunk is returned instead, so DF's cadence and the value columns' cadence are the same object. """ obs_t = {k: (v[:, -1] if v.dim() > 3 or (v.dim() == 3 and v.shape[1] > 1) else v[:, -1]) for k, v in obs_dict.items()} x = self.enc(obs_t) # [B, 1545] project state out = plan_bundles(self.model, x, self.H, self.guidance_scale, self.gamma, n_plans=self.n_plans, device=self.device, generator=self.gen, w_cond=self.w_cond) self._diag.append(dict(out["diag"])) if self.diag_path: # flush every plan: an eval that dies still has its health self.diagnostics() if self.decode == "idm": acts, rank = self._idm_actions(out, x) self._diag[-1]["J_rank_executed"] = float(rank) L = self.act_limit self._a_absmax = max(self._a_absmax, float(acts.abs().max())) self._n_act += int(acts.numel()) self._n_clip += int((acts.abs() > L).sum()) return acts.clamp(-L, L).permute(1, 0, 2).contiguous() if self.select == "argmax": acts, _ = best_actions(out, self.execute_frames) # [k, B, ACT_DIM] rank = 0.0 # argmax is rank 0 by construction elif self.select == "mean": plan = out["plan"] # [H, B, N, C] acts = plan[:self.execute_frames, :, :, OBS_DIM:OBS_DIM + ACT_DIM].mean(2) # [k, B, ACT_DIM] rank = -1.0 # no ranking happened else: # same bundle, uniform pick. Drawn from this policy's OWN generator so the control is # reproducible from (seed, cell) exactly like the argmax arm is. acts, rank = _random_actions(out, self.execute_frames, self.gen) # J_rank_executed: where the EXECUTED plan sat in the J ordering (0 = best). 0 on every # argmax plan by construction; ~ (N-1)/2 on the control. Published so the two arms cannot be # confused after the fact by reading the diag alone. self._diag[-1]["J_rank_executed"] = float(rank) L = self.act_limit self._a_absmax = max(self._a_absmax, float(acts.abs().max())) self._n_act += int(acts.numel()) self._n_clip += int((acts.abs() > L).sum()) return acts.clamp(-L, L).permute(1, 0, 2).contiguous() # [B, k, ACT_DIM]
def _idm_actions_impl(self, out, cur_obs): """DF plans observation latents -> the learned IDM decodes the executed chunk (run 36).
THE SELECTION RULE IS UNCHANGED AND THE CANDIDATE POOL IS IDENTICAL to the diffused-action arm: the same model, the same guidance scale, the same generator, the same `n_plans` bundle and the same J. Only the map from the CHOSEN plan to the executed action changes -- which is exactly the substitution upstream makes on maze2d (a PD controller instead of the diffused action), and it is measured beside the arm it replaces, never instead of it.
`select="random"` remains the random-of-N control over that identical pool; `select="mean"` decodes EVERY candidate and averages the decoded actions (the model's own posterior mean over its own samples, the same decoding rule the diffused arm's "mean" uses), so the controls the fairness rules require exist for this arm too. """ from df_idm import decode_plan plan, J = out["plan"], out["J"] # [H, B, N, C], [B, N] B, N = J.shape ar = torch.arange(B, device=plan.device) P = plan[..., :OBS_DIM] # planned observations, P[h] = o_{t+h+1} if self.select == "mean": sel = P # [H, B, N, OBS] idx, rank = None, -1.0 else: if self.select == "argmax": idx, rank = J.argmax(-1), 0.0 else: idx = torch.randint(N, (B,), device=plan.device, generator=self.gen) rank = (J > J.gather(1, idx[:, None])).sum(-1).float().mean().item() sel = P[:, ar, idx][:, :, None, :] # [H, B, 1, OBS] K = sel.shape[2] # O[0] is the TRUE current observation from the live encoder; O[j>=1] is DF's prediction. O = torch.cat([cur_obs[None, :, None, :].expand(1, B, K, OBS_DIM), sel], 0) acts = decode_plan(self.idm, self.idm_ck, O, self.execute_frames) # [k, B, K, ACT] return acts.mean(2), rank
DFPlannerPolicy._idm_actions = _idm_actions_impl
def _random_actions(out, execute_frames, gen): """best_actions() with a UNIFORM pick instead of argmax_J -- the random-of-N control.
Deliberately a sibling of df_plan.best_actions rather than a flag inside it: df_plan.py is vendored DF-adjacent code and the control is ours, so the diff stays on our side of the line.""" from df_plan import OBS_DIM, ACT_DIM plan, J = out["plan"], out["J"] # [H, B, N, C], [B, N] B, N = J.shape idx = torch.randint(N, (B,), device=plan.device, generator=gen) sel = plan[:, torch.arange(B, device=plan.device), idx] rank = (J > J.gather(1, idx[:, None])).sum(-1).float().mean().item() # 0 = the argmax was drawn return sel[:execute_frames, :, OBS_DIM:OBS_DIM + ACT_DIM], rank
def _accepts_layout(): import inspect from robomimic.algo.rsm_scorer import PooledDinoState return "img_layout" in inspect.signature(PooledDinoState.__init__).parameters
def install(policy, **kw): """Monkey-patch an already-built robomimic RolloutPolicy so the harness runs DF instead.
Returns the DFPlannerPolicy so the caller can read `diagnostics()` after the rollouts. The harness's own `start_episode` is chained to DF's `reset`, so each episode replans from scratch. """ df = DFPlannerPolicy(**kw) inner = getattr(policy, "policy", policy) # gen_q#274 run 5, disclosure guard. Replacing `get_action` SHADOWS the RISE planner entirely: # if the cell's config also has plan_n > 1, `plan_get_action` is never reached, yet # `planner_describe()` would still write that scorer's describe() into the cell JSON and the row # would read as if the RSM/IQL scorer had contributed to a DF number. Record the bypass so the # JSON says so, and say it on stdout where the slot log keeps it. try: _pn = inner.planner_cfg().get("plan_n") if hasattr(inner, "planner_cfg") else None _on = bool(getattr(inner, "planning_enabled", False)) except Exception: _pn, _on = None, False df.bypassed_planner = dict(plan_n=_pn, planning_was_enabled=_on) if _on: print(f"[gen_q#274] DF planner BYPASSES the cell's own ranked planner (plan_n={_pn}); " f"no RSM/IQL scorer contributes to this row -- DF proposes and selects its own " f"{df.n_plans} candidates.") inner.get_action = df.get_action # FINDING AJ: the handle eval.py's episode-level resume reaches this planner through, to carry # `self.gen` and the health accumulators across a preemption (see state_dump/state_load). It is # set on `inner` -- the algo -- so the harness finds it at policy.policy.policy, which is the # same handle eval.py already uses for `planner_describe` / `pop_plan_log`. # NOT a substitute for the start_episode chain below, and vice versa: THIS harness never calls # start_episode at all (no call site in sim_pipeline), which is why the chain never fires. inner._rr_df_planner = df if hasattr(policy, "start_episode"): _orig = policy.start_episode def start_episode(*a, **k): df.reset() return _orig(*a, **k) policy.start_episode = start_episode return df123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156"""IS DF'S CANDIDATE POOL SELECTABLE AT ALL, AND DOES ITS OBJECTIVE RANK IT? (gen_q#274 / #282)
Every DF cell reads 0.000: argmax_J, random-of-128 and mean-of-128 are all exactly 0.000 on 50episodes x 2 seeds x 2 tasks. Three decoding rules that differ only in WHICH of the same 128candidates gets executed cannot all land on the same number unless one of two things is true:
(H1) THE POOL IS DEAD. The 128 candidates are effectively the same chunk, so selection is a no-op by construction. Then no objective -- not DF's, not a perfect one -- can ever make the planner route work, and the route is dead until the GENERATOR is fixed. (H2) THE POOL IS FINE AND THE OBJECTIVE IS BLIND. The pool contains good chunks and J does not rank them, so every rule draws an equally bad candidate. Then the generator is fine and the whole problem is the objective (consistent with J_gain = +5.71..+16.33 while success = 0.000: DF maximises something, just not success).
This probe separates them on held-out episodes with NO environment and NO success number. It drawsone pool per state exactly as df_policy does (same plan_bundles, same guidance, same gamma) andscores each candidate's EXECUTED chunk against the expert's actions.
r2_random mean over candidates == what the random-of-N control executes r2_Kmean the K-sample mean chunk == what the mean-of-N arm executes r2_argmaxJ the candidate J picks == what every landed DF cell executes r2_oracle the per-state BEST candidate == the ceiling of ANY selection rule
`r2_oracle` uses the expert action to pick, so it is a DIAGNOSTIC UPPER BOUND, NOT A DF COLUMN and isnever to be quoted as a score. It bounds what a perfect scorer could extract from this pool.
oracle_gain = r2_oracle - r2_random the headroom selection could possibly capture captured = (r2_argmaxJ - r2_random) / oracle_gain the fraction J actually captures spearman_J corr(J_k, -err_k) within a state does J rank candidates in the right direction?
READ-OUT, REGISTERED IN ADVANCE (gen_q#274, before the numbers land): * oracle_gain <= 0.05 -> H1. The pool is dead; argmax == random == mean is FORCED by the generator and no objective fix can reach 10%. Report the planner route as blocked on the decoder, with this number as the evidence. * oracle_gain >= 0.20 and spearman_J <= 0.05 -> H2. The pool carries the headroom and J is blind to it; the objective is the entire problem and is worth unlimited effort. * spearman_J <= -0.05 -> J is ANTI-correlated with matching the expert: DF's objective actively prefers the worse candidate, which would explain argmax being no better than random."""from __future__ import annotationsimport argparse, json, os, sysimport numpy as npimport torch
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from df_data import DFCacheData, OBS_DIM, ACT_DIM # noqa: E402from df_probe import load_df # noqa: E402from df_plan import plan_bundles # noqa: E402
A0, A1 = OBS_DIM, OBS_DIM + ACT_DIM
def _rank(x, axis=-1): """average-free ordinal ranks along axis (ties broken by order; adequate for continuous J/err).""" order = np.argsort(x, axis=axis) r = np.empty_like(order) np.put_along_axis(r, order, np.arange(x.shape[axis]).reshape( [1] * (x.ndim - 1) + [x.shape[axis]]).repeat(x.shape[0], 0), axis=axis) return r.astype(np.float64)
@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("--n-plans", type=int, default=128) p.add_argument("--execute-frames", type=int, default=8) p.add_argument("--horizon-frames", type=int, default=20) p.add_argument("--guidance-scale", type=float, default=0.0) p.add_argument("--gamma", type=float, default=0.95) 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) bundle, mask = data.sample(a.n_states, rng, split="val", device=dev) # [W, B, C] init_obs = bundle[0, :, :OBS_DIM] H = min(a.horizon_frames, data.T) out = plan_bundles(model, init_obs, horizon_frames=H, guidance_scale=a.guidance_scale, gamma=a.gamma, n_plans=a.n_plans, device=dev) plan, J = out["plan"], out["J"] # [H,B,K,C], [B,K] K = a.n_plans
# executed chunk: plan indices 0..execute_frames-1, scored against bundle[h+1] (lag 0, as # implemented). keep only states whose whole chunk is inside the episode. hs = [h for h in range(min(a.execute_frames, H)) if h + 1 < bundle.shape[0]] w = mask[[h + 1 for h in hs]].bool().all(0) # [B] nB = int(w.sum()) pred = torch.stack([plan[h][w][..., A0:A1] for h in hs]) # [h,B',K,A] tgt = torch.stack([bundle[h + 1][w, A0:A1] for h in hs]) # [h,B',A] Jw = J[w] # [B',K]
mean_act = torch.as_tensor(np.asarray(data.act, np.float32).mean(0), device=dev) den = ((mean_act[None, None, :] - tgt) ** 2).mean((0, 2)) # [B'] per-state baseline MSE
def r2_from(errs): """errs [B'] per-state MSE -> pooled R2 against the constant mean-action predictor.""" return float(1.0 - errs.sum().item() / den.sum().clamp_min(1e-12).item())
err_k = ((pred - tgt[:, :, None, :]) ** 2).mean((0, 3)) # [B',K] per candidate MSE err_rand = err_k.mean(1) # random-of-K in expectation err_km = ((pred.mean(2) - tgt) ** 2).mean((0, 2)) # mean-of-K chunk err_best = err_k.min(1).values # ORACLE (diagnostic only) err_worst = err_k.max(1).values err_amax = err_k.gather(1, Jw.argmax(1, keepdim=True)).squeeze(1) # what the planner executes
r2 = dict(r2_random=r2_from(err_rand), r2_Kmean=r2_from(err_km), r2_argmaxJ=r2_from(err_amax), r2_oracle=r2_from(err_best), r2_antioracle=r2_from(err_worst)) r2["oracle_gain"] = r2["r2_oracle"] - r2["r2_random"] r2["argmaxJ_gain"] = r2["r2_argmaxJ"] - r2["r2_random"] r2["captured"] = (r2["argmaxJ_gain"] / r2["oracle_gain"]) if abs(r2["oracle_gain"]) > 1e-9 else float("nan")
# does J rank the pool in the right direction? spearman(J_k, -err_k) within each state. Jn, en = Jw.cpu().numpy(), err_k.cpu().numpy() rJ, re = _rank(Jn), _rank(-en) rJ -= rJ.mean(1, keepdims=True); re -= re.mean(1, keepdims=True) sp = (rJ * re).sum(1) / np.sqrt((rJ ** 2).sum(1) * (re ** 2).sum(1) + 1e-12) r2["spearman_J_vs_negerr_mean"] = float(sp.mean()) r2["spearman_J_vs_negerr_std"] = float(sp.std()) r2["spearman_frac_positive"] = float((sp > 0).mean())
# pool diversity: how different ARE the candidates, in action and in predicted observation? r2["act_pool_std"] = float(pred.std(2).mean()) r2["act_tgt_std"] = float(tgt.std(1).mean()) r2["act_pool_std_over_tgt"] = r2["act_pool_std"] / max(r2["act_tgt_std"], 1e-9) obs = torch.stack([plan[h][w][..., :OBS_DIM] for h in hs]) r2["obs_pool_std"] = float(obs.std(2).mean()) r2["J_spread"] = float((Jw.max(1).values - Jw.min(1).values).mean()) r2["J_std_within_state"] = float(Jw.std(1).mean())
res = dict(ckpt=a.ckpt, cache=a.cache, step=step, n_states=int(a.n_states), n_states_used=nB, n_plans=K, execute_frames=a.execute_frames, horizon_frames=H, guidance_scale=a.guidance_scale, gamma=a.gamma, seed=a.seed, act_align=str(meta.get("act_align", "ours")), planner_diag=out["diag"], **r2) os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True) with open(a.out, "w") as f: json.dump(res, f, indent=1) print(f"[df_poolcmp] step {step} n_states {nB} n_plans {K} g {a.guidance_scale}") print(f" R2 random {r2['r2_random']:+.4f} Kmean {r2['r2_Kmean']:+.4f} " f"argmaxJ {r2['r2_argmaxJ']:+.4f} ORACLE {r2['r2_oracle']:+.4f} (diagnostic only)") print(f" oracle_gain {r2['oracle_gain']:+.4f} argmaxJ_gain {r2['argmaxJ_gain']:+.4f} " f"captured {r2['captured']:.3f}") print(f" spearman(J, -err) {r2['spearman_J_vs_negerr_mean']:+.4f} " f"+-{r2['spearman_J_vs_negerr_std']:.3f} frac>0 {r2['spearman_frac_positive']:.2f}") print(f" pool act std/tgt {r2['act_pool_std_over_tgt']:.3f} J_spread {r2['J_spread']:.3f}") print("[df_poolcmp] wrote", a.out)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464"""THREE CHEAP EXTENSIONS OF df_poolcmp.py (gen_q#274 / #282) -- ALL DIAGNOSTICS, NO SUCCESS NUMBER.
df_poolcmp.py answered the question it was registered for: the POOL IS ALIVE (oracle_gain 0.30-1.40on held-out states) and the OBJECTIVE IS THE PROBLEM (spearman(J,-err) <= +0.05 in 3 of 4 cells,argmaxJ_gain NEGATIVE in 3 of 4 -- executing the argmax-J candidate is WORSE than drawing one atrandom). This file asks the three follow-ups, on the SAME held-out machinery: no environment, norollout, no success number, and the expert action is used ONLY to compute the error that the rankdiagnostics are scored against and the r2_oracle upper bound. Nothing from RSM/IQL touches DF'scandidates (fairness rule 7); no goal observation is used anywhere.
E1 PLAN-LENGTH SWEEP. Upstream's own maze2d recipe on the main branch plans chunk_size = 600 frames = 60 tokens and executes open_loop_horizon = 50; our RISE cells plan ceil(20/8) = 3 tokens and execute 8. Does spearman(J, -err) turn POSITIVE at a longer plan? Each arm re-diffuses the pool at a different horizon_frames H and re-scores it at several execute windows E.
THE CEILING, MEASURED, NOT ASSUMED (reported in the JSON as `ceiling`): * the backbone is upstream models/transformer.py, whose position embedding is a SinusoidalPosEmb evaluated on `torch.arange(seq_len)` at call time -- there is NO learned table and therefore NO hard context cap. Any token count runs. * the checkpoints were TRAINED on 1 conditioning token + n_tokens plan tokens = 1 + 8 = 9 tokens of frame_stack 8, i.e. a 64-frame plan. H <= 64 is IN DISTRIBUTION; H > 64 needs more plan tokens than the model ever saw and is flagged `extrapolation: true` on the arm. * the GROUND TRUTH also has to exist: scoring frame h needs bundle[h+1], so the data window must be at least H+1 frames. DFCacheData's window is independent of the model, so this file widens it (n_tokens = ceil((maxH+1)/frame_stack)) purely to have targets; every episode in both corpora is >= 194 frames, so the widening costs only the usual tail masking.
E2 RANK-RULE PANEL. The same pools, scored by several rules: J the planner's own objective, argmax == what every landed DF cell executes J_neg argmin J -- THE ANTI-OBJECTIVE, A DIAGNOSTIC. If it beats random while argmax J loses to random, J is anti-correlated with matching the expert. It is a measurement of J's sign, NOT a proposed column and never to be quoted as a rule. absJ argmax |J| J_final r_hat at the FINAL predicted frame of the plan J_plansum r_hat summed over the plan horizon with UNIFORM weights (no discount, no cond term) J_wplan the discounted plan part of J only (J with the conditioning term removed) J_cond the conditioning-frame part of J. This is not a curiosity: the weights are [w_cond]*frame_stack + gamma^j, so at frame_stack 8 / gamma 0.95 / H 20 the conditioning term carries W_cond_total 80 of the W_cond_total + W_plan_total 92.8 total weight -- 86% of the objective is the model's reconstruction of r_hat on the token it was GIVEN. J_cond's gain says how much of the ranking that share drives. Every rule reports r2, gain over random, and spearman(score, -err).
E3 WHAT J ACTUALLY REWARDS. The standing hypothesis (brief, lead 3): the provenance reward is ~1 wherever the model believes it is in distribution, so "maximise predicted provenance" is solved by STANDING STILL. For the argmax-J candidate vs a random one we report how far the predicted observation latent MOVES over the plan -- L2 between the first and last predicted latent, the per-step latent delta norm, and the distance from the conditioning observation -- plus the predicted provenance trajectory r_hat_j and its terminal value, plus the action norm. The single number is `latent_travel_ratio_argmaxJ_over_random`: < 1 confirms the hypothesis. The data's OWN travel over the same H at the same states is reported as the scale.
E4 THE REWARD CLAMP (`--r-max`, added 2026-09-24 -- THE READ-OUT IS REGISTERED HERE, BEFORE ANY NUMBER EXISTS).
THE PREMISE, MEASURED FIRST (see `status/nb/df_clamp.txt` header and df_plan.py's docstring): `plan_bundles` returns `model.unnorm(model.unstack(plan))` and `objective` reads r through the same `model.unnorm`, so BOTH are in RAW LABEL UNITS -- the units of DFCacheData's `ep_success`, which is the binary data-provenance label and lives in {0, 1}. Raw r = 0 reads as 0.000 and raw r = 1 reads as 1.000; nothing here is z-scored. The landed unclamped run (status/nb/df_poolcmp2.txt, job 1897107) reports `rhat_final_argmaxJ` 2.073 / 2.285 / 3.092 at guidance 5.0 -- 2-3x ABOVE the label's own maximum -- while the same cells at guidance 0.0 sit at 0.18-0.55, right on the corpora's own label means (mug train label mean 0.148, threading 0.568). So guidance IS driving r_hat out of the label's range, and the clamp tests whether that is what breaks the ranking.
WHAT THE CLAMP CHANGES AND WHAT IT DOES NOT. Only the planner's objective/guidance: r_hat -> min(r_hat, r_max) inside `objective`, which is used both for the J that ranks candidates and inside `guidance_fn`, whose gradient upstream takes through this expression (models/diffusion.py:424-440). The gradient of a clamp in the saturated region is ZERO, so a frame already at the label maximum stops attracting guidance. NOTHING IS RETRAINED, no weights change, the vendored checkout is untouched, and `--r-max` unset reproduces every landed number.
FAIRNESS. r_max = 1.0 is the maximum of the binary provenance reward itself -- the reward every column in tab:flagship shares. It is not privileged simulator state, not an outcome reward, not a success bit, and no RSM/IQL critic touches DF's candidates (stream rule 7). Only the DEFINITION of the shared label is used, so every column could apply it.
REGISTERED READ-OUT (written down before the number exists): * If under clamping `argmaxJ_gain` turns POSITIVE and `spearman(J,-err)` turns POSITIVE, the UNBOUNDED reward channel is the cause of the planner failure and the clamp is the fix; the next wave is a real RISE eval with controls. * If they stay <= 0 under clamping, the clamp is NOT the fix. Report it plainly as a negative result and name the remaining candidate causes. The clamped and unclamped arms run side by side at the same seed, states, checkpoints and guidance grid, so the only difference between two matched rows is min(r_hat, r_max).
THE J-DERIVED RULES ARE CLAMPED TOO, and they have to be: J_cond is computed as J - J_wplan, an identity that only holds if both halves use the same r_hat. E3's r_hat reporting stays RAW on purpose -- it is how far outside the label range the sample still goes even when the objective can no longer see it."""from __future__ import annotationsimport argparse, json, math, os, sysimport numpy as npimport torch
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
OBS_DIM, ACT_DIM = 1545, 7A0, A1 = OBS_DIM, OBS_DIM + ACT_DIM
# ---------------------------------------------------------------- rank helpersdef _rank(x): """ordinal ranks along the last axis of a [B, K] array (ties by order; J and err are continuous).""" x = np.asarray(x, np.float64) order = np.argsort(x, axis=-1) r = np.empty_like(order) np.put_along_axis(r, order, np.broadcast_to(np.arange(x.shape[-1]), x.shape).copy(), axis=-1) return r.astype(np.float64)
def spearman_rows(a, b): """per-row spearman between two [B, K] arrays -> (mean, std, frac>0, per-row array).""" ra, rb = _rank(a), _rank(b) ra = ra - ra.mean(-1, keepdims=True) rb = rb - rb.mean(-1, keepdims=True) sp = (ra * rb).sum(-1) / np.sqrt((ra ** 2).sum(-1) * (rb ** 2).sum(-1) + 1e-12) return float(sp.mean()), float(sp.std()), float((sp > 0).mean()), sp
def panel(scores, err_k, den, r2_random): """scores/err_k [B,K] numpy, den [B] numpy -> r2 / gain / spearman for argmax(scores).""" idx = scores.argmax(-1) e = np.take_along_axis(err_k, idx[:, None], -1).squeeze(-1) r2 = float(1.0 - e.sum() / max(den.sum(), 1e-12)) m, s, f, _ = spearman_rows(scores, -err_k) # A rule whose score does not VARY across the pool selects an arbitrary candidate: its "gain" is # then one draw of noise, not a ranking. J_cond is exactly this -- token 0 is never denoised, so # the conditioning frames are identical in every candidate. Emitted so no table can hide it. sd = float(np.std(scores, axis=-1).mean()) return dict(r2=r2, gain_over_random=r2 - r2_random, spearman_vs_negerr_mean=m, spearman_vs_negerr_std=s, spearman_frac_positive=f, score_std_within_state=sd, degenerate_constant_score=bool(sd < 1e-9))
# ---------------------------------------------------------------- arm scoringdef score_arm(acts, rhat, trav, step_d, from_cond, actnorm, J, bundle, mask, den_act, H, gamma, execute_list, data_travel, data_step, data_actnorm, r_max=None): """Everything downstream of the diffusion for ONE horizon arm. Pure numpy/torch on CPU tensors.
acts [H, B, K, ACT] predicted actions of every candidate rhat [H, B, K] predicted provenance channel over the plan frames trav [B, K] ||obs_pred[H-1] - obs_pred[0]|| step_d [B, K] mean_j ||obs_pred[j] - obs_pred[j-1]|| from_cond [B, K] ||obs_pred[H-1] - obs_cond|| actnorm [B, K] mean_j ||act_pred[j]|| J [B, K] the planner's own objective bundle [W, B, C] / mask [W, B] the held-out window (EXPERT ACTION USED ONLY HERE) """ res = {} wplan = (gamma ** np.arange(H, dtype=np.float64)) if gamma > 0 else np.ones(H) # E4: the J-derived rules must use the SAME r_hat the objective used, or `J_cond = J - J_wplan` # stops being an identity. `rhat` itself stays RAW for the E3 reporting below. rc = rhat if r_max is None else np.minimum(rhat, float(r_max)) J_wplan = (rc * wplan[:, None, None]).sum(0) J_cond = J - J_wplan # exact: weights are [w_cond]*fs + gamma^j + 0*pad J_plansum = rc.sum(0) J_final = rc[H - 1] r_ref = 1.0 if r_max is None else float(r_max) res["reward_range"] = dict( r_max=(None if r_max is None else float(r_max)), clamped=bool(r_max is not None), label_max=1.0, units="RAW label units -- plan_bundles returns model.unnorm(...), so 0.0 IS raw r=0 and " "1.0 IS raw r=1; the provenance label is binary so 1.0 is its maximum", rhat_plan_mean=float(rhat.mean()), rhat_plan_max=float(rhat.max()), rhat_plan_min=float(rhat.min()), rhat_plan_p99=float(np.quantile(rhat, 0.99)), frac_plan_frames_above_label_max=float((rhat > r_ref).mean()), frac_plan_frames_above_1=float((rhat > 1.0).mean()))
res["J_decomposition"] = dict( J_mean=float(J.mean()), J_cond_mean=float(J_cond.mean()), J_wplan_mean=float(J_wplan.mean()), J_cond_share_of_mean=float(J_cond.mean() / J.mean()) if abs(J.mean()) > 1e-9 else float("nan"), J_std_within_state=float(J.std(-1).mean()), J_cond_std_within_state=float(J_cond.std(-1).mean()), J_wplan_std_within_state=float(J_wplan.std(-1).mean()), # which part of J does the WITHIN-STATE ranking actually come from? spearman_J_vs_Jcond=spearman_rows(J, J_cond)[0], spearman_J_vs_Jwplan=spearman_rows(J, J_wplan)[0], )
# ---- E3: what does J reward? (prediction-side only; no mask needed) def arm_travel(v): amax = np.take_along_axis(v, J.argmax(-1)[:, None], -1).squeeze(-1) amin = np.take_along_axis(v, J.argmin(-1)[:, None], -1).squeeze(-1) rnd = v.mean(-1) # random-of-K in expectation return dict(argmaxJ=float(amax.mean()), argminJ=float(amin.mean()), random=float(rnd.mean()), ratio_argmaxJ_over_random=float(amax.mean() / max(rnd.mean(), 1e-12)), ratio_argminJ_over_random=float(amin.mean() / max(rnd.mean(), 1e-12)))
sp_trav = spearman_rows(J, trav) e3 = dict(latent_travel=arm_travel(trav), latent_step_delta=arm_travel(step_d), latent_dist_from_cond=arm_travel(from_cond), act_norm=arm_travel(actnorm), spearman_J_vs_latent_travel_mean=sp_trav[0], spearman_J_vs_latent_travel_frac_positive=sp_trav[2], data_latent_travel=data_travel, data_latent_step_delta=data_step, data_act_norm=data_actnorm) e3["latent_travel_ratio_argmaxJ_over_random"] = e3["latent_travel"]["ratio_argmaxJ_over_random"] e3["latent_travel_ratio_argmaxJ_over_data"] = float( e3["latent_travel"]["argmaxJ"] / max(data_travel, 1e-12)) # predicted provenance trajectory of the executed candidate vs a random one iamax = J.argmax(-1) rh_amax = np.take_along_axis(rhat, iamax[None, :, None], -1)[:, :, 0] # [H, B] e3["rhat_traj_argmaxJ"] = [float(v) for v in rh_amax.mean(-1)] e3["rhat_traj_random"] = [float(v) for v in rhat.mean((1, 2))] e3["rhat_final_argmaxJ"] = float(rh_amax[H - 1].mean()) e3["rhat_final_random"] = float(rhat[H - 1].mean()) e3["rhat_first_argmaxJ"] = float(rh_amax[0].mean()) e3["rhat_first_random"] = float(rhat[0].mean()) e3["rhat_pool_std_within_state"] = float(rhat.std(-1).mean()) res["what_J_rewards"] = e3
# ---- E1/E2: rank panel per execute window (EXPERT ACTION ENTERS ONLY BELOW) res["execute"] = {} for E in execute_list: hs = [h for h in range(min(E, H)) if h + 1 < bundle.shape[0]] if not hs: continue w = mask[[h + 1 for h in hs]].astype(bool).all(0) # [B] nB = int(w.sum()) if nB < 8: res["execute"][str(E)] = dict(n_states_used=nB, note="too few valid states, skipped") continue pred = acts[hs][:, w] # [e, B', K, A] tgt = bundle[[h + 1 for h in hs]][:, w, A0:A1] # [e, B', A] den = ((den_act[None, None, :] - tgt) ** 2).mean((0, 2)) # [B'] err_k = ((pred - tgt[:, :, None, :]) ** 2).mean((0, 3)) # [B', K] Jw = J[w]
def r2_from(e): return float(1.0 - e.sum() / max(den.sum(), 1e-12))
r2_random = r2_from(err_k.mean(-1)) cell = dict(n_states_used=nB, execute_frames=len(hs), r2_random=r2_random, r2_Kmean=r2_from(((pred.mean(2) - tgt) ** 2).mean((0, 2))), r2_oracle=r2_from(err_k.min(-1)), r2_antioracle=r2_from(err_k.max(-1))) cell["oracle_gain"] = cell["r2_oracle"] - r2_random rules = dict(J=Jw, J_neg=-Jw, absJ=np.abs(Jw), J_final=J_final[w], J_plansum=J_plansum[w], J_wplan=J_wplan[w], J_cond=J_cond[w]) cell["rules"] = {k: panel(v, err_k, den, r2_random) for k, v in rules.items()} cell["captured_by_J"] = (cell["rules"]["J"]["gain_over_random"] / cell["oracle_gain"] if abs(cell["oracle_gain"]) > 1e-9 else float("nan")) cell["act_pool_std"] = float(pred.std(2).mean()) cell["act_tgt_std"] = float(tgt.std(1).mean()) cell["act_pool_std_over_tgt"] = cell["act_pool_std"] / max(cell["act_tgt_std"], 1e-9) res["execute"][str(E)] = cell return res
# ---------------------------------------------------------------- self testdef selftest(): """Metric math on synthetic pools, no model and no GPU. Two planted cases: a score that IS the negative error must show gain > 0 and spearman ~ +1; its negation must show the mirror image. This is the guard that the panel's sign convention is right.""" rng = np.random.default_rng(0) B, K, H, W = 16, 32, 5, 12 bundle = rng.normal(size=(W, B, A1 + 1)).astype(np.float32) mask = np.ones((W, B), np.float32) acts = rng.normal(size=(H, B, K, ACT_DIM)).astype(np.float32) tgt = bundle[1:H + 1, :, A0:A1] err = ((acts - tgt[:, :, None, :]) ** 2).mean((0, 3)) J = (-err + 0.01 * rng.normal(size=(B, K))).astype(np.float32) # a PERFECT-ish objective rhat = rng.normal(size=(H, B, K)).astype(np.float32) trav = rng.random((B, K)).astype(np.float32) + 0.5 out = score_arm(acts, rhat, trav, trav, trav, trav, J, bundle, mask, np.zeros(ACT_DIM, np.float32), H, 0.95, [H], 1.0, 1.0, 1.0) c = out["execute"][str(H)] gJ, gN = c["rules"]["J"]["gain_over_random"], c["rules"]["J_neg"]["gain_over_random"] sJ = c["rules"]["J"]["spearman_vs_negerr_mean"] sN = c["rules"]["J_neg"]["spearman_vs_negerr_mean"] ok = (gJ > 0 > gN) and (sJ > 0.9) and (sN < -0.9) and (c["oracle_gain"] > 0) assert abs(sJ + sN) < 1e-9, (sJ, sN) assert c["r2_oracle"] >= c["rules"]["J"]["r2"] >= c["r2_antioracle"] print(f"[selftest] gain(J) {gJ:+.4f} gain(J_neg) {gN:+.4f} spearman(J) {sJ:+.4f} " f"spearman(J_neg) {sN:+.4f} oracle_gain {c['oracle_gain']:+.4f} -> {'PASS' if ok else 'FAIL'}") # E4 guard: a clamp far above the data must be an EXACT no-op, so any difference a real clamped # arm shows is the clamp biting and not a code path change. big = score_arm(acts, rhat, trav, trav, trav, trav, J, bundle, mask, np.zeros(ACT_DIM, np.float32), H, 0.95, [H], 1.0, 1.0, 1.0, r_max=1e9) assert json.dumps(big["execute"]) == json.dumps(out["execute"]), "r_max=1e9 changed the panel" assert big["reward_range"]["clamped"] and not out["reward_range"]["clamped"] low = score_arm(acts, rhat, trav, trav, trav, trav, J, bundle, mask, np.zeros(ACT_DIM, np.float32), H, 0.95, [H], 1.0, 1.0, 1.0, r_max=0.0) lo = low["execute"][str(H)]["rules"] un = out["execute"][str(H)]["rules"] assert lo["J_final"]["score_std_within_state"] < un["J_final"]["score_std_within_state"], \ "clamping at 0.0 must flatten J_final on a standard-normal r_hat" # J itself is an INPUT to score_arm, so argmax-J rules must be untouched by the clamp; only the # r_hat-derived rules move. This is the contract the clamped arm relies on. assert json.dumps(lo["J"]) == json.dumps(un["J"]) print(f"[selftest] clamp: r_max=1e9 no-op OK; r_max=0.0 flattens J_final " f"{un['J_final']['score_std_within_state']:.4f} -> {lo['J_final']['score_std_within_state']:.4f}; " f"rule J untouched -> PASS") # the anti-objective must be exactly the mirror of the objective on a symmetric pool assert ok return 0
# ---------------------------------------------------------------- main@torch.no_grad()def main(): p = argparse.ArgumentParser() p.add_argument("--selftest", action="store_true") p.add_argument("--ckpt") p.add_argument("--cache") p.add_argument("--out") p.add_argument("--n-states", type=int, default=128) p.add_argument("--n-plans", type=int, default=128) p.add_argument("--horizons", default="8,20,40,64,80", help="plan lengths in FRAMES; > train plan frames is flagged extrapolation") p.add_argument("--execute-base", type=int, default=8, help="the fixed execute window scored on every arm, so arms are comparable") p.add_argument("--guidance-scale", type=float, default=0.0) p.add_argument("--r-max", type=float, default=None, help="E4 REWARD CLAMP (opt-in). Saturate the predicted provenance reward at this " "value in J AND in the guidance gradient: r_hat -> min(r_hat, r_max). The " "units are RAW label units and the binary provenance label's maximum is 1.0, " "so --r-max 1.0 is the label's own range and nothing outside it. Unset = the " "original unbounded objective, bit-identical to every landed number.") p.add_argument("--gamma", type=float, default=0.95) p.add_argument("--seed", type=int, default=0) p.add_argument("--micro", type=int, default=8, help="states per diffusion chunk (memory knob)") a = p.parse_args() if a.selftest: return selftest() for r in ("ckpt", "cache", "out"): if getattr(a, r) is None: raise SystemExit(f"--{r} is required")
from df_data import DFCacheData # noqa: E402 from df_probe import load_df # noqa: E402 from df_plan import plan_bundles # noqa: E402
dev = "cuda" if torch.cuda.is_available() else "cpu" torch.manual_seed(a.seed) model, meta, step = load_df(a.ckpt, dev) fs = int(meta["frame_stack"]) train_tokens = int(meta["n_tokens"]) horizons = [int(h) for h in a.horizons.split(",") if h.strip()] maxH = max(horizons) # widen the DATA window only, so a target frame exists for every plan frame data_tokens = max(train_tokens, int(math.ceil((maxH + 1) / fs))) data = DFCacheData(a.cache, frame_stack=fs, n_tokens=data_tokens, seed=int(meta.get("seed", 0))) rng = np.random.default_rng(a.seed) bundle_t, mask_t = data.sample(a.n_states, rng, split="val", device=dev) # [W,B,C], [W,B] init_obs = bundle_t[0, :, :OBS_DIM] bundle = bundle_t.cpu().numpy() mask = mask_t.cpu().numpy() B = bundle.shape[1] mean_act = np.asarray(data.act, np.float32).mean(0) data_actnorm = float(np.linalg.norm(np.asarray(data.act, np.float32), axis=-1).mean())
ceiling = dict( train_plan_tokens=train_tokens, train_plan_frames=fs * train_tokens, frame_stack=fs, data_window_frames=int(data.W), data_plan_frames=int(data.T), pos_emb="SinusoidalPosEmb computed on torch.arange(seq_len) at call time -- no learned table, " "so the backbone has NO hard context cap; the limit is training distribution, not shape", in_distribution_max_horizon_frames=fs * train_tokens, note=("H <= %d frames uses at most the 1+%d tokens the checkpoint was trained on; larger H is " "token-count EXTRAPOLATION and is flagged per arm. Ground truth needs H+1 frames of " "window, which is why the data window was widened to %d frames (model untouched)." % (fs * train_tokens, train_tokens, int(data.W))))
arms = [] for H in horizons: plan_tokens = int(math.ceil(H / fs)) acts = torch.zeros(H, B, a.n_plans, ACT_DIM) rhat = torch.zeros(H, B, a.n_plans) trav = torch.zeros(B, a.n_plans) stepd = torch.zeros(B, a.n_plans) fcond = torch.zeros(B, a.n_plans) anorm = torch.zeros(B, a.n_plans) Jall = torch.zeros(B, a.n_plans) diags = [] for s in range(0, B, a.micro): e = min(B, s + a.micro) out = plan_bundles(model, init_obs[s:e], horizon_frames=H, guidance_scale=a.guidance_scale, gamma=a.gamma, n_plans=a.n_plans, device=dev, r_max=a.r_max) body = out["plan"] # [H, b, K, C] obs = body[..., :OBS_DIM] acts[:, s:e] = body[..., A0:A1].cpu() rhat[:, s:e] = body[..., -1].cpu() trav[s:e] = (obs[-1] - obs[0]).norm(dim=-1).cpu() stepd[s:e] = ((obs[1:] - obs[:-1]).norm(dim=-1).mean(0).cpu() if H > 1 else torch.zeros(e - s, a.n_plans)) fcond[s:e] = (obs[-1] - init_obs[s:e][:, None, :]).norm(dim=-1).cpu() anorm[s:e] = body[..., A0:A1].norm(dim=-1).mean(0).cpu() Jall[s:e] = out["J"].cpu() diags.append(out["diag"]) del out, body, obs if dev == "cuda": torch.cuda.empty_cache()
# the data's own motion over the same H at the same states, as the scale for E3 okH = mask[min(H, mask.shape[0] - 1)].astype(bool) if okH.sum() >= 4: o = bundle[:, okH, :OBS_DIM] data_travel = float(np.linalg.norm(o[H] - o[1], axis=-1).mean()) data_step = float(np.linalg.norm(o[2:H + 1] - o[1:H], axis=-1).mean()) else: data_travel = data_step = float("nan")
execute_list = sorted({min(a.execute_base, H), H}) arm = dict(horizon_frames=H, plan_tokens=plan_tokens, total_tokens=plan_tokens + 1, extrapolation=bool(plan_tokens > train_tokens), n_states=B, n_plans=a.n_plans, planner_diag={k: float(np.mean([d[k] for d in diags])) for k in ("J_mean", "J_std", "J_spread", "J_gain", "W_cond_total", "W_plan_total", "sched_rows", "rhat_raw_mean", "rhat_raw_max", "rhat_raw_min", "rhat_raw_p99", "frac_frames_above_rmax", "frac_cond_frames_above_rmax", "frac_plan_frames_above_rmax", "J_excess_above_rmax")}, r_max=(None if a.r_max is None else float(a.r_max)), clamped=bool(a.r_max is not None), data_latent_travel=data_travel, data_latent_step_delta=data_step) arm.update(score_arm(acts.numpy(), rhat.numpy(), trav.numpy(), stepd.numpy(), fcond.numpy(), anorm.numpy(), Jall.numpy(), bundle, mask, mean_act, H, a.gamma, execute_list, data_travel, data_step, data_actnorm, r_max=a.r_max)) arms.append(arm) c8 = arm["execute"].get(str(min(a.execute_base, H)), {}) rj = c8.get("rules", {}).get("J", {}) rn = c8.get("rules", {}).get("J_neg", {}) print(f"[df_poolcmp2] H={H:3d} ({plan_tokens} tok{' EXTRAP' if arm['extrapolation'] else ''}) " f"E={min(a.execute_base, H)} n={c8.get('n_states_used')} " f"oracle_gain {c8.get('oracle_gain', float('nan')):+.4f} " f"argmaxJ_gain {rj.get('gain_over_random', float('nan')):+.4f} " f"argminJ_gain {rn.get('gain_over_random', float('nan')):+.4f} " f"spearman(J,-err) {rj.get('spearman_vs_negerr_mean', float('nan')):+.4f} " f"travel argmaxJ/rand " f"{arm['what_J_rewards']['latent_travel_ratio_argmaxJ_over_random']:.3f} " f"rmax {'off' if a.r_max is None else f'{a.r_max:g}'} " f"fr_above {arm['planner_diag']['frac_frames_above_rmax']:.3f} " f"rhat_max {arm['planner_diag']['rhat_raw_max']:.3f}", flush=True)
res = dict(ckpt=a.ckpt, cache=a.cache, step=step, n_states=B, n_plans=a.n_plans, guidance_scale=a.guidance_scale, gamma=a.gamma, seed=a.seed, r_max=(None if a.r_max is None else float(a.r_max)), clamped=bool(a.r_max is not None), clamp_note=("E4: r_hat -> min(r_hat, r_max) in the planner's objective AND in the " "guidance gradient (zero gradient above r_max). r_hat is in RAW label " "units (plan_bundles unnorms), and the binary data-provenance label's " "maximum is 1.0, so r_max=1.0 uses only the shared reward's own " "definition -- no privileged state, no outcome reward, no success bit, " "no RSM/IQL contact. Nothing retrained; the vendored checkout untouched."), act_align=str(meta.get("act_align", "ours")), ceiling=ceiling, execute_base=a.execute_base, horizons=horizons, arms=arms, kind="DIAGNOSTIC -- held-out states, no environment, no rollout, NO SUCCESS NUMBER. " "The expert action enters ONLY as the error the rank rules are scored against and " "the r2_oracle upper bound; it is never given to the planner or the scorer. " "r2_oracle and the J_neg (argmin-J) rule are DIAGNOSTICS, never DF columns.") os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True) with open(a.out, "w") as f: json.dump(res, f, indent=1) print("[df_poolcmp2] wrote", a.out, flush=True) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164"""INTERROGATE THE DF PLANNER'S OBJECTIVE (gen_q#274, brief leads 2 and 3).
Three questions, one job, no environment and no success number -- this is a diagnostic, not a score.
P1 IS THE OBJECTIVE INFORMATIVE AT ALL? The guidance maximises J = sum_j w_j * r_hat_j where r_hat is DF's own predicted reward channel and the reward is the binary data-provenance label (constant over an episode). If r_hat cannot separate a held-out expert episode from a held-out non-expert one, then J is noise and "the optimiser improves its objective" (J_gain +5.71/+12.63/+16.33) means only that it is ascending an undertrained head adversarially. Reported as AUC over val episodes plus the raw spread of r_hat -- a head whose spread is ~0 has nothing to rank with.
P2 IS THE GUIDANCE SCALE CONNECTED? (the brief's explicit request) Same conditioning observation, same generator seed, guidance in {0,1,5,20,100,500}. Report the L2 between each plan and the guidance-0 plan, split into the obs part and the act part. ~0 means the knob is inert and the four-point 0..5 sweep measured nothing.
P3 DOES THE CHOSEN PLAN MOVE? ||obs_pred[h] - obs_cond|| for the argmax-J candidate, against the DATA's own ||obs[t+h] - obs[t]|| at the same h and the same states. A ratio << 1 is a planner whose predicted future is the present -- i.e. one that maximises in-distribution-ness by standing still.
Also emitted per guidance scale: act_absmax / act_clip_frac (the action marginal, FINDING C)."""from __future__ import annotationsimport argparse, json, os, sysfrom pathlib import Pathimport numpy as npimport torch
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from df_data import DFCacheData, OBS_DIM, ACT_DIM, BUNDLE_DIM # noqa: E402from df_core import DFRise # noqa: E402from df_plan import plan_bundles # noqa: E402
def load_df(ckpt, device): ck = torch.load(ckpt, map_location="cpu", weights_only=False) meta = ck["meta"] m = DFRise(frame_stack=int(meta["frame_stack"]), n_tokens=int(meta["n_tokens"]), mean=ck["mean"], std=ck["std"], cfg=ck["cfg"]).to(device) m.load_state_dict(ck["model"]) m.eval() return m, meta, int(ck["step"])
def auc(scores, labels): """rank AUC; 0.5 = uninformative.""" 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") order = np.argsort(np.concatenate([pos, neg]), kind="mergesort") ranks = np.empty(len(order), float); ranks[order] = np.arange(1, len(order) + 1) # average ties allv = np.concatenate([pos, neg]) for v in np.unique(allv): m = allv == v if m.sum() > 1: ranks[m] = ranks[m].mean() return float((ranks[:len(pos)].sum() - len(pos) * (len(pos) + 1) / 2) / (len(pos) * len(neg)))
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("--horizon", type=int, default=16) p.add_argument("--n-plans", type=int, default=128) p.add_argument("--gamma", type=float, default=0.99) p.add_argument("--w-cond", type=float, default=10.0) p.add_argument("--n-states", type=int, default=24, help="conditioning states for P1/P3") p.add_argument("--act-limit", type=float, default=1.0) 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) res = dict(ckpt=a.ckpt, cache=a.cache, step=step, horizon=a.horizon, n_plans=a.n_plans, gamma=a.gamma, w_cond=a.w_cond, frame_stack=int(meta["frame_stack"]), chan_share=meta.get("chan_share", ""), train_steps=int(meta.get("steps", -1)))
# ---- conditioning states drawn from HELD-OUT episodes, balanced over the provenance label ---- picks = [] # (row, label, ep, t) for e in data.val_eps: L = int(data.ep_len[e]) for t in rng.integers(0, max(1, L - a.horizon - 1), size=max(1, a.n_states // max(1, len(data.val_eps)))): picks.append((int(data.ep_from[e] + t), float(data.ep_success[e]), int(e), int(t))) rng.shuffle(picks) picks = picks[:a.n_states] rows = np.array([p_[0] for p_ in picks]); labs = np.array([p_[1] for p_ in picks]) res["n_val_eps"] = int(len(data.val_eps)) res["val_label_mean"] = float(data.ep_success[data.val_eps].mean()) res["n_states"] = int(len(picks)) obs = torch.from_numpy(data.obs_rows(rows).astype(np.float32)).to(dev) # [S, OBS]
# ---- P2 + P1 + P3: one pass per guidance scale, SAME generator seed every time ---- scales = [0.0, 1.0, 5.0, 20.0, 100.0, 500.0] per_scale, ref_plan = {}, None for gs in scales: g = torch.Generator(device=dev); g.manual_seed(1234 + a.seed) out = plan_bundles(model, obs, a.horizon, gs, a.gamma, n_plans=a.n_plans, device=dev, generator=g, w_cond=a.w_cond, collect_iters=True) plan, J = out["plan"], out["J"] # [H, S, n_plans, C], [S, n_plans] idx = J.argmax(-1) sel = plan[:, torch.arange(plan.shape[1], device=dev), idx] # [H, S, C] act = sel[..., OBS_DIM:OBS_DIM + ACT_DIM] d = dict(out["diag"]) d["act_absmax"] = float(act.abs().max()) d["act_clip_frac"] = float((act.abs() > a.act_limit).float().mean()) # P1: the score the guidance actually reads, per conditioning state (mean over candidates # AND the argmax candidate) -> AUC against the episode's true provenance label. r_pred = sel[..., -1] # [H, S] d["rhat_mean"] = float(r_pred.mean()); d["rhat_std"] = float(r_pred.std()) d["rhat_frame_spread"] = float((r_pred.max(0).values - r_pred.min(0).values).mean()) score_argmax = r_pred.mean(0).cpu().numpy() score_pool = plan[..., -1].mean((0, 2)).cpu().numpy() d["auc_rhat_argmax"] = auc(score_argmax, labs) d["auc_rhat_pool"] = auc(score_pool, labs) d["rhat_by_label"] = {"expert": float(score_pool[labs > 0.5].mean()) if (labs > 0.5).any() else None, "other": float(score_pool[labs <= 0.5].mean()) if (labs <= 0.5).any() else None} # P3: does the predicted latent move? mv = {} for h in (1, 2, 4, 8, 16): if h > a.horizon: continue pm = float((sel[h - 1, :, :OBS_DIM] - obs).norm(dim=-1).mean()) dm = [] for (row, _l, e, t) in picks: L = int(data.ep_len[e]); tt = min(t + h, L - 1) o2 = data.obs_rows(np.array([data.ep_from[e] + tt]))[0] o1 = data.obs_rows(np.array([row]))[0] dm.append(float(np.linalg.norm(o2 - o1))) mv[f"h{h}"] = dict(plan_move=pm, data_move=float(np.mean(dm)), ratio=pm / max(1e-8, float(np.mean(dm)))) d["move"] = mv # P2: L2 against the guidance-0 plan, same seed if ref_plan is None: ref_plan = plan.detach().clone() d["l2_vs_g0_obs"] = 0.0; d["l2_vs_g0_act"] = 0.0; d["l2_vs_g0_rew"] = 0.0 else: df_ = plan - ref_plan d["l2_vs_g0_obs"] = float(df_[..., :OBS_DIM].norm(dim=-1).mean()) d["l2_vs_g0_act"] = float(df_[..., OBS_DIM:OBS_DIM + ACT_DIM].norm(dim=-1).mean()) d["l2_vs_g0_rew"] = float(df_[..., -1].abs().mean()) # scale-free: the obs L2 relative to the plan's own obs norm at guidance 0 d["l2_vs_g0_obs_rel"] = d["l2_vs_g0_obs"] / max(1e-8, float(ref_plan[..., :OBS_DIM].norm(dim=-1).mean())) per_scale[str(gs)] = d print(f"[df_probe] gs={gs}: J_mean={d['J_mean']:.4g} J_gain={d['J_gain']:.4g} " f"spread={d['J_spread']:.4g} auc_pool={d['auc_rhat_pool']:.3f} " f"l2obs={d['l2_vs_g0_obs']:.4g} (rel {d['l2_vs_g0_obs_rel']:.3g}) " f"actmax={d['act_absmax']:.3f} clip={d['act_clip_frac']:.4f} " f"move_h8={mv.get('h8', {}).get('ratio', float('nan')):.3f}", flush=True) res["per_scale"] = per_scale Path(a.out).parent.mkdir(parents=True, exist_ok=True) Path(a.out).write_text(json.dumps(res, indent=1)) print("[df_probe] wrote " + a.out, flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241"""Diffusion Forcing as a VALUE ESTIMATOR -- the read-out (gen_q#274 / tracking #282, stream DF_VALUE).
WHAT THIS IS, AND HOW IT DIFFERS FROM `df_plan.py` (which this stream does not touch).`df_plan.plan_bundles` runs DF as a PLANNER: it lets the diffusion model propose its own actionchannels and steers them with a guidance gradient on the predicted reward. This file runs the samemodel as a VALUE FUNCTION over somebody ELSE's candidate actions -- the shape every other column intab:flagship is scored in (a proposer emits N action chunks, the column ranks them). Concretely:
guidance_fn = None, ALWAYS. no gradient steering of any kind the candidate action chunk is INPAINTED instead. Diffuser-style replacement conditioning the value is DF's own predicted reward channel r_hat, read off the rolled-out bundle.
The sampling loop below MIRRORS `df_plan.plan_bundles` line for line -- same pyramid schedulingmatrix (`model.scheduling`), same conditioning token construction, same`model.diffusion_model.sample_step(plan, None, frm, to, guidance_fn=...)` call -- so a differencebetween the planner route and the value route cannot come from a difference in the sampler.
DESIGN DECISIONS D1..D4 (status/real/DF_VALUE.md, run 1; binding, implemented exactly)
D1 ACTION CLAMP = REPLACEMENT CONDITIONING, RE-IMPOSED AFTER EVERY SCHEDULING STEP. `frame_stack == 8 == the project's action chunk`, so one candidate chunk occupies exactly plan token 1 (sequence index 1; index 0 is the conditioning token). Frame f of a token lives at `[f*BUNDLE_DIM : (f+1)*BUNDLE_DIM]`, so frame f's action slice is `[f*1553 + 1545 : f*1553 + 1552]`. Those slices are overwritten with the z-scored candidate once before the loop and again after every `sample_step`. `clamp_maxerr` in the returned diag is the assertion: the UNNORMALISED actions recovered from token 1 after the last step must equal the candidate to < 1e-3, otherwise the value was not computed for the candidate we asked about. The check is an `assert`, not a warning.
D2 free_tail=True (default): past the 8-frame chunk the action channel is LEFT FREE, i.e. model-sampled. The roll-out then means "this chunk, then the behaviour distribution the model was trained on" -- the same semantics as RSM's successor measure under the behaviour policy. free_tail=False is the named ABLATION: the tail action channels are clamped to a RAW ZERO action (z-scored through the model's own action mean/std), i.e. "this chunk then nothing". Note the convention difference against `df_core.make_sequence`, which zeroes the conditioning token's action channels AFTER normalisation; here the ablation wants a zero ACTION, not a mean action, so the zero is imposed in raw units and then normalised. Stated because the two conventions differ by `-mean/std` and a reader would otherwise have to guess.
D3 M Monte-Carlo samples = M independent noise draws of the FREE channels, with COMMON RANDOM NUMBERS across the N candidates of an anchor: the noise is drawn at shape `[plan_tokens, B, 1, M, fs*C]` and expanded over N, so candidate i and candidate j inside the same anchor are diffused from the SAME noise and their difference is not a noise difference. (DDIM with eta = 0 -- upstream's planning recipe, `ddim_sampling_eta: 0.0` -- makes the sampler deterministic given the initial noise, so the initial draw is the whole stochasticity.) This is the analogue of RSM's particle count P.
D4 TWO aggregations of the unnormalised reward channel over plan frames 1..H, both returned: terminal r_hat at plan frame H (absolute frame index fs + H - 1) disc sum_j gamma^j r_hat_j / sum_j gamma^j, default gamma = 1 - 1/H Each is averaged over the M samples; the per-candidate standard deviation over M is returned beside it, because std_across_cand / std_across_M is the only number that says whether the ranking is signal or Monte-Carlo noise.
UNITS. `init_obs` is the project's z-scored 1545-d state (`DFCacheData.obs_rows`), exactly what`plan_bundles` takes. `cand_act` is in RAW OSC action units -- the same units `DFCacheData.sample`puts in the bundle's action channel and the same units `plan_bundles` returns, because the model'sz-scoring is applied by `model.norm` to the WHOLE bundle inside this file (see `_act_z`). The D1assertion is what proves this end to end: it un-normalises what the sampler actually held andcompares it against the raw candidate that was passed in.
COST / MEMORY. One sequence is `(1 + plan_tokens) * fs * BUNDLE_DIM` floats = 1.29 MB at H = 200,and the batch is B*N*M, so the flattened batch is chunked over the candidate axis to a byte budget(`max_bytes`, default 400 MB of plan tensor). Chunking is over N only; the noise is drawn ONCE percall before chunking, so chunking cannot change a single returned number."""from __future__ import annotations
import numpy as npimport torch
from df_data import OBS_DIM, ACT_DIM, BUNDLE_DIM
def default_gamma(H): """D4's gamma. H = 1/(1-gamma) is the horizon parameterisation #273 sweeps.""" return 1.0 - 1.0 / float(H)
def _act_z(model, act_raw): """Raw OSC actions -> the model's z-scored action units.
This is the action block of `model.norm`, and it is written out rather than calling `model.norm` on a padded bundle so that the slice indices are visible at the call site.""" mu = model.data_mean[OBS_DIM:OBS_DIM + ACT_DIM] sd = model.data_std[OBS_DIM:OBS_DIM + ACT_DIM] return (act_raw - mu) / sd
def _act_unz(model, act_z): mu = model.data_mean[OBS_DIM:OBS_DIM + ACT_DIM] sd = model.data_std[OBS_DIM:OBS_DIM + ACT_DIM] return act_z * sd + mu
@torch.no_grad()def value_of_candidates(model, init_obs, cand_act, H, M, gamma=None, free_tail=True, device="cuda", seed=0, max_bytes=4.0e8, return_samples=False, assert_clamp=True, clamp_tol=1e-3, crn_rows=False): """DF's value of N candidate action chunks at each of B anchors.
init_obs [B, OBS_DIM] project z-scored state (DFCacheData.obs_rows units) cand_act [B, N, fs, ACT_DIM] candidate action chunks, RAW OSC units, fs = model.frame_stack H plan frames to roll out (the value horizon) M Monte-Carlo noise draws per (anchor, candidate), common across candidates (D3) gamma discount for the `disc` aggregation; None -> 1 - 1/H (D4) free_tail True -> action channel past the chunk is model-sampled (D2, default) False -> action channel past the chunk is clamped to a raw zero action (the ablation) crn_rows False -> one noise draw per (anchor, M), common across that anchor's N candidates. This is D3 as written and is what the offline spread gate runs: the anchors there are independent rows of a batch, so sharing noise between them would correlate measurements that are supposed to be independent samples. True -> ONE noise draw per M, common across every anchor AND every candidate in the call. Needed by the eval harness (df_readout.DFCritic): rsm_scorer flattens (B envs x N candidates) into rows and a backend never learns N, so per-row noise would break common random numbers across exactly the comparison the argmax is taken over. Strictly stronger CRN, and it cannot bias a ranking -- every candidate is diffused from identical noise.
returns dict: terminal [B, N] mean over M of r_hat at plan frame H disc [B, N] mean over M of sum_j gamma^j r_hat_j / sum_j gamma^j terminal_std [B, N] std over M of the same (population std, ddof=0) disc_std [B, N] terminal_samples / disc_samples [B, N, M] (only if return_samples) diag dict incl. `clamp_maxerr` (the D1 assertion's measured error) """ fs = int(model.frame_stack) C = BUNDLE_DIM D = fs * C B, N, K, A = cand_act.shape assert K == fs, f"candidate chunk is {K} frames but frame_stack is {fs}" assert A == ACT_DIM, f"candidate action dim {A} != {ACT_DIM}" assert init_obs.shape == (B, OBS_DIM), init_obs.shape H = int(H) M = int(M) gamma = default_gamma(H) if gamma is None else float(gamma)
plan_tokens = int(np.ceil(H / fs)) assert plan_tokens >= 1, "H must be >= 1" total_frames = fs * (1 + plan_tokens) sched = model.scheduling(plan_tokens) clip = float(model.cfg.clip_noise)
init_obs = init_obs.to(device).float() cand_act = cand_act.to(device).float()
# ---- conditioning token, built EXACTLY as df_plan.plan_bundles builds it ------------------ init = torch.zeros(B, C, device=device) init[:, :OBS_DIM] = init_obs init = model.norm(init) init[:, OBS_DIM:] = 0.0 init_tok = init.view(B, 1, C).repeat(1, fs, 1).reshape(B, D) # [B, fs*C]
cand_z = _act_z(model, cand_act) # [B, N, fs, A] zero_z = _act_z(model, torch.zeros(A, device=device)) # D2 ablation value
# ---- D3: one noise draw per (anchor, M), expanded over the N candidates ------------------- g = torch.Generator(device=device) g.manual_seed(int(seed)) # crn_rows collapses the anchor axis to 1; `.expand` below broadcasts it back over B, so the # sampler sees identical noise on every row. Shape is the only difference; nothing else changes. noise = torch.randn((plan_tokens, 1 if crn_rows else B, 1, M, D), device=device, generator=g).clamp(-clip, clip)
# ---- chunking over N only (cannot change a number: the noise is already fixed) ------------ per_cand = (1 + plan_tokens) * M * 4.0 * D # bytes of plan per anchor-candidate cn = max(1, int(max_bytes / max(per_cand * B, 1.0))) cn = min(cn, N)
term_s = torch.empty(B, N, M, device=device) disc_s = torch.empty(B, N, M, device=device) w = torch.from_numpy((gamma ** np.arange(H, dtype=np.float64)).astype(np.float32)).to(device) w = w / w.sum()
clamp_err = 0.0 n_chunks = 0 for n0 in range(0, N, cn): n1 = min(N, n0 + cn) nn = n1 - n0 bs = B * nn * M n_chunks += 1
chunk = noise.expand(plan_tokens, B, nn, M, D).reshape(plan_tokens, bs, D) head = init_tok.view(B, 1, 1, D).expand(B, nn, M, D).reshape(1, bs, D) plan = torch.cat([head, chunk], 0) # [1+plan_tokens, bs, D]
az = cand_z[:, n0:n1].view(B, nn, 1, fs, A).expand(B, nn, M, fs, A).reshape(bs, fs, A)
def clamp_(p): """D1 (+ D2 when free_tail is False). In-place on the plan tensor.""" p[1].view(bs, fs, C)[:, :, OBS_DIM:OBS_DIM + ACT_DIM] = az if not free_tail and plan_tokens > 1: p[2:].view(-1, bs, fs, C)[:, :, :, OBS_DIM:OBS_DIM + ACT_DIM] = zero_z
clamp_(plan) # once before the loop for m in range(sched.shape[0] - 1): frm = torch.from_numpy(np.concatenate([[0], sched[m]])).to(device)[:, None].repeat(1, bs) to = torch.from_numpy(np.concatenate([[0], sched[m + 1]])).to(device)[:, None].repeat(1, bs) plan[1:] = model.diffusion_model.sample_step(plan, None, frm, to, guidance_fn=None)[1:] clamp_(plan) # after EVERY step
# ---- D1 assertion: what the sampler held, in raw units, is the candidate -------------- got = _act_unz(model, plan[1].view(bs, fs, C)[:, :, OBS_DIM:OBS_DIM + ACT_DIM]) want = cand_act[:, n0:n1].view(B, nn, 1, fs, A).expand(B, nn, M, fs, A).reshape(bs, fs, A) e = float((got - want).abs().max().item()) clamp_err = max(clamp_err, e) if assert_clamp: assert e < clamp_tol, ( f"D1 action clamp FAILED: recovered actions differ from the candidate by {e:.3e} " f"(tol {clamp_tol}); the value would not be the value of the candidate")
# Reward channel only. `model.unnorm(model.unstack(plan))` would materialise a second # copy of the whole (1.29 MB/sequence) plan; the reward is one channel of each frame, and # the frame order below IS `unstack`'s order (token-major, then frame within the token). r_all = plan.view(1 + plan_tokens, bs, fs, C)[..., -1].permute(0, 2, 1).reshape( total_frames, bs) r_all = r_all * model.data_std[-1] + model.data_mean[-1] # unnormalised r_hat r = r_all[fs:fs + H].view(H, B, nn, M) # plan frames 1..H term_s[:, n0:n1] = r[H - 1] disc_s[:, n0:n1] = (r * w[:, None, None, None]).sum(0) del plan, r_all, r, chunk, head
out = dict( terminal=term_s.mean(-1), disc=disc_s.mean(-1), terminal_std=term_s.std(-1, unbiased=False), disc_std=disc_s.std(-1, unbiased=False), diag=dict(clamp_maxerr=clamp_err, clamp_tol=float(clamp_tol), H=H, M=M, N=int(N), B=int(B), gamma=float(gamma), free_tail=bool(free_tail), frame_stack=fs, bundle_dim=C, plan_tokens=int(plan_tokens), total_frames=int(total_frames), sched_rows=int(sched.shape[0]), crn_rows=bool(crn_rows), sampling_timesteps=int(model.sampling_timesteps), cand_per_chunk=int(cn), n_chunks=int(n_chunks), seed=int(seed), guidance="none (guidance_fn=None) -- value route, not planner route"), ) if return_samples: out["terminal_samples"] = term_s out["disc_samples"] = disc_s return out
AGGREGATIONS = ("terminal", "disc")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195"""CPU smoke for the Diffusion Forcing PLANNER (gen_q#274, item 1).
WHY THIS EXISTS. `train_df.py` has a smoke (status/nb/df_train_smoke.txt) and `td_plan.py` has one(status/nb/td_plan_smoke.txt), but `df_plan.py` -- the file that carries the ONLY piece of the DFcolumn that is our code rather than upstream's (the reward-guidance branch upstream leaves as`raise NotImplementedError`) -- has never been executed. Everything it could get wrong is silent:a guidance SIGN error would make DF minimise the provenance reward and still return a plausiblesuccess rate; a wrong weight vector would guide on the conditioning frames only; a padding bug wouldguide on frames the plan does not execute. None of those raise.
The model here is randomly initialised and tiny -- this tests the PLANNER, not the world model.Everything asserted is a property that must hold for ANY weights."""import sys, json, mathfrom pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parent))
import numpy as npimport torch
from df_data import OBS_DIM, ACT_DIM, BUNDLE_DIMfrom df_core import DFRise, default_cfgfrom df_plan import plan_bundles, best_actions, _guidance_weights
FAIL = []def check(name, cond, extra=""): print(f"[{'PASS' if cond else 'FAIL'}] {name} {extra}") if not cond: FAIL.append(name)
torch.manual_seed(0); np.random.seed(0)print(f"dims OBS={OBS_DIM} ACT={ACT_DIM} BUNDLE={BUNDLE_DIM} torch={torch.__version__}")
# ---------------------------------------------------------------- T1 weightsFS, GAMMA = 4, 0.9w = _guidance_weights(FS, 6, 12, GAMMA, w_cond=10.0).numpy()exp = np.concatenate([np.full(FS, 10.0), GAMMA ** np.arange(6), np.zeros(12 - FS - 6)])check("T1 weight vector == [w_cond]*fs + gamma^j + zero pad", np.allclose(w, exp, atol=1e-6), f"w={np.round(w,4).tolist()}")check("T1 padding frames carry ZERO weight", float(w[FS + 6:].sum()) == 0.0)# horizon longer than the room available must be truncated, not wrap aroundw2 = _guidance_weights(FS, 100, 12, GAMMA, w_cond=10.0).numpy()check("T1 over-long horizon truncates to the available frames", w2.shape == (12,) and np.allclose(w2[FS:], GAMMA ** np.arange(12 - FS), atol=1e-6))
# ---------------------------------------------------------------- tiny modelcfg = default_cfg(network_size=32, num_layers=2, attn_heads=2, dim_feedforward=64, timesteps=100, sampling_timesteps=4, frame_stack=FS)mean = np.zeros(BUNDLE_DIM, np.float32)std = np.full(BUNDLE_DIM, 2.0, np.float32) # non-trivial, so unnorm() is exercisedmean[-1], std[-1] = 0.25, 0.5 # reward channel gets its own scalemodel = DFRise(frame_stack=FS, n_tokens=4, mean=mean, std=std, cfg=cfg).eval()nparam = sum(p.numel() for p in model.parameters())print(f"tiny model params={nparam/1e6:.2f}M sampling_timesteps={model.sampling_timesteps}")
B, NP, H = 2, 4, 6obs = torch.randn(B, OBS_DIM)
def run(scale, seed=0, n_plans=NP, horizon=H): g = torch.Generator(device="cpu"); g.manual_seed(seed) return plan_bundles(model, obs, horizon, scale, GAMMA, n_plans=n_plans, device="cpu", generator=g)
# ---------------------------------------------------------------- T2 shapeso0 = run(0.0)plan_tokens = int(math.ceil(H / FS))check("T2 plan shape [H, B, n_plans, BUNDLE]", tuple(o0["plan"].shape) == (H, B, NP, BUNDLE_DIM), str(tuple(o0["plan"].shape)))check("T2 J shape [B, n_plans]", tuple(o0["J"].shape) == (B, NP), str(tuple(o0["J"].shape)))check("T2 J_iter has one row per scheduling step + 1", o0["J_iter"].shape == (o0["diag"]["sched_rows"], B, NP), str(o0["J_iter"].shape))check("T2 plan_tokens = ceil(H/frame_stack)", o0["diag"]["plan_tokens"] == plan_tokens, f"{o0['diag']['plan_tokens']} vs {plan_tokens}")check("T2 no NaN/Inf in the plan", bool(torch.isfinite(o0["plan"]).all()))check("T2 unguided run reports guidance_scale 0.0", o0["diag"]["guidance_scale"] == 0.0)
# ---------------------------------------------------------------- T3 determinisma = run(2.0, seed=7); b = run(2.0, seed=7)check("T3 same seed -> identical plan", torch.allclose(a["plan"], b["plan"], atol=0, rtol=0))c = run(2.0, seed=8)check("T3 different seed -> different plan", not torch.allclose(a["plan"], c["plan"], atol=1e-6))
# ---------------------------------------------------------------- T4 GUIDANCE SIGN# The one that matters. Guidance must RAISE the objective it is handed. Upstream's sample_step# computes grad = -d(guidance_fn)/dx and ADDS sqrt(1-a)*grad to pred_noise, which is classifier# guidance in the ASCENT direction (diffusion.py:423-441) -- so a correct wiring means J at the end# of diffusion grows with guidance_scale. A sign error here would publish a DF column that actively# avoids the expert partition, at a success rate that would still look like a number.SEEDS = list(range(6))J0 = np.array([float(run(0.0, seed=s)["J"].mean()) for s in SEEDS])J3 = np.array([float(run(3.0, seed=s)["J"].mean()) for s in SEEDS])J9 = np.array([float(run(9.0, seed=s)["J"].mean()) for s in SEEDS])print(f"T4 J(scale=0) mean={J0.mean():.4f} J(3)={J3.mean():.4f} J(9)={J9.mean():.4f}")print(f"T4 per-seed J0={np.round(J0,3).tolist()}")print(f"T4 per-seed J3={np.round(J3,3).tolist()}")print(f"T4 per-seed J9={np.round(J9,3).tolist()}")check("T4 guidance INCREASES the objective (scale 3 > scale 0, every seed)", bool((J3 > J0).all()), f"wins={int((J3>J0).sum())}/{len(SEEDS)}")check("T4 more guidance -> more objective (scale 9 > scale 3, every seed)", bool((J9 > J3).all()), f"wins={int((J9>J3).sum())}/{len(SEEDS)}")check("T4 the effect is not numerical noise (mean gain > 1e-3)", float((J3 - J0).mean()) > 1e-3, f"gain={float((J3-J0).mean()):.5f}")
# ---------------------------------------------------------------- T5 diagnostics are realo = run(3.0, seed=1)d = o["diag"]check("T5 J_spread > 0 with n_plans>1 (planner discriminates among its own samples)", d["J_spread"] > 0, f"J_spread={d['J_spread']:.5f}")check("T5 J_std > 0", d["J_std"] > 0, f"J_std={d['J_std']:.5f}")o1 = run(3.0, seed=1, n_plans=1)check("T5 n_plans=1 reports J_spread exactly 0 (documented, not an accident)", o1["diag"]["J_spread"] == 0.0)check("T5 J_gain == J_iter[-1]-J_iter[0] mean", abs(d["J_gain"] - float((o["J_iter"][-1] - o["J_iter"][0]).mean())) < 1e-5)check("T5 diag records gamma / horizon / n_plans verbatim", d["gamma"] == GAMMA and d["horizon_frames"] == H and d["n_plans"] == NP)
# ---------------------------------------------------------------- T6 best_actionsacts, sel = best_actions(o, execute_frames=3)check("T6 action shape [execute_frames, B, ACT_DIM]", tuple(acts.shape) == (3, B, ACT_DIM), str(tuple(acts.shape)))idx = o["J"].argmax(-1)man = torch.stack([o["plan"][:, i, idx[i]] for i in range(B)], 1)check("T6 best_actions selects the argmax-J candidate per batch element", torch.allclose(sel, man, atol=0, rtol=0), f"idx={idx.tolist()}")check("T6 executed actions are the ACT slice of the bundle", torch.allclose(acts, man[:3, :, OBS_DIM:OBS_DIM + ACT_DIM], atol=0, rtol=0))# What the env will actually be handed. DF's action channel is unconstrained -- report the range so# a future clamp decision is made on evidence, not assumed.amax = float(acts.abs().max())print(f"T6 |action|_max on an UNTRAINED model = {amax:.3f} " f"(env limit is 1.0; a trained model's range goes in the cell JSON)")check("T6 actions are finite", bool(torch.isfinite(acts).all()))
# ---------------------------------------------------------------- T7 execute_frames > H must not# silently return a short queue that the policy then drains into an index error.acts_long, _ = best_actions(o, execute_frames=H + 5)check("T7 execute_frames > horizon returns at most H frames (caller must not over-request)", acts_long.shape[0] == H, f"got {acts_long.shape[0]} for H={H}")
# ---------------------------------------------------------------- T8 horizon not a multiple of fso7 = run(3.0, seed=2, horizon=7) # 7 frames, frame_stack 4 -> 2 tokens, 1 pad framecheck("T8 non-multiple horizon returns exactly H frames", o7["plan"].shape[0] == 7)w7 = _guidance_weights(FS, 7, FS * (1 + 2), GAMMA).numpy()check("T8 the padded frame is excluded from the objective", float(w7[FS + 7:].sum()) == 0.0, f"tail={np.round(w7[FS:],4).tolist()}")
# ------------------------------------------------- T9 DFPlannerPolicy: queue, clamp, health# `df_policy.DFPlannerPolicy.__init__` builds the DINOv2 encoder, which needs the RISE robomimic env# this venv does not have. Everything AFTER the encoder -- the replan cadence, the action clamp and# the action-range health -- is testable here, and it is the part that decides what the env is# actually handed. The encoder itself is exercised by the GPU smoke through the eval harness.import df_policy as dfp
pol = object.__new__(dfp.DFPlannerPolicy)pol.model, pol.device = model, "cpu"pol.H, pol.guidance_scale, pol.gamma = H, 3.0, GAMMApol.n_plans, pol.execute_frames = NP, 3pol.step, pol.diag_path, pol.act_limit = 12345, "", 1.0pol.gen = torch.Generator(device="cpu"); pol.gen.manual_seed(0)pol.enc = lambda obs_t: obs_t["state"] # stand in for PooledDinoStatepol.reset()
class _FakeObs(dict): passob = {"state": obs} # the stub encoder returns it as the [B, OBS] state# get_action indexes v[:, -1]; give the stub a tensor it can handle by bypassing that pathpol.enc = lambda obs_t: obsa1 = pol.get_action({"state": obs.unsqueeze(1).repeat(1, 2, 1)})check("T9 get_action returns [B, ACT_DIM]", tuple(a1.shape) == (B, ACT_DIM), str(tuple(a1.shape)))check("T9 one plan after the first action", len(pol._diag) == 1, f"plans={len(pol._diag)}")for _ in range(pol.execute_frames - 1): pol.get_action({"state": obs.unsqueeze(1).repeat(1, 2, 1)})check("T9 no replan while the queue has actions (execute_frames=3 -> still 1 plan)", len(pol._diag) == 1, f"plans={len(pol._diag)}")pol.get_action({"state": obs.unsqueeze(1).repeat(1, 2, 1)})check("T9 replans exactly when the queue empties", len(pol._diag) == 2, f"plans={len(pol._diag)}")
check("T9 every emitted action is inside the env box", float(a1.abs().max()) <= 1.0 + 1e-6, f"|a|max={float(a1.abs().max()):.3f}")d9 = pol.diagnostics()print("T9 health: " + json.dumps({k: d9[k] for k in ("act_limit", "act_absmax", "act_clip_frac", "act_components", "plans", "n_plans")}))check("T9 act_absmax records the PRE-clamp magnitude (the clamp is not hidden)", d9["act_absmax"] > 1.0, f"act_absmax={d9['act_absmax']:.3f}")check("T9 act_clip_frac in [0,1] and >0 on this untrained model", 0.0 < d9["act_clip_frac"] <= 1.0, f"clip_frac={d9['act_clip_frac']:.3f}")check("T9 diagnostics carry J_spread / J_gain and the DF train step", "J_spread" in d9 and "J_gain" in d9 and d9["df_train_step"] == 12345)pol.reset()check("T9 reset() clears the plan log and the action-range counters", pol._diag == [] and pol._n_act == 0 and pol._a_absmax == 0.0)
print("\nSMOKE " + ("FAILED: " + ", ".join(FAIL) if FAIL else "PASSED (all checks)"))sys.exit(1 if FAIL else 0)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325#!/usr/bin/env python"""Train Diffusion Forcing on an rsm_rise task corpus (gen_q#274).
python train_df.py --cache cache/<task> --out runs/<task>/wm/df [--steps 100000] ...
Same corpus, same state definition, same split and the same binary provenance reward every othercolumn in tab:flagship sees -- see df_data.py's header. The diffusion model is upstream's(code/diffusion_forcing @ 475e0bca, main branch); see df_core.py's header for what is ours.
HEALTH NUMBERS ARE PRODUCED HERE, not bolted on later (#274's standing rule). Every `--eval-every`steps the trainer reports, on HELD-OUT episodes: val/loss the diffusion loss on validation windows; fid/obs_rmse_h<H> ROLLOUT FIDELITY: unguided (guidance 0) plans from a true start state, observation RMSE against the TRUE future at H frames, in the same z-scored units the state is defined in, next to fid/obs_rmse_h<H>_naive the RMSE of the trivial "the state never changes" predictor at the same H. A ratio >= 1 means the model's roll-out carries no information about the future and any planner score built on it must be flagged."""from __future__ import annotations
import argparse, json, os, sys, timefrom pathlib import Path
import numpy as npimport torch
sys.path.insert(0, str(Path(__file__).resolve().parent))from df_data import DFCacheData, OBS_DIM, ACT_DIM, BUNDLE_DIM # noqa: E402from df_core import DFRise, default_cfg, DF_COMMIT # noqa: E402
def parse(): p = argparse.ArgumentParser() p.add_argument("--cache", required=True) p.add_argument("--out", required=True) p.add_argument("--frame-stack", type=int, default=8) # = the project's hop/chunk p.add_argument("--n-tokens", type=int, default=8) # 64-frame training window p.add_argument("--batch", type=int, default=32) p.add_argument("--micro", type=int, default=8) p.add_argument("--lr", type=float, default=1e-4) p.add_argument("--weight-decay", type=float, default=1e-4) p.add_argument("--warmup-steps", type=int, default=2000) p.add_argument("--steps", type=int, default=100000) p.add_argument("--network-size", type=int, default=256) p.add_argument("--num-layers", type=int, default=12) p.add_argument("--attn-heads", type=int, default=4) p.add_argument("--dim-feedforward", type=int, default=1024) p.add_argument("--sampling-timesteps", type=int, default=50) p.add_argument("--ema", type=float, default=0.995) p.add_argument("--seed", type=int, default=0) p.add_argument("--eval-every", type=int, default=2500) p.add_argument("--save-every", type=int, default=10000) p.add_argument("--fid-batch", type=int, default=16) # run 28: the default used to start at 10, but the planner COMMITS RR_DF_EXECUTE=8 frames per # decision, so every published DF health number was measured at horizons the planner never # acts on. status/nb/df_actfid.txt: df_A reads fid/obs_ratio_h10 = 0.962 (healthy) and 1.43 # at H=1 (worse than stay-put). Measuring 1..8 as well is a strictly larger diagnostic; it # changes no training quantity. p.add_argument("--fid-horizons", default="1,2,4,8,10,20,50") # run 29 (gen_q#274). Target GRADIENT SHARE of the three channel groups, "obs:act:rew". # "" = the uniform `loss.mean()` every landed DF cell used, which spends 99.49% of the gradient # on the 1545 observation channels, 0.45% on the 7 action channels and 0.064% on the reward # channel. "4:2:1" is DF's OWN published planning bundle (obs 4 | act 2 | reward 1), i.e. this # knob moves TOWARD the configuration the method works in, not away from it. # This is a loss reduction over channels we already train. It adds no signal: same corpus, same # binary provenance reward, same state definition, same split, same evaluation. p.add_argument("--chan-share", default="") p.add_argument("--wandb-name", default="") # run 32 (gen_q#274), FINDING G -- ACTION/OBSERVATION ALIGNMENT. # Upstream's own planning trainer (code/diffusion_forcing_paper/algorithms/diffusion_forcing/ # df_planning.py:_preprocess_batch, L96-101) shifts the OBSERVATIONS by one and leaves the # ACTIONS unshifted: # init_obs = observations[:, 0] # observations = cat([observations[:, 1:], zeros_like(observations[:, -1:])], 1) # actions = actions # <- NOT shifted # bundles = make_bundle(observations, actions, rewards) # so upstream's bundle token t is (obs_{t+1}, a_t, r_t) -- "the action that PRODUCED obs_{t+1}", # which is also exactly how its rollout appends frames (df_planning.py:308 make_bundle(obs, # action, reward) after envs.step(action)). Our train_df.py:189 does # `make_sequence(bundle[1:], init_obs)`, which shifts BOTH channels, so our token t is # (obs_{t+1}, a_{t+1}). df_plan.best_actions then executes plan[0:k]'s actions starting from # s_0 -- i.e. a_1..a_k from s_0 -- and the action for the CURRENT state is never predicted at # all (it is zeroed in the conditioning token). That is a train/execute mismatch, not a # convention choice: our EXECUTOR already follows upstream's convention while our TRAINER does # not. # "ours" reproduces every already-measured cell byte-for-byte; "upstream" is the fix. p.add_argument("--act-align", default="ours", choices=["ours", "upstream"]) # ---- DF_MAKEITWORK mug-WM sweep (2026-09-24). All three default to the value every landed # checkpoint used, so a command that does not pass them is bit-identical to before. # # --cond-history. Upstream's conditioning token is ONE observation repeated frame_stack times # (df_planning.py:69-71, DFRise.make_sequence, df_plan.plan_bundles), so the model is asked to # predict the next frame from a POSITION with no VELOCITY. That is the most likely mechanism # behind the one fidelity defect both tasks share: `ratio_inf` at h=1 is 1.39 (mug) / 1.27 # (threading) -- worse than standing still with sampling noise removed -- while h>=4 is < 1 on # both. With --cond-history 1 the conditioning token is the agent's OWN last frame_stack # observations. FAIRNESS: an observation history is not privileged information -- DINO-WM and # every frame-stacking policy in tab:flagship already read one and the executing policy has its # own past for free. No object pose, no simulator state, no success bit, no outcome reward; the # action and reward channels of the conditioning token stay zeroed exactly as before. # COST: the plan starts at frame frame_stack instead of frame 1, so a config that wants the same # 64-frame plan asks for one more token (--n-tokens 9 at --frame-stack 8). p.add_argument("--cond-history", type=int, default=0, choices=[0, 1]) # --beta-schedule / --objective: upstream's own options (diffusion.py:84-91, :165-178), promoted # to knobs. The measured motivation is that a quarter to a half of every fid/obs_ratio_h* this # project published was the sampler's own noise (var_frac 0.24-0.45, status/nb/df_fidmean), which # is a statement about the noise schedule and the loss parameterisation, not about capacity. p.add_argument("--beta-schedule", default="linear", choices=["linear", "cosine", "sigmoid"]) p.add_argument("--objective", default="pred_x0", choices=["pred_x0", "pred_noise", "pred_v"]) # GPU packs run on the preemptable queue, so a run must be able to pick itself up where it was # killed. ckpt_last.pt carries the step and the optimiser state; --resume 0 disables. p.add_argument("--resume", type=int, default=1) return p.parse_args()
def seq_body(bundle, align): """bundle [W,B,C] -> the T=W-1 frames the plan tokens are trained on.
align="ours" : token t = bundle[t+1] = (obs_{t+1}, a_{t+1}, r) align="upstream" : obs from bundle[t+1], act/reward from bundle[t] = (obs_{t+1}, a_t, r) See --act-align. The reward channel here is the episode-constant provenance label, so the shift is a no-op on it except at the padded tail; it is shifted anyway so the layout is upstream's verbatim and nothing has to be argued about later. """ if align == "ours": return bundle[1:] return torch.cat([bundle[1:, :, :OBS_DIM], bundle[:-1, :, OBS_DIM:]], dim=-1)
def split_window(bundle, mask, frame_stack, align, cond_history): """window [W,B,C] + mask [W,B] -> (cond_obs, body, body_mask), one place for both layouts.
cond_history=0 (default, and what every checkpoint on disk used): cond_obs [B, OBS] = frame 0, which make_sequence / plan_bundles repeat frame_stack times. body = frames 1..T, body_mask = mask[1:]. cond_history=1 (--cond-history): cond_obs [B, fs, OBS] = the REAL frames 0..fs-1, oldest first. body = whole plan tokens starting at frame fs, under the SAME --act-align convention, so body[j] carries (obs_{fs+j}, a_{fs+j-1}). body_mask = mask[fs : fs+len(body)], the padding flag of those same frames. In both layouts the LAST CONDITIONING FRAME is the state the plan is predicted from -- frame 0 in the first, frame fs-1 in the second -- so `body[h]` is h+1 steps into the future either way and the stay-put control stays the same comparison. """ if not cond_history: return bundle[0, :, :OBS_DIM], seq_body(bundle, align), mask[1:] fs = int(frame_stack) body = seq_body(bundle[fs - 1:], align) # [W-fs, B, C], body[j] -> frame fs+j n = (body.shape[0] // fs) * fs # whole tokens only if n == 0: raise SystemExit("--cond-history 1 needs at least frame_stack plan frames: raise --n-tokens") return (bundle[:fs, :, :OBS_DIM].permute(1, 0, 2).contiguous(), body[:n], mask[fs:fs + n])
@torch.no_grad()def fidelity(model, data, rng, device, horizons, n=16, align="ours", cond_history=0): """Unguided roll-out vs the true future, and the stay-put control at the same horizons.""" from df_plan import plan_bundles model.eval() bundle, mask = data.sample(n, rng, split="val", device=device) cond_obs, body, m = split_window(bundle, mask, model.frame_stack, align, cond_history) T = body.shape[0] # the plan is predicted from the LAST conditioning frame; the stay-put control is that frame held init_obs = cond_obs if cond_obs.dim() == 2 else cond_obs[:, -1] out = {} plan = plan_bundles(model, cond_obs, horizon_frames=T, guidance_scale=0.0, gamma=0.0, n_plans=1, device=device)["plan"][:, :, 0, :] # [T, B, C] true_obs = body[:, :, :OBS_DIM] pred_obs = plan[:, :, :OBS_DIM] for H in horizons: h = min(H, T) - 1 if h < 0 or m[h].sum() == 0: continue w = m[h].bool() err = ((pred_obs[h][w] - true_obs[h][w]) ** 2).mean(-1).sqrt().mean().item() naive = ((init_obs[w] - true_obs[h][w]) ** 2).mean(-1).sqrt().mean().item() out[f"fid/obs_rmse_h{H}"] = err out[f"fid/obs_rmse_h{H}_naive"] = naive out[f"fid/obs_ratio_h{H}"] = err / max(naive, 1e-8) model.train() return out
def channel_weights(spec, device): """"obs:act:rew" target gradient shares -> per-channel weight [BUNDLE_DIM], mean 1.
Group g with n_g channels and target share s_g gets weight s_g/n_g per channel, so the group's contribution to the mean is proportional to s_g regardless of how wide it is. The vector is then renormalised to mean 1 so the TOTAL loss scale -- and therefore the effective learning rate -- is unchanged from the uniform reduction; only the split between the groups moves. Returns (tensor, diagnostic dict of the realised shares).""" s = [float(x) for x in spec.split(":")] if len(s) != 3 or min(s) < 0 or sum(s) <= 0: raise SystemExit(f"--chan-share must be 'obs:act:rew' with non-negative entries, got {spec!r}") n = [OBS_DIM, ACT_DIM, BUNDLE_DIM - OBS_DIM - ACT_DIM] per = [si / sum(s) / ni for si, ni in zip(s, n)] w = torch.cat([torch.full((ni,), pi) for ni, pi in zip(n, per)]) w = w / w.mean() tot = float(w.sum()) # loss.mean() weights every channel alike, so a group's share of # the gradient is its share of sum(w) shares = {g: float(w[a_:b_].sum() / tot) for g, (a_, b_) in zip(("obs", "act", "rew"), ((0, OBS_DIM), (OBS_DIM, OBS_DIM + ACT_DIM), (OBS_DIM + ACT_DIM, BUNDLE_DIM)))} return w.to(device), shares
def main(): a = parse() dev = "cuda" if torch.cuda.is_available() else "cpu" torch.manual_seed(a.seed); np.random.seed(a.seed) out = Path(a.out); out.mkdir(parents=True, exist_ok=True) data = DFCacheData(a.cache, frame_stack=a.frame_stack, n_tokens=a.n_tokens, seed=a.seed) mean, std = data.bundle_stats(seed=a.seed) cfg = default_cfg(network_size=a.network_size, num_layers=a.num_layers, attn_heads=a.attn_heads, dim_feedforward=a.dim_feedforward, sampling_timesteps=a.sampling_timesteps, frame_stack=a.frame_stack, beta_schedule=a.beta_schedule, objective=a.objective) model = DFRise(frame_stack=a.frame_stack, n_tokens=a.n_tokens, mean=mean, std=std, cfg=cfg).to(dev) ema = {k: v.detach().clone() for k, v in model.state_dict().items()} n_par = sum(p.numel() for p in model.parameters()) print(f"[train_df] params {n_par/1e6:.2f} M device {dev} bundle {BUNDLE_DIM} " f"plan {data.T} frames upstream {DF_COMMIT[:12]}", flush=True)
chan_w, chan_shares = (None, None) if a.chan_share: chan_w, chan_shares = channel_weights(a.chan_share, dev) print(f"[train_df] chan_share {a.chan_share!r} -> realised gradient shares " f"{ {k: round(v, 4) for k, v in chan_shares.items()} } " f"w_obs {chan_w[0]:.4g} w_act {chan_w[OBS_DIM]:.4g} w_rew {chan_w[-1]:.4g}", flush=True)
opt = torch.optim.AdamW(model.parameters(), lr=a.lr, weight_decay=a.weight_decay, betas=(0.9, 0.999)) rng = np.random.default_rng(a.seed) wb = None if a.wandb_name and os.environ.get("RSM_WANDB_ENTITY"): import wandb wb = wandb.init(entity=os.environ["RSM_WANDB_ENTITY"], project=os.environ.get("WANDB_PROJECT", "rsm_rise"), name=a.wandb_name, config=vars(a)) horizons = [int(x) for x in a.fid_horizons.split(",")] meta = dict(vars(a), upstream_commit=DF_COMMIT, bundle_dim=BUNDLE_DIM, obs_dim=OBS_DIM, act_dim=ACT_DIM, params=n_par, plan_frames=data.T, window_frames=data.W, n_train_eps=int(len(data.train_eps)), n_val_eps=int(len(data.val_eps)), n_expert_eps=int(data.ep_success.sum())) (out / "META.json").write_text(json.dumps(meta, indent=1, default=str))
start_step = 0 last = out / "ckpt_last.pt" if a.resume and last.exists(): ck = torch.load(last, map_location=dev, weights_only=False) model.load_state_dict(ck["online"] if "online" in ck else ck["model"]) ema = {k: v.to(dev) for k, v in ck["ema"].items()} if "opt" in ck: opt.load_state_dict(ck["opt"]) start_step = int(ck["step"]) rng = np.random.default_rng(a.seed + start_step) # do not replay the same window order print(f"[train_df] RESUMED from {last} at step {start_step}", flush=True) if start_step >= a.steps: print("[train_df] already complete", flush=True); return
t0 = time.time() for step in range(start_step + 1, a.steps + 1): for g in opt.param_groups: # upstream's manual warmup (df_base.py:63) g["lr"] = a.lr * min(1.0, step / max(1, a.warmup_steps)) opt.zero_grad(set_to_none=True) tot, nmb = 0.0, 0 for _ in range(max(1, a.batch // a.micro)): bundle, mask = data.sample(a.micro, rng, "train", dev) cond_obs, body, bmask = split_window(bundle, mask, a.frame_stack, a.act_align, a.cond_history) xs = model.make_sequence(body, cond_obs) # per-frame weight: 1 on the conditioning token and on real frames, 0 on tail padding fw = torch.cat([torch.ones(a.frame_stack, bundle.shape[1], device=dev), bmask], 0) fw = fw.view(-1, a.frame_stack, bundle.shape[1]).permute(0, 2, 1) # [t, B, fs] tok_mask = fw.amax(-1) k = model.noise_levels(xs, tok_mask) _, loss = model.loss(xs, k, weight=fw, chan_w=chan_w) (loss / max(1, a.batch // a.micro)).backward() tot += float(loss.detach()); nmb += 1 torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) opt.step() with torch.no_grad(): for k_, v in model.state_dict().items(): if v.dtype.is_floating_point: ema[k_].mul_(a.ema).add_(v, alpha=1 - a.ema) else: ema[k_].copy_(v)
if step % 100 == 0: msg = {"step": step, "loss": tot / nmb, "lr": opt.param_groups[0]["lr"], "s_per_step": (time.time() - t0) / max(1, step - start_step)} print("[train_df] " + json.dumps(msg), flush=True) if wb: wb.log(msg, step=step) if step % a.eval_every == 0 or step == a.steps: vb, vm = data.sample(a.micro, rng, "val", dev) with torch.no_grad(): vcond, vbody, vbmask = split_window(vb, vm, a.frame_stack, a.act_align, a.cond_history) xs = model.make_sequence(vbody, vcond) fw = torch.cat([torch.ones(a.frame_stack, vb.shape[1], device=dev), vbmask], 0) fw = fw.view(-1, a.frame_stack, vb.shape[1]).permute(0, 2, 1) _, vl = model.loss(xs, model.noise_levels(xs, fw.amax(-1)), weight=fw, chan_w=chan_w) h = fidelity(model, data, np.random.default_rng(a.seed + 1), dev, horizons, a.fid_batch, align=a.act_align, cond_history=a.cond_history) rec = {"step": step, "val/loss": float(vl), **h} print("[train_df] EVAL " + json.dumps(rec), flush=True) (out / "health.jsonl").open("a").write(json.dumps(rec) + "\n") if wb: wb.log(rec, step=step) if step % a.save_every == 0 or step == a.steps: # ckpt_s*: the EMA weights (what the planner loads). ckpt_last: EMA + online + optimiser, # so a preempted run resumes exactly rather than restarting. torch.save({"model": ema, "cfg": cfg, "meta": meta, "mean": mean, "std": std, "step": step}, out / f"ckpt_s{step}.pt") tmp = out / "ckpt_last.pt.tmp" torch.save({"model": ema, "ema": ema, "online": model.state_dict(), "opt": opt.state_dict(), "cfg": cfg, "meta": meta, "mean": mean, "std": std, "step": step}, tmp) os.replace(tmp, out / "ckpt_last.pt") print("[train_df] done", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285import copyfrom typing import Any
import flaximport jaximport jax.numpy as jnpimport ml_collectionsimport optax
from utils.encoders import encoder_modulesfrom utils.flax_utils import ModuleDict, TrainState, nonpytree_fieldfrom utils.loss_utils import hl_gauss_cross_entropy, hl_gauss_from_logits, sample_beta_timesfrom utils.networks import MLP_CLASSES, ActorVectorField, CategoricalValue
class IFQLAgent(flax.struct.PyTreeNode): """Implicit flow Q-learning (IFQL) agent.
IFQL is the flow variant of implicit diffusion Q-learning (IDQL). """
rng: Any network: Any config: Any = nonpytree_field()
@staticmethod def expectile_loss(adv, diff, expectile): """Compute the expectile loss.""" weight = jnp.where(adv >= 0, expectile, (1 - expectile)) return weight * (diff**2)
def value_loss(self, batch, grad_params): """Compute the IQL value loss.""" qs = self.network.select('target_critic')(batch['observations'], actions=batch['actions']) if self.config['q_agg'] == 'min': q = qs.min(axis=0) else: q = qs.mean(axis=0) v_logits = self.network.select('value')(batch['observations'], output_logits=True, params=grad_params) v = hl_gauss_from_logits(v_logits) weight = jnp.where(q - v >= 0, self.config['expectile'], 1 - self.config['expectile']) value_loss = (weight * hl_gauss_cross_entropy(v_logits, q)).mean()
return value_loss, { 'value_loss': value_loss, 'v_mean': v.mean(), 'v_max': v.max(), 'v_min': v.min(), }
def critic_loss(self, batch, grad_params): """Compute the IQL critic loss.""" next_v = self.network.select('value')(batch['next_observations']) discounts = batch['discounts'] if 'discounts' in batch else self.config['discount'] * batch['masks'] q = batch['rewards'] + discounts * next_v
q_logits = self.network.select('critic')( batch['observations'], actions=batch['actions'], output_logits=True, params=grad_params ) critic_loss = hl_gauss_cross_entropy(q_logits, q).mean()
return critic_loss, { 'critic_loss': critic_loss, 'q_mean': q.mean(), 'q_max': q.max(), 'q_min': q.min(), }
def actor_loss(self, batch, grad_params, rng=None): """Compute the behavioral flow-matching actor loss.""" batch_size, action_dim = batch['actions'].shape rng, x_rng, t_rng = jax.random.split(rng, 3)
x_0 = jax.random.normal(x_rng, (batch_size, action_dim)) x_1 = batch['actions'] t = sample_beta_times(t_rng, (batch_size, 1), self.config['betas']) x_t = (1 - t) * x_0 + t * x_1 vel = x_1 - x_0
pred = self.network.select('actor_flow')(batch['observations'], x_t, t, params=grad_params) actor_loss = jnp.mean((pred - vel) ** 2)
return actor_loss, { 'actor_loss': actor_loss, }
@jax.jit def total_loss(self, batch, grad_params, rng=None): """Compute the total loss.""" info = {} rng = rng if rng is not None else self.rng
value_loss, value_info = self.value_loss(batch, grad_params) for k, v in value_info.items(): info[f'value/{k}'] = v
critic_loss, critic_info = self.critic_loss(batch, grad_params) for k, v in critic_info.items(): info[f'critic/{k}'] = v
rng, actor_rng = jax.random.split(rng) actor_loss, actor_info = self.actor_loss(batch, grad_params, actor_rng) for k, v in actor_info.items(): info[f'actor/{k}'] = v
loss = value_loss + critic_loss + actor_loss return loss, info
def target_update(self, network, module_name): """Update the target network.""" new_target_params = jax.tree_util.tree_map( lambda p, tp: p * self.config['tau'] + tp * (1 - self.config['tau']), self.network.params[f'modules_{module_name}'], self.network.params[f'modules_target_{module_name}'], ) network.params[f'modules_target_{module_name}'] = new_target_params
@jax.jit def update(self, batch): """Update the agent and return a new agent with information dictionary.""" new_rng, rng = jax.random.split(self.rng)
def loss_fn(grad_params): return self.total_loss(batch, grad_params, rng=rng)
new_network, info = self.network.apply_loss_fn(loss_fn=loss_fn) self.target_update(new_network, 'critic')
return self.replace(network=new_network, rng=new_rng), info
@jax.jit def sample_actions( self, observations, seed=None, temperature=1.0, ): """Sample actions from the actor.""" orig_observations = observations batch_shape = orig_observations.shape[: -len(self.config['ob_dims'])] if self.config['encoder'] is not None: observations = self.network.select('actor_flow_encoder')(observations) action_seed, _ = jax.random.split(seed)
# Sample `num_samples` noises and propagate them through the flow. sample_shape = (*batch_shape, self.config['num_samples']) actions = jax.random.normal( action_seed, ( *sample_shape, self.config['action_dim'], ), ) sample_axis = len(batch_shape) n_observations = jnp.repeat( jnp.expand_dims(observations, sample_axis), self.config['num_samples'], axis=sample_axis ) n_orig_observations = jnp.repeat( jnp.expand_dims(orig_observations, sample_axis), self.config['num_samples'], axis=sample_axis ) for i in range(self.config['flow_steps']): t = jnp.full((*sample_shape, 1), i / self.config['flow_steps']) vels = self.network.select('actor_flow')(n_observations, actions, t, is_encoded=True) actions = actions + vels / self.config['flow_steps'] actions = jnp.clip(actions, -1, 1)
# Pick the action with the highest Q-value. qs = self.network.select('critic')(n_orig_observations, actions=actions) if self.config['q_agg'] == 'min': q = qs.min(axis=0) else: q = qs.mean(axis=0) best_idxs = jnp.argmax(q, axis=-1) gather_idxs = jnp.broadcast_to(best_idxs[..., None, None], (*best_idxs.shape, 1, self.config['action_dim'])) actions = jnp.take_along_axis(actions, gather_idxs, axis=-2).squeeze(axis=-2) return actions
@classmethod def create( cls, seed, ex_observations, ex_actions, config, ): """Create a new agent.
Args: seed: Random seed. ex_observations: Example batch of observations. ex_actions: Example batch of actions. config: Configuration dictionary. """ rng = jax.random.PRNGKey(seed) rng, init_rng = jax.random.split(rng, 2)
ex_times = ex_actions[..., :1] ob_dims = ex_observations.shape[1:] action_dim = ex_actions.shape[-1]
if config['mlp_class'] not in MLP_CLASSES: raise ValueError(f'Invalid mlp_class: {config["mlp_class"]}') mlp_class = MLP_CLASSES[config['mlp_class']]
# Define encoders. encoders = dict() if config['encoder'] is not None: encoder_module = encoder_modules[config['encoder']] encoders['value'] = encoder_module() encoders['critic'] = encoder_module() encoders['actor_flow'] = encoder_module()
# Define networks. value_def = CategoricalValue( hidden_dims=config['value_hidden_dims'], layer_norm=config['layer_norm'], num_ensembles=1, mlp_class=mlp_class, encoder=encoders.get('value'), ) critic_def = CategoricalValue( hidden_dims=config['value_hidden_dims'], layer_norm=config['layer_norm'], num_ensembles=2, mlp_class=mlp_class, encoder=encoders.get('critic'), ) actor_flow_def = ActorVectorField( hidden_dims=config['actor_hidden_dims'], action_dim=action_dim, mlp_class=mlp_class, layer_norm=config['actor_layer_norm'], encoder=encoders.get('actor_flow'), )
network_info = dict( value=(value_def, (ex_observations,)), critic=(critic_def, (ex_observations, ex_actions)), target_critic=(copy.deepcopy(critic_def), (ex_observations, ex_actions)), actor_flow=(actor_flow_def, (ex_observations, ex_actions, ex_times)), ) if encoders.get('actor_flow') is not None: # Add actor_flow_encoder to ModuleDict to make it separately callable. network_info['actor_flow_encoder'] = (encoders.get('actor_flow'), (ex_observations,)) networks = {k: v[0] for k, v in network_info.items()} network_args = {k: v[1] for k, v in network_info.items()}
network_def = ModuleDict(networks) network_tx = optax.adam(learning_rate=config['lr']) network_params = network_def.init(init_rng, **network_args)['params'] network = TrainState.create(network_def, network_params, tx=network_tx)
params = network_params params['modules_target_critic'] = params['modules_critic']
config['ob_dims'] = ob_dims config['action_dim'] = action_dim return cls(rng, network=network, config=flax.core.FrozenDict(**config))
def get_config(): config = ml_collections.ConfigDict( dict( agent_name='ifql', # Agent name. ob_dims=ml_collections.config_dict.placeholder(list), # Observation dimensions (will be set automatically). action_dim=ml_collections.config_dict.placeholder(int), # Action dimension (will be set automatically). lr=3e-4, # Learning rate. batch_size=256, # Batch size. actor_hidden_dims=(512, 512, 512, 512), # Actor network hidden dimensions. value_hidden_dims=(512, 512, 512, 512), # Value network hidden dimensions. mlp_class='resmlp', # MLP class ('mlp' or 'resmlp'). layer_norm=True, # Whether to use layer normalization. actor_layer_norm=True, # Whether to use layer normalization for the actor. discount=0.9999, # Discount factor. tau=0.001, # Target network update rate. expectile=0.5, # IQL expectile. n_step=200, # Number of steps for bootstrapped returns. q_agg='mean', # Aggregation method for Q values. num_samples=32, # Number of action samples for rejection sampling. flow_steps=10, # Number of flow steps. betas=(1.0, 1.5), # Beta parameters for time sampling. encoder=ml_collections.config_dict.placeholder(str), # Visual encoder name (None, 'impala_small', etc.). ) ) return config123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108import functoolsfrom typing import Sequence
import flax.linen as nnimport jax.numpy as jnp
from utils.networks import MLP
class ResnetStack(nn.Module): """ResNet stack module."""
num_features: int num_blocks: int max_pooling: bool = True
@nn.compact def __call__(self, x): initializer = nn.initializers.xavier_uniform() conv_out = nn.Conv( features=self.num_features, kernel_size=(3, 3), strides=1, kernel_init=initializer, padding='SAME', )(x)
if self.max_pooling: conv_out = nn.max_pool( conv_out, window_shape=(3, 3), padding='SAME', strides=(2, 2), )
for _ in range(self.num_blocks): block_input = conv_out conv_out = nn.relu(conv_out) conv_out = nn.Conv( features=self.num_features, kernel_size=(3, 3), strides=1, padding='SAME', kernel_init=initializer, )(conv_out)
conv_out = nn.relu(conv_out) conv_out = nn.Conv( features=self.num_features, kernel_size=(3, 3), strides=1, padding='SAME', kernel_init=initializer, )(conv_out) conv_out += block_input
return conv_out
class ImpalaEncoder(nn.Module): """IMPALA encoder."""
width: int = 1 stack_sizes: tuple = (16, 32, 32) num_blocks: int = 2 dropout_rate: float = None mlp_hidden_dims: Sequence[int] = (512,) layer_norm: bool = True
def setup(self): stack_sizes = self.stack_sizes self.stack_blocks = [ ResnetStack( num_features=stack_sizes[i] * self.width, num_blocks=self.num_blocks, ) for i in range(len(stack_sizes)) ] if self.dropout_rate is not None: self.dropout = nn.Dropout(rate=self.dropout_rate)
@nn.compact def __call__(self, x, train=True, cond_var=None): x = x.astype(jnp.float32) / 255.0
conv_out = x
for idx in range(len(self.stack_blocks)): conv_out = self.stack_blocks[idx](conv_out) if self.dropout_rate is not None: conv_out = self.dropout(conv_out, deterministic=not train)
conv_out = nn.relu(conv_out) if self.layer_norm: conv_out = nn.LayerNorm()(conv_out) out = conv_out.reshape((*x.shape[:-3], -1))
out = MLP(self.mlp_hidden_dims, activate_final=True, layer_norm=self.layer_norm)(out)
return out
encoder_modules = { 'impala': ImpalaEncoder, 'impala_debug': functools.partial(ImpalaEncoder, num_blocks=1, stack_sizes=(4, 4)), 'impala_small': functools.partial(ImpalaEncoder, num_blocks=1), 'impala_large': functools.partial(ImpalaEncoder, stack_sizes=(64, 128, 128), mlp_hidden_dims=(1024,)),}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337import functoolsimport gcimport globimport jsonimport osimport pickleimport timefrom typing import Any, Dict, Mapping, Sequence
import flaximport flax.linen as nnimport jaximport jax.numpy as jnpimport numpy as npimport optax
nonpytree_field = functools.partial(flax.struct.field, pytree_node=False)
class ModuleDict(nn.Module): """A dictionary of modules.
This allows sharing parameters between modules and provides a convenient way to access them.
Attributes: modules: Dictionary of modules. """
modules: Dict[str, nn.Module]
@nn.compact def __call__(self, *args, name=None, **kwargs): """Forward pass.
For initialization, call with `name=None` and provide the arguments for each module in `kwargs`. Otherwise, call with `name=<module_name>` and provide the arguments for that module. """ if name is None: if kwargs.keys() != self.modules.keys(): raise ValueError( f'When `name` is not specified, kwargs must contain the arguments for each module. ' f'Got kwargs keys {kwargs.keys()} but module keys {self.modules.keys()}' ) out = {} for key, value in kwargs.items(): if isinstance(value, Mapping): out[key] = self.modules[key](**value) elif isinstance(value, Sequence): out[key] = self.modules[key](*value) else: out[key] = self.modules[key](value) return out
return self.modules[name](*args, **kwargs)
class TrainState(flax.struct.PyTreeNode): """Custom train state for models.
Attributes: step: Counter to keep track of the training steps. It is incremented by 1 after each `apply_gradients` call. apply_fn: Apply function of the model. model_def: Model definition. params: Parameters of the model. tx: optax optimizer. opt_state: Optimizer state. """
step: int apply_fn: Any = nonpytree_field() model_def: Any = nonpytree_field() params: Any tx: Any = nonpytree_field() opt_state: Any
@classmethod def create(cls, model_def, params, tx=None, **kwargs): """Create a new train state.""" if tx is not None: opt_state = tx.init(params) else: opt_state = None
return cls( step=1, apply_fn=model_def.apply, model_def=model_def, params=params, tx=tx, opt_state=opt_state, **kwargs, )
def __call__(self, *args, params=None, method=None, **kwargs): """Forward pass.
When `params` is not provided, it uses the stored parameters.
The typical use case is to set `params` to `None` when you want to *stop* the gradients, and to pass the current traced parameters when you want to flow the gradients. In other words, the default behavior is to stop the gradients, and you need to explicitly provide the parameters to flow the gradients.
Args: *args: Arguments to pass to the model. params: Parameters to use for the forward pass. If `None`, it uses the stored parameters, without flowing the gradients. method: Method to call in the model. If `None`, it uses the default `apply` method. **kwargs: Keyword arguments to pass to the model. """ if params is None: params = self.params variables = {'params': params} if method is not None: method_name = getattr(self.model_def, method) else: method_name = None
return self.apply_fn(variables, *args, method=method_name, **kwargs)
def select(self, name): """Helper function to select a module from a `ModuleDict`.""" return functools.partial(self, name=name)
def apply_gradients(self, grads, **kwargs): """Apply the gradients and return the updated state.""" updates, new_opt_state = self.tx.update(grads, self.opt_state, self.params) new_params = optax.apply_updates(self.params, updates)
return self.replace( step=self.step + 1, params=new_params, opt_state=new_opt_state, **kwargs, )
def apply_loss_fn(self, loss_fn): """Apply the loss function and return the updated state and info.
It additionally computes the gradient statistics and adds them to the dictionary. """ grads, info = jax.grad(loss_fn, has_aux=True)(self.params)
grad_max = jax.tree_util.tree_map(jnp.max, grads) grad_min = jax.tree_util.tree_map(jnp.min, grads) grad_norm = jax.tree_util.tree_map(jnp.linalg.norm, grads)
grad_max_flat = jnp.concatenate([jnp.reshape(x, -1) for x in jax.tree_util.tree_leaves(grad_max)], axis=0) grad_min_flat = jnp.concatenate([jnp.reshape(x, -1) for x in jax.tree_util.tree_leaves(grad_min)], axis=0) grad_norm_flat = jnp.concatenate([jnp.reshape(x, -1) for x in jax.tree_util.tree_leaves(grad_norm)], axis=0)
final_grad_max = jnp.max(grad_max_flat) final_grad_min = jnp.min(grad_min_flat) final_grad_norm = jnp.linalg.norm(grad_norm_flat, ord=1)
info.update( { 'grad/max': final_grad_max, 'grad/min': final_grad_min, 'grad/norm': final_grad_norm, } )
return self.apply_gradients(grads=grads), info
def save_agent(agent, save_dir, epoch, name=None): """Save the agent to a file, atomically.
Args: agent: Agent. save_dir: Directory to save the agent. epoch: Epoch number. name: Override the file name (used for the rolling resume checkpoint).
The write goes to a temporary file that is then renamed. A checkpoint is multiple GB and jobs on this cluster are killed mid-write; a half-written params_*.pkl is the worst possible failure, because resume picks the newest checkpoint and would then crash on every relaunch. """
save_dict = dict( agent=flax.serialization.to_state_dict(agent), ) save_path = os.path.join(save_dir, name if name is not None else f'params_{epoch}.pkl') tmp_path = f'{save_path}.tmp{os.getpid()}' with open(tmp_path, 'wb') as f: pickle.dump(save_dict, f) f.flush() os.fsync(f.fileno()) os.replace(tmp_path, save_path)
print(f'Saved to {save_path}')
LATEST_PARAMS = 'params_latest.pkl'RESUME_STATE = 'resume.json'
def save_resume_checkpoint(agent, save_dir, step): """Overwrite the rolling resume checkpoint (params_latest.pkl + resume.json).
Archival checkpoints (params_<step>.pkl) exist to be re-evaluated later, so they sit on the evaluation grid and are kept. This one exists only so a killed job restarts near where it died, so it is written far more often and overwritten in place -- one file per run, not one per save. """ save_agent(agent, save_dir, step, name=LATEST_PARAMS) tmp = os.path.join(save_dir, RESUME_STATE + '.tmp') with open(tmp, 'w') as f: json.dump(dict(step=int(step), time=time.time()), f) os.replace(tmp, os.path.join(save_dir, RESUME_STATE))
def _load_state_dict_host(path): """Unpickle a checkpoint's state dict into HOST memory, never the accelerator.
``jax.Array.__reduce__`` reconstructs through ``device_put(np_value)`` with no device, so a plain ``pickle.load`` stages every leaf on the default device. That is fatal on resume: the freshly initialised agent is already resident, so a 4096x4 arm asks the card for a second ~3 GB copy of itself and dies with RESOURCE_EXHAUSTED inside ``pickle.load`` (the packed waves run two workers per card at mem_frac 0.45). Pinning the default device to CPU for the unpickle keeps the checkpoint in host RAM; the caller then frees the template's buffers before copying it back, so peak device memory over the whole restore is one copy of the model instead of two. """ with jax.default_device(jax.devices('cpu')[0]): with open(path, 'rb') as f: load_dict = pickle.load(f) # Uncommitted CPU arrays would be re-transferred on every jitted call; hand back plain numpy so the # tree is unambiguously host-side until we put it back deliberately. return jax.tree_util.tree_map(np.asarray, load_dict['agent'])
def _reset_opt_state(agent, state_dict): """Replace every saved ``opt_state`` subtree with the TARGET's freshly-initialized one.
A fork onto a DIFFERENT optax structure cannot restore the saved optimizer state. Concretely: a parent trained with `occ_lr_mult == actor_lr_mult == 1.0` takes rsm.py's single `optax.adam` branch, whose state serializes as a plain 2-tuple ({'0','1'}); a child that sets `occ_lr_mult != 1.0` trips the `actor_knobs` test and builds `optax.multi_transform`, whose state is `MultiTransformState(inner_states=...)`. `from_state_dict` then raises
ValueError: The field names of the state dict and the named tuple do not match, got {'0', '1'} and {'inner_states'} at path ./network/opt_state
and the arm dies at restore having trained ZERO steps (this killed all 10 arms of wave ocOL). The PARAMS are unaffected -- only Adam's accumulators are structurally incompatible.
Dropping them gives a COLD Adam restart (m = v = 0), which is NOT free: with zero accumulators the first bias-corrected update is ~lr * sign(g) on every parameter, a full-size kick on an otherwise converged network. That transient is real, so every arm in a wave that uses this path -- INCLUDING its control -- must take the same path, or the transient is attributed to whatever else the arms differ in. """ fresh = flax.serialization.to_state_dict(agent)
def walk(loaded, tgt): for k, v in loaded.items(): if k == 'opt_state' and k in tgt: loaded[k] = tgt[k] elif isinstance(v, dict) and isinstance(tgt.get(k), dict): walk(v, tgt[k])
walk(state_dict, fresh) return state_dict
def _fill_missing_opt_state(agent, state_dict): """Re-insert any ``opt_state`` subtree the checkpoint does NOT carry, from the fresh target.
``tools/strip_opt_state.py`` rewrites archival ``params_<step>.pkl`` without their Adam accumulators: ``opt_state`` is two thirds of every checkpoint (2.02 GB of a 3.03 GB file) and is read only when RESUMING training. A re-scored grid point is only ever rolled out, so for ``tools/final_eval.py`` / ``tools/eval_checkpoint.py`` the accumulators are dead weight.
``flax.serialization.from_state_dict`` matches key sets exactly, so a stripped file otherwise dies with ``ValueError: target dict contains keys {'opt_state'} which are not present in state dict``. This differs from ``_reset_opt_state``, which handles a key that is PRESENT but structurally incompatible; here the key is ABSENT. Both end at the same place -- the target's freshly initialised accumulators -- so a stripped checkpoint restores as a COLD Adam start. That is exactly why the stripper refuses to touch a seed's highest-step checkpoint: resuming from a stripped file would be a real behaviour change, while re-evaluating one cannot be.
Returns the state dict unchanged when nothing is missing, so the 8000+ unstripped checkpoints take a byte-identical path through the loader. """ fresh = flax.serialization.to_state_dict(agent)
def walk(loaded, tgt): if not isinstance(loaded, dict) or not isinstance(tgt, dict): return for k, v in tgt.items(): if k not in loaded: if k == 'opt_state': loaded[k] = v continue walk(loaded[k], v)
walk(state_dict, fresh) return state_dict
def _merge_state_dict(agent, state_dict, path): """Load a host-side state dict into ``agent`` and return it on the default device.""" # OC_RESTORE_PARAMS_ONLY=1 keeps the target's own fresh opt_state instead of the saved one. # Required for any fork that changes occ_lr_mult / actor_lr_mult / actor_grad_clip / # actor_adam_b2 away from the parent's, because those switch the optimizer STRUCTURE. if os.environ.get('OC_RESTORE_PARAMS_ONLY', '') not in ('', '0'): state_dict = _reset_opt_state(agent, state_dict) print('OC_RESTORE_PARAMS_ONLY: kept fresh opt_state (COLD Adam restart)', flush=True) # A stripped archival checkpoint carries params but no opt_state; refill it so the key sets match. state_dict = _fill_missing_opt_state(agent, state_dict) agent = flax.serialization.from_state_dict(agent, state_dict) # numpy leaves; template buffers now dead del state_dict gc.collect() # actually release the template's device buffers before allocating the restored ones agent = jax.tree_util.tree_map(lambda x: jax.device_put(x) if isinstance(x, np.ndarray) else x, agent) print(f'Restored from {path}', flush=True) return agent
def restore_agent_file(agent, path): """Restore the agent from an exact .pkl path (used by the resume launcher, which picks the file).""" return _merge_state_dict(agent, _load_state_dict_host(path), path)
def restore_agent(agent, restore_path, restore_epoch): """Restore the agent from a file.
Args: agent: Agent. restore_path: Path to the directory containing the saved agent. restore_epoch: Epoch number. """ candidates = glob.glob(restore_path)
assert len(candidates) == 1, f'Found {len(candidates)} candidates: {candidates}'
restore_path = candidates[0] + f'/params_{restore_epoch}.pkl'
return _merge_state_dict(agent, _load_state_dict_host(restore_path), restore_path)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556import jaximport jax.numpy as jnpimport jax.scipy.special
HL_GAUSS_MIN_VALUE = 0.0HL_GAUSS_MAX_VALUE = 1.0HL_GAUSS_NUM_BINS = 101HL_GAUSS_SIGMA_RATIO = 0.75
def sample_beta_times(rng, shape, betas): """Sample flow times from a Beta distribution.""" beta_a, beta_b = betas if beta_a == 1.0: # Use inverse CDF for Beta(1, b), which is much faster than jax.random.beta. t_uniform = jax.random.uniform(rng, shape) return 1 - (1 - t_uniform) ** (1 / beta_b) return jax.random.beta(rng, beta_a, beta_b, shape)
def hl_gauss_bin_centers(num_bins=HL_GAUSS_NUM_BINS): """Return HL-Gauss bin centers over [0, 1].""" edges = jnp.linspace(HL_GAUSS_MIN_VALUE, HL_GAUSS_MAX_VALUE, num_bins + 1, dtype=jnp.float32) return (edges[:-1] + edges[1:]) / 2
def hl_gauss_targets(targets, num_bins=HL_GAUSS_NUM_BINS): """Convert scalar targets to Gaussian-smoothed histogram targets.""" edges = jnp.linspace(HL_GAUSS_MIN_VALUE, HL_GAUSS_MAX_VALUE, num_bins + 1, dtype=jnp.float32) bin_width = (HL_GAUSS_MAX_VALUE - HL_GAUSS_MIN_VALUE) / num_bins sigma = HL_GAUSS_SIGMA_RATIO * bin_width
targets = jnp.clip(targets, HL_GAUSS_MIN_VALUE, HL_GAUSS_MAX_VALUE)[..., None] cdf_evals = jax.scipy.special.erf((edges - targets) / (jnp.sqrt(2.0) * sigma)) z = cdf_evals[..., -1:] - cdf_evals[..., :1] probs = cdf_evals[..., 1:] - cdf_evals[..., :-1] return probs / jnp.maximum(z, 1e-8)
def hl_gauss_from_probs(probs): """Convert categorical probabilities to scalar values.""" centers = hl_gauss_bin_centers(probs.shape[-1]) return jnp.sum(probs * centers, axis=-1)
def hl_gauss_from_logits(logits): """Convert categorical logits to scalar values.""" return hl_gauss_from_probs(jax.nn.softmax(logits, axis=-1))
def hl_gauss_cross_entropy(logits, targets): """Compute cross entropy from HL-Gauss targets to predicted logits.""" target_probs = hl_gauss_targets(targets, num_bins=logits.shape[-1]) log_probs = jax.nn.log_softmax(logits, axis=-1) return -jnp.sum(target_probs * log_probs, axis=-1)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378from typing import Any, Optional, Sequence
try: # rsm_rise: the project's JAX env (third_party/openpi/.venv) has no distrax. IFQL uses only # MLP / ResidualMLP / CategoricalValue / ActorVectorField, none of which need it, so the import # is made optional rather than vendoring distrax. Anything that DOES need it fails at use time. import distraxexcept ModuleNotFoundError: # pragma: no cover distrax = Noneimport flax.linen as nnimport jax.numpy as jnp
from utils.loss_utils import HL_GAUSS_NUM_BINS, hl_gauss_from_logits
def default_init(scale=1.0): """Default kernel initializer.""" return nn.initializers.variance_scaling(scale, 'fan_avg', 'uniform')
def ensemblize(cls, num_qs, in_axes=None, out_axes=0, **kwargs): """Ensemblize a module.""" return nn.vmap( cls, variable_axes={'params': 0, 'intermediates': 0}, split_rngs={'params': True}, in_axes=in_axes, out_axes=out_axes, axis_size=num_qs, **kwargs, )
class Identity(nn.Module): """Identity layer."""
def __call__(self, x): return x
class MLP(nn.Module): """Multi-layer perceptron.
Attributes: hidden_dims: Hidden layer dimensions. activations: Activation function. activate_final: Whether to apply activation to the final layer. kernel_init: Kernel initializer. layer_norm: Whether to apply layer normalization. """
hidden_dims: Sequence[int] activations: Any = nn.gelu activate_final: bool = False kernel_init: Any = default_init() layer_norm: bool = True
@nn.compact def __call__(self, x): for i, size in enumerate(self.hidden_dims): x = nn.Dense(size, kernel_init=self.kernel_init)(x) if i + 1 < len(self.hidden_dims) or self.activate_final: x = self.activations(x) if self.layer_norm: x = nn.LayerNorm()(x) if i == len(self.hidden_dims) - 2: self.sow('intermediates', 'feature', x) return x
class ResidualMLPBlock(nn.Module): """Residual dense block for vector features."""
hidden_dim: int activations: Any = nn.gelu kernel_init: Any = default_init() layer_norm: bool = True
@nn.compact def __call__(self, x: Any) -> Any: residual = x x = nn.Dense(self.hidden_dim, kernel_init=self.kernel_init)(x) x = self.activations(x) if self.layer_norm: x = nn.LayerNorm()(x) x = nn.Dense(self.hidden_dim, kernel_init=self.kernel_init)(x) x = residual + x x = self.activations(x) if self.layer_norm: x = nn.LayerNorm()(x) return x
class ResidualMLP(nn.Module): """Residual MLP for vector inputs."""
hidden_dims: Sequence[int] output_dim: int activations: Any = nn.gelu kernel_init: Any = default_init() layer_norm: bool = True
@nn.compact def __call__(self, x: Any) -> Any: if not self.hidden_dims: return nn.Dense(self.output_dim, kernel_init=self.kernel_init)(x)
x = nn.Dense(self.hidden_dims[0], kernel_init=self.kernel_init)(x) x = self.activations(x) if self.layer_norm: x = nn.LayerNorm()(x)
for hidden_dim in self.hidden_dims: if hidden_dim != x.shape[-1]: raise ValueError( 'ResidualMLP requires constant hidden widths after the input projection; ' f'got current width {x.shape[-1]} and requested width {hidden_dim}.' ) x = ResidualMLPBlock( hidden_dim=hidden_dim, activations=self.activations, kernel_init=self.kernel_init, layer_norm=self.layer_norm, )(x)
return nn.Dense(self.output_dim, kernel_init=self.kernel_init)(x)
MLP_CLASSES = dict( mlp=MLP, resmlp=ResidualMLP,)
class LogParam(nn.Module): """Scalar parameter module with log scale."""
init_value: float = 1.0
@nn.compact def __call__(self): log_value = self.param('log_value', init_fn=lambda key: jnp.full((), jnp.log(self.init_value))) return jnp.exp(log_value)
class TransformedWithMode(distrax.Transformed if distrax is not None else object): """Transformed distribution with mode calculation."""
def mode(self): return self.bijector.forward(self.distribution.mode())
class Actor(nn.Module): """Gaussian actor network.
Attributes: hidden_dims: Hidden layer dimensions. action_dim: Action dimension. mlp_class: MLP class. layer_norm: Whether to apply layer normalization. log_std_min: Minimum value of log standard deviation. log_std_max: Maximum value of log standard deviation. tanh_squash: Whether to squash the action with tanh. state_dependent_std: Whether to use state-dependent standard deviation. const_std: Whether to use constant standard deviation. final_fc_init_scale: Initial scale of the final fully-connected layer. encoder: Optional encoder module to encode the inputs. """
hidden_dims: Sequence[int] action_dim: int mlp_class: Any = MLP layer_norm: bool = True log_std_min: Optional[float] = -5 log_std_max: Optional[float] = 2 tanh_squash: bool = False state_dependent_std: bool = False const_std: bool = True final_fc_init_scale: float = 1e-2 encoder: nn.Module = None
def setup(self): if self.mlp_class is ResidualMLP: self.actor_net = self.mlp_class( self.hidden_dims, self.hidden_dims[-1], layer_norm=self.layer_norm, ) else: self.actor_net = self.mlp_class( self.hidden_dims, activate_final=True, layer_norm=self.layer_norm, ) self.mean_net = nn.Dense(self.action_dim, kernel_init=default_init(self.final_fc_init_scale)) if self.state_dependent_std: self.log_std_net = nn.Dense(self.action_dim, kernel_init=default_init(self.final_fc_init_scale)) else: if not self.const_std: self.log_stds = self.param('log_stds', nn.initializers.zeros, (self.action_dim,))
def __call__( self, observations, temperature=1.0, ): """Return action distributions.
Args: observations: Observations. temperature: Scaling factor for the standard deviation. """ if self.encoder is not None: inputs = self.encoder(observations) else: inputs = observations outputs = self.actor_net(inputs)
means = self.mean_net(outputs) if self.state_dependent_std: log_stds = self.log_std_net(outputs) else: if self.const_std: log_stds = jnp.zeros_like(means) else: log_stds = self.log_stds
log_stds = jnp.clip(log_stds, self.log_std_min, self.log_std_max)
distribution = distrax.MultivariateNormalDiag(loc=means, scale_diag=jnp.exp(log_stds) * temperature) if self.tanh_squash: distribution = TransformedWithMode(distribution, distrax.Block(distrax.Tanh(), ndims=1))
return distribution
class Value(nn.Module): """Value/critic network.
This module can be used for both value V(s, g) and critic Q(s, a, g) functions.
Attributes: hidden_dims: Hidden layer dimensions. layer_norm: Whether to apply layer normalization. num_ensembles: Number of ensemble components. encoder: Optional encoder module to encode the inputs. """
hidden_dims: Sequence[int] layer_norm: bool = True num_ensembles: int = 2 mlp_class: Any = MLP encoder: nn.Module = None
def setup(self): use_residual = self.mlp_class is ResidualMLP mlp_class = self.mlp_class if self.num_ensembles > 1: mlp_class = ensemblize(mlp_class, self.num_ensembles) if use_residual: value_net = mlp_class(self.hidden_dims, 1, layer_norm=self.layer_norm) else: value_net = mlp_class((*self.hidden_dims, 1), activate_final=False, layer_norm=self.layer_norm)
self.value_net = value_net
def __call__(self, observations, actions=None): """Return values or critic values.
Args: observations: Observations. actions: Actions (optional). """ if self.encoder is not None: inputs = [self.encoder(observations)] else: inputs = [observations] if actions is not None: inputs.append(actions) inputs = jnp.concatenate(inputs, axis=-1)
v = self.value_net(inputs).squeeze(-1)
return v
class CategoricalValue(nn.Module): """Categorical value/critic network for HL-Gauss losses."""
hidden_dims: Sequence[int] layer_norm: bool = True num_ensembles: int = 2 num_bins: int = HL_GAUSS_NUM_BINS mlp_class: Any = MLP encoder: nn.Module = None
def setup(self): use_residual = self.mlp_class is ResidualMLP mlp_class = self.mlp_class if self.num_ensembles > 1: mlp_class = ensemblize(mlp_class, self.num_ensembles) if use_residual: self.value_net = mlp_class(self.hidden_dims, self.num_bins, layer_norm=self.layer_norm) else: self.value_net = mlp_class( (*self.hidden_dims, self.num_bins), activate_final=False, layer_norm=self.layer_norm, )
def __call__(self, observations, actions=None, output_logits=False): """Return scalar values or categorical logits.""" if self.encoder is not None: inputs = [self.encoder(observations)] else: inputs = [observations] if actions is not None: inputs.append(actions) inputs = jnp.concatenate(inputs, axis=-1)
logits = self.value_net(inputs) if output_logits: return logits return hl_gauss_from_logits(logits)
class ActorVectorField(nn.Module): """Actor vector field network for flow matching.
Attributes: hidden_dims: Hidden layer dimensions. action_dim: Action dimension. layer_norm: Whether to apply layer normalization. encoder: Optional encoder module to encode the inputs. """
hidden_dims: Sequence[int] action_dim: int mlp_class: Any = MLP layer_norm: bool = True encoder: nn.Module = None
def setup(self) -> None: if self.mlp_class is ResidualMLP: self.mlp = self.mlp_class(self.hidden_dims, self.action_dim, layer_norm=self.layer_norm) else: self.mlp = self.mlp_class( (*self.hidden_dims, self.action_dim), activate_final=False, layer_norm=self.layer_norm, )
def _embed_times(self, times): freqs = jnp.arange(1, 33, dtype=times.dtype) angles = 2 * jnp.pi * times * freqs return jnp.concatenate([times, jnp.cos(angles), jnp.sin(angles)], axis=-1)
@nn.compact def __call__(self, observations, actions, times=None, conditions=None, is_encoded=False): """Return the vectors at the given states, actions, and times (optional).
Args: observations: Observations. actions: Actions. times: Times (optional). conditions: Additional conditioning variables (optional). is_encoded: Whether the observations are already encoded. """ if not is_encoded and self.encoder is not None: observations = self.encoder(observations) inputs = [observations, actions] if conditions is not None: inputs.append(conditions) if times is not None: inputs.append(self._embed_times(times)) inputs = jnp.concatenate(inputs, axis=-1) v = self.mlp(inputs)
return v123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395#!/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 withan 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_plusimplementation, 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. Whatthis 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-scoredwith 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 aspublished -- 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-provenancelabel, 1 on every frame of an episode that came from the expert file and 0 on every frame of asuboptimal/play episode. It is read from the source HDF5's `rewards` (constant within an episode; thescript 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 thatV in [0,1]. Our provenance reward is DENSE (1 on every expert frame), so the raw n-step returnsum_{k<200} gamma^k r is ~200 and every expert state would clip to the top bin -- a constant critic withno ranking at all. The reward is therefore multiplied by (1 - discount) (`--reward-scale auto`), which isa strictly monotone rescaling of the identical reward signal: the fixed point becomesV = (1-gamma) * E[sum gamma^k r] in [0, 1], i.e. the discounted AVERAGE provenance label = "how expert-likedoes the future from here look", the same quantity the RSM membership head estimates. Rankings areunchanged by the rescale, so the fairness rule ("same reward as every other method") is preserved; onlythe axis the two-hot head has to represent changes. `--reward-scale 1.0` restores the raw sum for acontrol.
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 demonstrationends, not because the MDP reached an absorbing state, so the last transition is TRUNCATED and keepsmasks = 1, bootstrapping off the final observation -- the standard convention, and the one ogbench usesfor its own non-goal-reaching trajectories. That is also what makes the value usable here: it puts thefixed 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 our230-370-frame episodes at gamma = 0.9999, which is 2-4 of the 101 bins: the provenance gap survives butthe differences between 128 candidate actions at one state fall below one bin and the critic cannot rankat all. Every run records its realised Q/V range in IFQL.json (`value_spread.q_range_in_bins`) so thisis 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 writesa rolling `params_latest.pkl` + `resume.json` every `--resume-every` steps (25 000, ~2 min of work) andcontinues from it on restart. Without that a preemption threw away up to the whole 500k-step run -- 5 ofthe first 21 trainings restarted from step 1 before this existed. `train.seed` still fixes the networkinitialisation, so a resumed run is the SAME arm; only the batch order after the restart differs, and thedata 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 thefeat_stats path. Eval runs inside the RISE robomimic env, whose python has no JAX, so both the criticbackend (robomimic/algo/ifql_torch.py) and the flow actor read that bundle in torch. Numerical parity ofthe 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 argparseimport jsonimport osimport pickleimport sysimport timefrom pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parentsys.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
# --------------------------------------------------------------------------- datadef 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, )
# --------------------------------------------------------------------------- exportdef _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)
# --------------------------------------------------------------------------- maindef 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384<img src="rise_fig.png" alt="fig1" />
[](https://docs.python.org/3/whatsnew/3.10.html)
Code for the paper Using Non-Expert Data to Robustify Imitation Learning via Offline Reinforcement Learning.
[Website](https://uwrobotlearning.github.io/RISE-offline/) | [Paper](https://arxiv.org/abs/2510.19495)
### Installation
Clone repo
```git clone git@github.com:UWRobotLearning/RISE.git```
Install Dependencies
```cd ood-sim-pipeline
# Install base dependenciesconda env create -f environment.yamlconda activate
# pytorch3d (dependency for diffusion) must be installed separately # due to bugs with downgrading torch to cpuconda install pytorch3d -c pytorch3d
# install sim-pipeline packagepip install -e .
cd ..
# install custom robosuite from sourcegit clone git@github.com:UWRobotLearning/robosuite.gitcd robosuitepip install -e .
# install custom robomimic from sourcegit clone git@github.com:UWRobotLearning/robomimic.gitcd robomimicpip install -e .
# install mimicgen_environmentsgit clone git@github.com:UWRobotLearning/mimicgen_environments.gitcd mimicgen_environmentspip install -e .```
### Datasets / Data Collection
Datasets used in paper can be downloaded here (pending).
Simulation data in robosuite can be collected using Spacemouse in the same manner as in robosuite. With the proper spacemouse vendor ID and product ID set in `robosuite/utils/macros.py`, run:
```python scripts/collect_human_demonstrations.py +env=<env_config>
# Then convert to the proper formatpython sim_pipeline/data_manager/convert_robosuite.py --dataset /path/to/collected/data
python scripts/dataset_states_to_obs.py --dataset /path/to/data --output_name <name> --camera_names agentview,robot0_eye_in_hand```
Envs can be found in `configs/envs`.
### Training and evaluation
Configs for each experiment can be found in `configs/training/_imitation_learning/_offline_rl/_experiments`. For custom datasets, replace `low_dim_keys` with the names of observation proprioception keys, and `rgb_keys` with the names of observation image keys in the config. To train, run
```python scripts/train_robomimic.py -cn iql_diffusion +training=<square/piece_assembly/threading/real_franka/...> data.dataset_path=<path_to_dataset>```
To evaluate policies in simulation, run:
```python scripts/eval.py -cn eval_robomimic_iql_diffusion exp.model_path=<path_to_checkpoint> +env=<env_config_to_eval_in>```
valid envs can be found in `configs/env`. Policies used in the paper can be downloaded here (pending).
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950name: ood_simchannels: - pytorch - nvidia - conda-forge - defaultsdependencies: - python==3.10.14 - cudatoolkit=11.8 - pytorch-cuda=11.8 - torchvision - cmake - pybind11 - py - pip - mesalib # neede for offline renderer on hyak # for diffusion - dill - einops - zarr - threadpoolctl=3.1.0 - av - diffusers - pip: - gymnasium - mujoco==3.0.0 - dm-robotics-moma - mujoco-python-viewer - hydra-core==1.3.2 - wandb - tensorboard - stable_baselines3[extra] - submitit - hydra-submitit-launcher - moviepy - imageio - tabulate - gym==0.26.2 - imagecodecs - gitpython - dvc[ssh] # stable contrastive jax stuff # - jax[cuda12] # - flax # - optax # - chex # - tensorflow # - tf-keras # - overrides # - ml_collections1234from sim_pipeline.data_collection.collect_human_demonstrations import collect
if __name__ == '__main__': collect()1234from sim_pipeline.data_manager.combine_datasets import combine_datasets_command
if __name__ == '__main__': combine_datasets_command()1234from sim_pipeline.data_manager.dataset_states_to_obs import main
if __name__ == "__main__": main()1234from sim_pipeline.eval.eval import eval
if __name__ == "__main__": eval()1234from sim_pipeline.data_manager.playback_dataset import playback_dataset
if __name__ == '__main__': playback_dataset()1234from sim_pipeline.training.train_robomimic import train
if __name__ == '__main__': train()12345678from setuptools import setup, find_packages
setup( name="sim_pipeline", version="0.1.0", packages=find_packages(),)
1234567891011121314151617181920212223242526272829303132333435import osimport warningsfrom pathlib import Path
warnings.filterwarnings('ignore', module='robosuite')warnings.filterwarnings('ignore', module='robomimic')
# required for running on hyak without dockerif not os.environ.get("MUJOCO_GL"): try: from robosuite.utils.binding_utils import MjRenderContextOffscreen except ImportError: os.environ["MUJOCO_GL"] = "osmesa" else: os.environ["MUJOCO_GL"] = "glfw" from sim_pipeline.configs.parse_config import parse_config
parse_config()
# print(f'Using renderer: {os.environ["MUJOCO_GL"]}')
from robosuite import macros
# if this is True, robosuite will try to use EGL rendering backend# regardless of MUJCO_GL which errors. This forces glfw if enabled# Can change this to True if EGL is supported.macros.MUJOCO_GPU_RENDERING = False
# get rid of robosuite warning after first importimport robosuiterobosuite_path = Path(robosuite.__file__).parent# make macros filemacros_path = robosuite_path / 'macros_private.py'macros_path.touch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647from dataclasses import dataclass, fieldfrom typing import Anyfrom sim_pipeline.configs.constants import IO_Devices, ROOT_DIR, DATA_DIRfrom sim_pipeline.configs.env.robomimic_base import RobomimicEnvConfigfrom sim_pipeline.configs.env.robomimic_square_ood import RobommimicSquareEnvOODConfig
@dataclassclass DataCollectionConfig: data_name: str = 'test' env: Any = RobomimicEnvConfig() device: IO_Devices = IO_Devices.SPACEMOUSE
pos_sensitivity: float = 1.0 rot_sensitivity: float = 1.0
directory: str = str(DATA_DIR)
print_rew: bool = False # if debug, don't save the data to avoid cluttering the # data directory with test runs debug: bool = False # for evaluating policies while controlling env manually model_path: str | None = None discriminator: bool = False eval_model: bool = False eval_value: bool = False n_obs_steps: int = 2 lowdim_keys: list[str] | None = field(default_factory=lambda: [ 'robot0_eef_pos', 'robot0_eef_quat', 'robot0_gripper_qpos', 'object-state', ]) rgb_keys: list[str] | None = field(default_factory=lambda: [ 'agentview_image', 'robot0_eye_in_hand_image' ]) record_image_embedding: bool = False use_dino_features: bool = False123456from dataclasses import dataclassfrom sim_pipeline.configs.data.base_data import BaseDataConfig
@dataclassclass DataSummaryConfig: data: BaseDataConfig = BaseDataConfig()1234567891011121314from dataclasses import dataclassimport sim_pipeline.configs.default as defaultfrom sim_pipeline.configs.env.base import BaseEnvConfigfrom sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfigfrom sim_pipeline.configs.training._diffusion.base_diffusion import DiffusionTrainingConfigfrom sim_pipeline.configs.exp.diffusion_train import DiffusionExpConfig
@dataclassclass DiffusionBaseConfig(default.TopLevelConfig): name: str = 'diffusion_square' env: BaseEnvConfig = RobomimicSquareEnvConfig() exp: DiffusionExpConfig = DiffusionExpConfig() training: DiffusionTrainingConfig = DiffusionTrainingConfig() 1234567891011121314from dataclasses import dataclassimport sim_pipeline.configs.default as defaultfrom sim_pipeline.configs.env.base import BaseEnvConfigfrom sim_pipeline.configs.env.robomimic_square_image import RobomimicSquareImageEnvConfigfrom sim_pipeline.configs.training._diffusion.diffusion_image import DiffusionImageTrainingConfigfrom sim_pipeline.configs.exp.diffusion_train import DiffusionExpConfig
@dataclassclass DiffusionImageConfig(default.TopLevelConfig): name: str = 'diffusion_image_square' env: BaseEnvConfig = RobomimicSquareImageEnvConfig() exp: DiffusionExpConfig = DiffusionExpConfig() training: DiffusionImageTrainingConfig = DiffusionImageTrainingConfig() 1234567891011121314from dataclasses import dataclassimport sim_pipeline.configs.default as defaultfrom sim_pipeline.configs.env.base import BaseEnvConfigfrom sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfigfrom sim_pipeline.configs.training._diffusion.tycho_diffusion import DiffusionTrainingConfigfrom sim_pipeline.configs.exp.diffusion_train import DiffusionExpConfig
@dataclassclass DiffusionBaseConfig(default.TopLevelConfig): name: str = 'diffusion_square' env: BaseEnvConfig = RobomimicSquareEnvConfig() exp: DiffusionExpConfig = DiffusionExpConfig() training: DiffusionTrainingConfig = DiffusionTrainingConfig() 123456789101112131415from dataclasses import dataclassimport sim_pipeline.configs.default as defaultfrom sim_pipeline.configs.env.base import BaseEnvConfigfrom sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfigfrom sim_pipeline.configs.training._imitation_learning.base_imitation import ImitationTrainingConfigfrom sim_pipeline.configs.training._imitation_learning.discriminator import DiscriminatorTrainingConfigfrom sim_pipeline.configs.exp.robomimic_train import RobomimicTrainExpConfigfrom sim_pipeline.configs.data.base_data import BaseDataConfig
@dataclassclass RobomimicDiscriminatorConfig(default.TopLevelConfig): name: str = 'discriminator_square' env: BaseEnvConfig = RobomimicSquareEnvConfig() exp: RobomimicTrainExpConfig = RobomimicTrainExpConfig() training: ImitationTrainingConfig = DiscriminatorTrainingConfig()12345678910from dataclasses import dataclassimport sim_pipeline.configs.default as default
from sim_pipeline.configs.env.robomimic_square_ood_pushing import RobommimicSquareEnvOODPushingConfigfrom sim_pipeline.configs.training._reinforcement_learning.robomimic_sac import SACTrainingConfig
@dataclassclass Config(default.TopLevelConfig): name: str = '' env: RobommimicSquareEnvOODPushingConfig = RobommimicSquareEnvOODPushingConfig()1234567891011121314from dataclasses import dataclassfrom sim_pipeline.configs._evaluation.eval_base import EvaluationConfigfrom sim_pipeline.configs.env.base import BaseEnvConfigfrom sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfigfrom sim_pipeline.configs.exp._eval._combined_individual.square_expert_diffusion_lowdim import DiffusionEvalExpConfigfrom sim_pipeline.configs.exp._eval.evaluation import EvalExpConfigfrom sim_pipeline.configs.training._diffusion.base_diffusion import DiffusionTrainingConfig
@dataclassclass RobomimicEvalConfig(EvaluationConfig): name: str ='diffusion_hook_expert' env: BaseEnvConfig = RobomimicSquareEnvConfig() exp: EvalExpConfig = DiffusionEvalExpConfig() training: DiffusionTrainingConfig = DiffusionTrainingConfig()1234567891011121314from dataclasses import dataclassfrom sim_pipeline.configs._evaluation.eval_base import EvaluationConfigfrom sim_pipeline.configs.env.base import BaseEnvConfigfrom sim_pipeline.configs.env.robomimic_square_ood import RobommimicSquareEnvOODConfigfrom sim_pipeline.configs.exp._eval._combined_individual.pushing_expert_diffusion_lowdim import DiffusionEvalExpConfigfrom sim_pipeline.configs.exp._eval.evaluation import EvalExpConfigfrom sim_pipeline.configs.training._diffusion.base_diffusion_rohan import DiffusionTrainingRohanConfig
@dataclassclass RobomimicEvalConfig(EvaluationConfig): name: str ='diffusion_combined_lowdim_rohan' env: BaseEnvConfig = RobommimicSquareEnvOODConfig() exp: EvalExpConfig = DiffusionEvalExpConfig() training: DiffusionTrainingRohanConfig = DiffusionTrainingRohanConfig()README.md+1-1
code_src/df_rise/_deps/PROVENANCE.txtAdded+22
code_src/df_rise/_deps/rotary_embedding_torch/__init__.pyAdded+6
code_src/df_rise/_deps/rotary_embedding_torch/flash_attn_with_rotary.pyAdded+597
code_src/df_rise/_deps/rotary_embedding_torch/flash_fused_rotary.pyAdded+529
code_src/df_rise/_deps/rotary_embedding_torch/rotary_embedding_torch.pyAdded+350
code_src/df_rise/df_actprobe.pyAdded+132
code_src/df_rise/df_core.pyAdded+242
code_src/df_rise/df_data.pyAdded+145
code_src/df_rise/df_fidmean.pyAdded+118
code_src/df_rise/df_guid_l2.pyAdded+112
code_src/df_rise/df_idm.pyAdded+457
code_src/df_rise/df_idm_probe.pyAdded+231
code_src/df_rise/df_plan.pyAdded+200
code_src/df_rise/df_policy.pyAdded+432
code_src/df_rise/df_poolcmp.pyAdded+156
code_src/df_rise/df_poolcmp2.pyAdded+464
code_src/df_rise/df_probe.pyAdded+164
code_src/df_rise/df_value.pyAdded+241
code_src/df_rise/smoke_df_plan.pyAdded+195
code_src/df_rise/train_df.pyAdded+325
code_src/ifql/impls/__init__.pyAdded
code_src/ifql/impls/agents/__init__.pyAdded
code_src/ifql/impls/agents/ifql.pyAdded+285
code_src/ifql/impls/utils/__init__.pyAdded
code_src/ifql/impls/utils/encoders.pyAdded+108
code_src/ifql/impls/utils/flax_utils.pyAdded+337
code_src/ifql/impls/utils/loss_utils.pyAdded+56
code_src/ifql/impls/utils/networks.pyAdded+378
code_src/ifql/train_ifql.pyAdded+395
code_src/rise_code/README.mdAdded+84
code_src/rise_code/environment.yamlAdded+50
code_src/rise_code/scripts/collect_human_demonstrations.pyAdded+4
code_src/rise_code/scripts/combine_datasets.pyAdded+4
code_src/rise_code/scripts/dataset_states_to_obs.pyAdded+4
code_src/rise_code/scripts/eval.pyAdded+4
code_src/rise_code/scripts/playback_dataset.pyAdded+4
code_src/rise_code/scripts/train_robomimic.pyAdded+4
code_src/rise_code/setup.pyAdded+8
code_src/rise_code/sim_pipeline/__init__.pyAdded+35
code_src/rise_code/sim_pipeline/configs/__init__.pyAdded
code_src/rise_code/sim_pipeline/configs/_data_collection/data_collection.pyAdded+47
code_src/rise_code/sim_pipeline/configs/_data_summary/data_summary.pyAdded+6
code_src/rise_code/sim_pipeline/configs/_diffusion/base_diffusion.pyAdded+14
code_src/rise_code/sim_pipeline/configs/_diffusion/diffusion_image.pyAdded+14
code_src/rise_code/sim_pipeline/configs/_diffusion/tycho_diffusion.pyAdded+14
code_src/rise_code/sim_pipeline/configs/_discriminator/robomimic_discriminator.pyAdded+15
code_src/rise_code/sim_pipeline/configs/_env_configs/ood_pushing.pyAdded+10
code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/hook_expert_lowdim.pyAdded+14
code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/pushing_expert_lowdim.pyAdded+14