diff --git a/README.md b/README.md index c3fa3c7d1a271f982fb613a0abff855011375cd7..8f424cd750dbb11c3e8cb9354587dd569180f152 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ the pipeline, training/eval launchers and the paper tables' source docs. Snapsh | 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) | +| `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) | diff --git a/code_src/df_rise/_deps/PROVENANCE.txt b/code_src/df_rise/_deps/PROVENANCE.txt new file mode 100644 index 0000000000000000000000000000000000000000..16d3c01e3a3de09f11e0e987255d34b7ba00bc80 --- /dev/null +++ b/code_src/df_rise/_deps/PROVENANCE.txt @@ -0,0 +1,22 @@ +gen_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 killed +every 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 and +venv_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 transformer +backbone); the import is merely on the module path. Supplying the real package rather than stubbing +it keeps the vendored checkout honest -- if upstream code ever does reach RotaryEmbedding, it gets +the real implementation. +copied 2026-09-23, source venv_df (pip install rotary_embedding_torch==0.9.1). diff --git a/code_src/df_rise/_deps/rotary_embedding_torch/__init__.py b/code_src/df_rise/_deps/rotary_embedding_torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fa7caab938e3832a8362daa2f114451297fdfdff --- /dev/null +++ b/code_src/df_rise/_deps/rotary_embedding_torch/__init__.py @@ -0,0 +1,6 @@ +from rotary_embedding_torch.rotary_embedding_torch import ( + apply_rotary_emb, + RotaryEmbedding, + apply_learned_rotations, + broadcat +) diff --git a/code_src/df_rise/_deps/rotary_embedding_torch/flash_attn_with_rotary.py b/code_src/df_rise/_deps/rotary_embedding_torch/flash_attn_with_rotary.py new file mode 100644 index 0000000000000000000000000000000000000000..c87d6fa9bbc43b660a6aafebabbb0a6882d46782 --- /dev/null +++ b/code_src/df_rise/_deps/rotary_embedding_torch/flash_attn_with_rotary.py @@ -0,0 +1,597 @@ +import math +import torch +from torch import cat +from torch import Tensor +from einops import rearrange, repeat + +try: + import triton + import triton.language as tl + TRITON_AVAILABLE = True +except 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) diff --git a/code_src/df_rise/_deps/rotary_embedding_torch/flash_fused_rotary.py b/code_src/df_rise/_deps/rotary_embedding_torch/flash_fused_rotary.py new file mode 100644 index 0000000000000000000000000000000000000000..804d8ecca1160ac74766f3928c8097c7f3b47879 --- /dev/null +++ b/code_src/df_rise/_deps/rotary_embedding_torch/flash_fused_rotary.py @@ -0,0 +1,529 @@ +import math +import torch +from torch import Tensor +from einops import rearrange, repeat + +try: + import triton + import triton.language as tl + TRITON_AVAILABLE = True +except 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) diff --git a/code_src/df_rise/_deps/rotary_embedding_torch/rotary_embedding_torch.py b/code_src/df_rise/_deps/rotary_embedding_torch/rotary_embedding_torch.py new file mode 100644 index 0000000000000000000000000000000000000000..4b5428d0baa5a93300eae117396d2fea991f680e --- /dev/null +++ b/code_src/df_rise/_deps/rotary_embedding_torch/rotary_embedding_torch.py @@ -0,0 +1,350 @@ +from __future__ import annotations +from math import pi, log + +import torch +from torch.amp import autocast +from torch.nn import Module, ModuleList +from 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 freqs diff --git a/code_src/df_rise/df_actprobe.py b/code_src/df_rise/df_actprobe.py new file mode 100644 index 0000000000000000000000000000000000000000..f7c9c705802362de70afd0cdde81159c29d08feb --- /dev/null +++ b/code_src/df_rise/df_actprobe.py @@ -0,0 +1,132 @@ +"""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 action +distribution 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, on +held-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 from +act_absmax/act_clip_frac (a shifted expert action is still in the box), which is why it needs its own +measurement. +""" +from __future__ import annotations +import argparse, json, os, sys +import numpy as np +import torch + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from df_data import DFCacheData, OBS_DIM, ACT_DIM # noqa: E402 +from df_probe import load_df # noqa: E402 +from 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() diff --git a/code_src/df_rise/df_core.py b/code_src/df_rise/df_core.py new file mode 100644 index 0000000000000000000000000000000000000000..3c85212031d455f72b253a9ad9e284048abed680 --- /dev/null +++ b/code_src/df_rise/df_core.py @@ -0,0 +1,242 @@ +"""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 independent +per-token noise levels and pyramid scheduling matrix copied from upstream's `df_base.py`, and a +planner 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 guidance +branches. 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 goal +observation is privileged information no other column in tab:flagship receives (the project already +ruled the env-replay goal classifier "privileged goal labels", LAUNCH_MATRIX 2026-09-18 13:05). So +the reward branch is the only fair one, and we implement it from the recipe upstream left in the dead +code 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 publish +must carry this sentence. +""" +from __future__ import annotations + +import os +import sys + +import numpy as np +import torch +import 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) diff --git a/code_src/df_rise/df_data.py b/code_src/df_rise/df_data.py new file mode 100644 index 0000000000000000000000000000000000000000..7941244a8ed4cb3b4f25ecaea713992b7e443194 --- /dev/null +++ b/code_src/df_rise/df_data.py @@ -0,0 +1,145 @@ +"""Diffusion Forcing corpus adapter (gen_q#274). + +CORPUS. The SAME DINOv2 cache every other scorer in tab:flagship reads -- `cache/`: + 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//tokens); +Diffusion Forcing here trains on the POOLED 1545-d form, which is the same frames, the same episodes +and 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-specific +normalisation 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 every +frame of an expert episode -- i.e. exactly what `train_rsm.py --reward-mode dense` feeds the +membership 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 the +episodes 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 at +the tail with the episode's last frame, with a `mask` marking the padded frames so the loss and the +fidelity metric ignore them. +""" +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import torch + +OBS_DIM, ACT_DIM, REW_DIM = 1545, 7, 1 +BUNDLE_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) diff --git a/code_src/df_rise/df_fidmean.py b/code_src/df_rise/df_fidmean.py new file mode 100644 index 0000000000000000000000000000000000000000..62f5f6c70d41e5642ffd5f301accdabd3b93a3b6 --- /dev/null +++ b/code_src/df_rise/df_fidmean.py @@ -0,0 +1,118 @@ +"""IS THE WORLD MODEL ACTUALLY BAD, OR IS `fid/obs_ratio_h1` MEASURING SAMPLING NOISE? + +`train_df.fidelity` (train_df.py:85) draws **one** diffusion sample, `n_plans=1`, and compares its +RMSE against the truth to a **deterministic** stay-put control. That comparison is structurally +biased against any stochastic predictor: for a PERFECTLY CALIBRATED sampler whose posterior equals +the truth's, + E||x_sample - x_true||^2 = ||E[x] - x_true||^2 + Var(x_sample) = 2 * Var, +while the best deterministic predictor scores only `Var`. So a flawless generative model plateaus at +ratio sqrt(2) = 1.414 against a stay-put control of the same quality -- and threading plateaus at 1.51. + +This script separates the two terms. For K in {1,2,4,8,16,64} it averages K independent samples from +the SAME conditioning state and re-measures the RMSE, giving + + mse(K) = bias2 + var/K (the Monte-Carlo law) + +so a straight line in 1/K reads off `bias2` (the model's real error, K -> inf) and `var` (the sampling +noise the old metric was charging to the model). Reported per horizon: + + ratio_K1 the old number, for continuity + ratio_Kmax the posterior-mean estimate against the same stay-put control + ratio_inf the 1/K -> 0 extrapolation, i.e. the model's dynamics error with sampling noise removed + var_frac var / mse(1), the fraction of the old metric that was sampling noise + +If ratio_inf < 1 the model DOES beat stay-put and "the world model has no short-horizon dynamics" +(FINDING A/B's premise) is an artifact of the instrument. If ratio_inf >= 1 the model is genuinely +worse than standing still and the diagnosis stands. Either way the number is decisive, and it costs +one GPU-minute rather than a 100k-step training run. +""" +from __future__ import annotations +import argparse, json, os, sys +import numpy as np +import torch + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from df_data import DFCacheData, OBS_DIM # noqa: E402 +from df_probe import load_df # noqa: E402 +from df_plan import plan_bundles # noqa: E402 +from train_df import split_window # noqa: E402 (one definition of the window layout) + + +@torch.no_grad() +def main(): + p = argparse.ArgumentParser() + p.add_argument("--ckpt", required=True) + p.add_argument("--cache", required=True) + p.add_argument("--out", required=True) + p.add_argument("--n-states", type=int, default=64) + p.add_argument("--kmax", type=int, default=64) + p.add_argument("--seed", type=int, default=0) + a = p.parse_args() + dev = "cuda" if torch.cuda.is_available() else "cpu" + model, meta, step = load_df(a.ckpt, dev) + data = DFCacheData(a.cache, frame_stack=int(meta["frame_stack"]), + n_tokens=int(meta["n_tokens"]), seed=int(meta.get("seed", 0))) + rng = np.random.default_rng(a.seed) + # The window layout is the checkpoint's own, read out of its meta, so a --cond-history model is + # measured through the conditioning it was trained with and a default model is bit-identical to + # every number already in status/nb/df_fidmean/. + align = str(meta.get("act_align", "ours")) + cond_history = int(meta.get("cond_history", 0)) + bundle, mask = data.sample(a.n_states, rng, split="val", device=dev) + cond_obs, body, m = split_window(bundle, mask, int(meta["frame_stack"]), align, cond_history) + T = body.shape[0] + init_obs = cond_obs if cond_obs.dim() == 2 else cond_obs[:, -1] # stay-put control + true_obs = body[:, :, :OBS_DIM] # [T, B, C] + + # one draw of KMAX samples per state; every K is a prefix of it, so all K share the same draws + plan = plan_bundles(model, cond_obs, horizon_frames=T, guidance_scale=0.0, gamma=0.0, + n_plans=a.kmax, device=dev)["plan"][..., :OBS_DIM] # [T, B, K, C] + Ks = [k for k in (1, 2, 4, 8, 16, 64) if k <= a.kmax] + horizons = [1, 2, 4, 8, 10, 20, 50] + res = dict(ckpt=a.ckpt, cache=a.cache, step=step, n_states=int(a.n_states), kmax=a.kmax, + frame_stack=int(meta["frame_stack"]), chan_share=meta.get("chan_share", ""), + act_align=align, cond_history=cond_history, + beta_schedule=str(meta.get("beta_schedule", "linear")), + objective=str(meta.get("objective", "pred_x0")), + n_tokens=int(meta.get("n_tokens", -1)), seed=int(meta.get("seed", 0)), + train_steps=int(meta.get("steps", -1)), Ks=Ks, per_h={}) + + for H in horizons: + h = min(H, T) - 1 + if h < 0 or m[h].sum() == 0: + continue + w = m[h].bool() + tgt = true_obs[h][w] # [b, C] + naive = ((init_obs[w] - tgt) ** 2).mean(-1).mean().item() # MSE, stay-put + row = {"naive_mse": naive, "naive_rmse": naive ** 0.5, "mse": {}, "rmse": {}, "ratio": {}} + for K in Ks: + pm = plan[h][w][:, :K, :].mean(1) # posterior-mean estimate over K draws + mse = ((pm - tgt) ** 2).mean(-1).mean().item() + row["mse"][str(K)] = mse + row["rmse"][str(K)] = mse ** 0.5 + row["ratio"][str(K)] = (mse ** 0.5) / max(naive ** 0.5, 1e-8) + # mse(K) = bias2 + var/K -> least squares in x = 1/K + x = np.array([1.0 / K for K in Ks]); y = np.array([row["mse"][str(K)] for K in Ks]) + A = np.stack([np.ones_like(x), x], 1) + bias2, var = np.linalg.lstsq(A, y, rcond=None)[0] + bias2 = float(max(bias2, 0.0)); var = float(max(var, 0.0)) + row["bias2"] = bias2 + row["var"] = var + row["ratio_inf"] = (bias2 ** 0.5) / max(naive ** 0.5, 1e-8) + row["var_frac"] = var / max(row["mse"]["1"], 1e-12) + # the sqrt(2) prediction: a calibrated sampler with bias2 == naive would sit here + row["fit_resid"] = float(np.abs(A @ np.array([bias2, var]) - y).max()) + res["per_h"][str(H)] = row + + os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True) + with open(a.out, "w") as f: + json.dump(res, f, indent=1) + for H, r in res["per_h"].items(): + print(f"h{H:>3s} naive {r['naive_rmse']:.4f} | ratio K=1 {r['ratio']['1']:.3f} " + f"K={Ks[-1]} {r['ratio'][str(Ks[-1])]:.3f} inf {r['ratio_inf']:.3f} " + f"| var_frac {r['var_frac']:.3f} resid {r['fit_resid']:.2e}") + print("[df_fidmean] wrote", a.out) + + +if __name__ == "__main__": + main() diff --git a/code_src/df_rise/df_guid_l2.py b/code_src/df_rise/df_guid_l2.py new file mode 100644 index 0000000000000000000000000000000000000000..4cd09648e47b99d1bda2455757d0c7e2156ed908 --- /dev/null +++ b/code_src/df_rise/df_guid_l2.py @@ -0,0 +1,112 @@ +"""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 0 +and at guidance 5 from the same seed. If it is ~0, the parameter is inert and the sweep was +measuring 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 one +alone. `plan_bundles` draws fresh diffusion noise per call, so two calls differ even at the SAME +guidance; a large cross-guidance L2 would prove nothing unless it is large COMPARED TO that. So +every 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 split +of the same cache the column trains on, uses DF's own predicted binary-provenance reward channel +for J, and never touches a simulator, a success bit, or an RSM/IQL critic (rules 1, 2, 7). +""" +import argparse +import json +import os +import sys + +import numpy as np +import torch + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from df_data import DFCacheData, OBS_DIM # noqa: E402 +from df_probe import load_df # noqa: E402 +from df_plan import plan_bundles # noqa: E402 + + +@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() diff --git a/code_src/df_rise/df_idm.py b/code_src/df_rise/df_idm.py new file mode 100644 index 0000000000000000000000000000000000000000..a40778e3652809a831aa237bb2b7e44cec930e08 --- /dev/null +++ b/code_src/df_rise/df_idm.py @@ -0,0 +1,457 @@ +#!/usr/bin/env python +"""INVERSE DYNAMICS MODEL -- the honest, learned analogue of upstream DF's hand-written maze2d +controller (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, the +commit 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 POSITIONS +ONLY, 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 normalised +and the paper's own "Diffuser w/ diffused action" floor is 13.5 +- 2.3. Upstream says it in their +own words in a COMMENTED-OUT README block (line 86): *"Here is also ckpt where we take diffused +actions ... 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, so +the 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 then +plans in the channel our health numbers say is HEALTHY (observations) and the IDM decodes it. That +is 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/` -- the SAME cache, the SAME frozen +DINOv2 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 simulator +state, no goal, no success bit, no reward of any kind, no privileged anything. +SUPERVISION: `cache//act.f32.npy`, the OSC action the dataset actually executed -- which is +the identical supervision every BC column is trained on. +SPLIT: `DFCacheData(seed=)`, i.e. the SAME held-out episodes every other DF +diagnostic (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//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 than +stay-put. A `k1` IDM consumes exactly that delta, so it is being fed the noisiest thing DF +produces. The horizons where DF's observation channel is at or below 1.0 are h>=8. So the shape +that matches where the world model is actually healthy is a CHUNKED IDM that reads a planned +WAYPOINT and emits the whole 8-action chunk -- which is also precisely the cadence the harness +executes (`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 planned +observations. 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 success +rate, 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.0x +the size of the true delta at h=8 (table above). Training on clean pairs alone builds a decoder +that has never seen an input as bad as the one it will get. So the non-anchor frames are corrupted +with per-dimension Gaussian noise of std `noise_rel * std(o_{t+k} - o_t)`; `noise_rel=1.0` matches +the measured ratio. This is standard input augmentation on the model's OWN inputs -- it adds no +information 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 successive +first differences -- because the action is a function of the MOTION and the deltas are ~100x smaller +than the state. Targets are standardised by the dataset's own per-channel action std so the 7 OSC +channels (6 continuous + 1 near-binary gripper) contribute comparably to the loss; predictions are +un-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 the +IDM's actions decoded from DF's OWN PLANNED latents, on the same held-out states, at the same plan +indices, K-sample mean -- against DF's own action head measured on those identical states in the +same 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 baseline +already on record (status/nb/df_table.txt:9,90 -- threading 0.000, mug 0.027). A scorer that ties +across most candidates IS random-of-N however good its headline. + +usage: + python df_idm.py --cache cache/ --out runs//idm/ --mode k8 --noise-rel 1.0 +""" +from __future__ import annotations + +import argparse +import json +import os +import sys +import time +from pathlib import Path + +import numpy as np +import torch +import 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 + + +# --------------------------------------------------------------------------- data +class 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 / decode +def load_idm(d, device="cuda"): + """/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() + + +# --------------------------------------------------------------------------- metric +def 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 + + +# --------------------------------------------------------------------------- train +def 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/ ONLY; " + "supervision = cache//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() diff --git a/code_src/df_rise/df_idm_probe.py b/code_src/df_rise/df_idm_probe.py new file mode 100644 index 0000000000000000000000000000000000000000..c44b3d87b2897ce52c0d003e4faa98ca0ad31b31 --- /dev/null +++ b/code_src/df_rise/df_idm_probe.py @@ -0,0 +1,231 @@ +#!/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 any +candidate (rule 7). No goal guidance. Guidance scale is swept over the same {0, 5} the rest of the +stream uses; nothing privileged is added at any scale. + +usage: + python df_idm_probe.py --ckpt runs//wm/df_G0/ckpt_s40000.pt --cache cache/ \ + --idm-dir runs//idm/k1_n0 --idm-dir runs//idm/k8_n1 ... \ + --out status/nb/df_idm/_probe.json +""" +from __future__ import annotations + +import argparse +import json +import os +import sys +from pathlib import Path + +import numpy as np +import torch + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from df_data import DFCacheData, OBS_DIM, ACT_DIM # noqa: E402 +from df_probe import load_df # noqa: E402 +from df_plan import plan_bundles # noqa: E402 +from 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() diff --git a/code_src/df_rise/df_plan.py b/code_src/df_rise/df_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..227384a2e6216098adeddd29bf6389d1aac94708 --- /dev/null +++ b/code_src/df_rise/df_plan.py @@ -0,0 +1,200 @@ +"""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 same +conditioning token, the same `diffusion_model.sample_step(..., guidance_fn=...)` -- with ONE +substitution, 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 no +other column in tab:flagship receives, so a goal-guided DF would not be a fair baseline; and +upstream'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 the +recipe we implement: a reconstruction weight on the conditioning frames, a geometric weight over the +plan 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 outside +the 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 conditioning +observation and the executed one is argmax_J. This is NOT the shared 128-candidate set the value +columns rank -- DF proposes its own actions, which is what "run it as a planner" means -- so the +number is disclosed with every score, per #274 ("never compare a 16-candidate planner to a +128-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 a +cell 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 units +as DFCacheData's `ep_success`, which is BINARY and lives in {0, 1}. Nothing in the diffusion or in +the guidance constrains r_hat to that interval, so ascending J can be solved by pushing r_hat ABOVE +the 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 landed +number. `r_max=1.0` replaces r_hat by min(r_hat, 1.0) EVERYWHERE the objective is evaluated: in the +J 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 saturated +region is exactly ZERO, which is the whole point: once a frame's predicted provenance has reached the +label maximum, guidance stops pushing on it. +FAIRNESS: 1.0 is the maximum of the binary data-provenance label itself, which is 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 is involved. Only the DEFINITION of the shared reward is used. +""" +from __future__ import annotations + +import numpy as np +import 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], sel diff --git a/code_src/df_rise/df_policy.py b/code_src/df_rise/df_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..073ef658c415e99beff09d609b4679e8ac9f6d93 --- /dev/null +++ b/code_src/df_rise/df_policy.py @@ -0,0 +1,432 @@ +"""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", and +a planner proposes its OWN actions. So DF cannot enter through `rsm_backend`; it replaces the action +instead of ranking someone else's. That is also why its candidate count is reported separately and +never 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; it +must 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` against `fid/obs_rmse_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 json +import os +import sys +from pathlib import Path + +import numpy as np +import torch + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from df_core import DFRise # noqa: E402 +from df_data import OBS_DIM, ACT_DIM # noqa: E402 +from 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/'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=") + 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 ".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 df diff --git a/code_src/df_rise/df_poolcmp.py b/code_src/df_rise/df_poolcmp.py new file mode 100644 index 0000000000000000000000000000000000000000..269cfd669f84ef9020c8af715017a1ed53af955f --- /dev/null +++ b/code_src/df_rise/df_poolcmp.py @@ -0,0 +1,156 @@ +"""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 50 +episodes x 2 seeds x 2 tasks. Three decoding rules that differ only in WHICH of the same 128 +candidates 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 draws +one pool per state exactly as df_policy does (same plan_bundles, same guidance, same gamma) and +scores 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 is +never 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 annotations +import argparse, json, os, sys +import numpy as np +import torch + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from df_data import DFCacheData, OBS_DIM, ACT_DIM # noqa: E402 +from df_probe import load_df # noqa: E402 +from 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() diff --git a/code_src/df_rise/df_poolcmp2.py b/code_src/df_rise/df_poolcmp2.py new file mode 100644 index 0000000000000000000000000000000000000000..c69f5c747cb3dd041d9f50fc05acc3f26a99e951 --- /dev/null +++ b/code_src/df_rise/df_poolcmp2.py @@ -0,0 +1,464 @@ +"""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.40 +on 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 at +random). This file asks the three follow-ups, on the SAME held-out machinery: no environment, no +rollout, no success number, and the expert action is used ONLY to compute the error that the rank +diagnostics are scored against and the r2_oracle upper bound. Nothing from RSM/IQL touches DF's +candidates (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 annotations +import argparse, json, math, os, sys +import numpy as np +import torch + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +OBS_DIM, ACT_DIM = 1545, 7 +A0, A1 = OBS_DIM, OBS_DIM + ACT_DIM + + +# ---------------------------------------------------------------- rank helpers +def _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 scoring +def 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 test +def 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()) diff --git a/code_src/df_rise/df_probe.py b/code_src/df_rise/df_probe.py new file mode 100644 index 0000000000000000000000000000000000000000..4e6169071cabf056aa33ea12dac4e5377ca16daa --- /dev/null +++ b/code_src/df_rise/df_probe.py @@ -0,0 +1,164 @@ +"""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 annotations +import argparse, json, os, sys +from pathlib import Path +import numpy as np +import torch + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from df_data import DFCacheData, OBS_DIM, ACT_DIM, BUNDLE_DIM # noqa: E402 +from df_core import DFRise # noqa: E402 +from 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() diff --git a/code_src/df_rise/df_value.py b/code_src/df_rise/df_value.py new file mode 100644 index 0000000000000000000000000000000000000000..cd27c3c6ff18a021cf64f200face6a2f58679c0c --- /dev/null +++ b/code_src/df_rise/df_value.py @@ -0,0 +1,241 @@ +"""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 action +channels and steers them with a guidance gradient on the predicted reward. This file runs the same +model as a VALUE FUNCTION over somebody ELSE's candidate actions -- the shape every other column in +tab: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 scheduling +matrix (`model.scheduling`), same conditioning token construction, same +`model.diffusion_model.sample_step(plan, None, frm, to, guidance_fn=...)` call -- so a difference +between 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's +z-scoring is applied by `model.norm` to the WHOLE bundle inside this file (see `_act_z`). The D1 +assertion is what proves this end to end: it un-normalises what the sampler actually held and +compares 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 per +call before chunking, so chunking cannot change a single returned number. +""" +from __future__ import annotations + +import numpy as np +import 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") diff --git a/code_src/df_rise/smoke_df_plan.py b/code_src/df_rise/smoke_df_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..82a5ae480302d6c6e78391a1db102e5ff887091c --- /dev/null +++ b/code_src/df_rise/smoke_df_plan.py @@ -0,0 +1,195 @@ +"""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 DF +column 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 plausible +success rate; a wrong weight vector would guide on the conditioning frames only; a padding bug would +guide 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, math +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import numpy as np +import torch + +from df_data import OBS_DIM, ACT_DIM, BUNDLE_DIM +from df_core import DFRise, default_cfg +from 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 weights +FS, GAMMA = 4, 0.9 +w = _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 around +w2 = _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 model +cfg = 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 exercised +mean[-1], std[-1] = 0.25, 0.5 # reward channel gets its own scale +model = 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, 6 +obs = 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 shapes +o0 = 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 determinism +a = 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 real +o = 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_actions +acts, 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 fs +o7 = run(3.0, seed=2, horizon=7) # 7 frames, frame_stack 4 -> 2 tokens, 1 pad frame +check("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, GAMMA +pol.n_plans, pol.execute_frames = NP, 3 +pol.step, pol.diag_path, pol.act_limit = 12345, "", 1.0 +pol.gen = torch.Generator(device="cpu"); pol.gen.manual_seed(0) +pol.enc = lambda obs_t: obs_t["state"] # stand in for PooledDinoState +pol.reset() + +class _FakeObs(dict): + pass +ob = {"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 path +pol.enc = lambda obs_t: obs +a1 = 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) diff --git a/code_src/df_rise/train_df.py b/code_src/df_rise/train_df.py new file mode 100644 index 0000000000000000000000000000000000000000..b410461b63a4e8de2a17e781255ee1aa3427c04a --- /dev/null +++ b/code_src/df_rise/train_df.py @@ -0,0 +1,325 @@ +#!/usr/bin/env python +"""Train Diffusion Forcing on an rsm_rise task corpus (gen_q#274). + + python train_df.py --cache cache/ --out runs//wm/df [--steps 100000] ... + +Same corpus, same state definition, same split and the same binary provenance reward every other +column 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 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_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, time +from pathlib import Path + +import numpy as np +import torch + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from df_data import DFCacheData, OBS_DIM, ACT_DIM, BUNDLE_DIM # noqa: E402 +from 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() diff --git a/code_src/ifql/impls/__init__.py b/code_src/ifql/impls/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code_src/ifql/impls/agents/__init__.py b/code_src/ifql/impls/agents/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code_src/ifql/impls/agents/ifql.py b/code_src/ifql/impls/agents/ifql.py new file mode 100644 index 0000000000000000000000000000000000000000..69d9501faafe0c74377e06f3adaa8fff6915bf4f --- /dev/null +++ b/code_src/ifql/impls/agents/ifql.py @@ -0,0 +1,285 @@ +import copy +from typing import Any + +import flax +import jax +import jax.numpy as jnp +import ml_collections +import optax + +from utils.encoders import encoder_modules +from utils.flax_utils import ModuleDict, TrainState, nonpytree_field +from utils.loss_utils import hl_gauss_cross_entropy, hl_gauss_from_logits, sample_beta_times +from 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 config diff --git a/code_src/ifql/impls/utils/__init__.py b/code_src/ifql/impls/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code_src/ifql/impls/utils/encoders.py b/code_src/ifql/impls/utils/encoders.py new file mode 100644 index 0000000000000000000000000000000000000000..addc56a9e15d426ead7d93d81916dbf8d9ea35cc --- /dev/null +++ b/code_src/ifql/impls/utils/encoders.py @@ -0,0 +1,108 @@ +import functools +from typing import Sequence + +import flax.linen as nn +import 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,)), +} diff --git a/code_src/ifql/impls/utils/flax_utils.py b/code_src/ifql/impls/utils/flax_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e2ee66a782450284101212e217ffe2e19fe280da --- /dev/null +++ b/code_src/ifql/impls/utils/flax_utils.py @@ -0,0 +1,337 @@ +import functools +import gc +import glob +import json +import os +import pickle +import time +from typing import Any, Dict, Mapping, Sequence + +import flax +import flax.linen as nn +import jax +import jax.numpy as jnp +import numpy as np +import 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=` 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_.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_.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) diff --git a/code_src/ifql/impls/utils/loss_utils.py b/code_src/ifql/impls/utils/loss_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f2805b955189e9df01de36454d2fa39347f32b74 --- /dev/null +++ b/code_src/ifql/impls/utils/loss_utils.py @@ -0,0 +1,56 @@ +import jax +import jax.numpy as jnp +import jax.scipy.special + + +HL_GAUSS_MIN_VALUE = 0.0 +HL_GAUSS_MAX_VALUE = 1.0 +HL_GAUSS_NUM_BINS = 101 +HL_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) diff --git a/code_src/ifql/impls/utils/networks.py b/code_src/ifql/impls/utils/networks.py new file mode 100644 index 0000000000000000000000000000000000000000..43debf8748d26bf8b1ec2381d75fb0b1870d2354 --- /dev/null +++ b/code_src/ifql/impls/utils/networks.py @@ -0,0 +1,378 @@ +from 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 distrax +except ModuleNotFoundError: # pragma: no cover + distrax = None +import flax.linen as nn +import 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 v diff --git a/code_src/ifql/train_ifql.py b/code_src/ifql/train_ifql.py new file mode 100644 index 0000000000000000000000000000000000000000..ed017cad352307dc9dac33ac3efb103eae65aa98 --- /dev/null +++ b/code_src/ifql/train_ifql.py @@ -0,0 +1,395 @@ +#!/usr/bin/env python +"""IFQL (implicit flow Q-learning) on an rsm_rise RISE task -- gen_q#264, the flagship baseline. + +IFQL is the flow variant of IDQL: a flow-matching BC actor (unweighted) plus an IQL expectile critic with +an HL-Gauss two-hot value head; at action time it draws `num_samples` noises, integrates the flow with +`flow_steps` Euler steps and takes the arg-max Q. The agent itself is the VERBATIM ogbench_plus +implementation, vendored under impls/ (`impls/agents/ifql.py`, md5 a6152bff6837e24f2bf63fef36fbb0b6 == +the upstream file); nothing in this script changes its losses, its network shapes or its defaults. What +this script supplies is the rsm_rise data loader, the fairness constants and the export. + +OBSERVATION (primary variant, `--obs dino`): the pooled frozen-DINOv2 state of the CURRENT frame -- +[agentview CLS|GeM (768) | wrist CLS|GeM (768) | eef_pos(3) eef_quat(4) gripper_qpos(2)] = 1545 -- z-scored +with the Stage-1 cache's feat_stats.npz, i.e. the EXACT input our successor scorer sees +(cache//{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//act.f32.npy), single step, exactly as +published -- the flow actor is a per-step actor, not a chunked one. + +REWARD (fairness rule, same as every other column of the flagship table): the binary data-provenance +label, 1 on every frame of an episode that came from the expert file and 0 on every frame of a +suboptimal/play episode. It is read from the source HDF5's `rewards` (constant within an episode; the +script asserts that) and cross-checked against the cache's own ep_success. + +VALUE SCALE. IFQL's value head is HL-Gauss over the FIXED support [0, 1] (impls/utils/loss_utils.py: +HL_GAUSS_MIN_VALUE=0, HL_GAUSS_MAX_VALUE=1), because upstream rewards are sparse-at-goal so that +V in [0,1]. Our provenance reward is DENSE (1 on every expert frame), so the raw n-step return +sum_{k<200} gamma^k r is ~200 and every expert state would clip to the top bin -- a constant critic with +no ranking at all. The reward is therefore multiplied by (1 - discount) (`--reward-scale auto`), which is +a strictly monotone rescaling of the identical reward signal: the fixed point becomes +V = (1-gamma) * E[sum gamma^k r] in [0, 1], i.e. the discounted AVERAGE provenance label = "how expert-like +does the future from here look", the same quantity the RSM membership head estimates. Rankings are +unchanged by the rescale, so the fairness rule ("same reward as every other method") is preserved; only +the axis the two-hot head has to represent changes. `--reward-scale 1.0` restores the raw sum for a +control. + +n-STEP RETURNS: computed inside each episode exactly as impls/utils/datasets.Dataset.get_n_step_returns +(stop at the episode's last frame, bootstrap from the frame `steps-1` ahead). + +TERMINAL CONVENTION (`--terminal`, default `truncate`): a demonstration ends because the demonstration +ends, not because the MDP reached an absorbing state, so the last transition is TRUNCATED and keeps +masks = 1, bootstrapping off the final observation -- the standard convention, and the one ogbench uses +for its own non-goal-reaching trajectories. That is also what makes the value usable here: it puts the +fixed point at V = r, so V spans the whole HL-Gauss support [0, 1]. Treating the end as a true terminal +(`--terminal terminate`, masks = 0) instead caps the return at (1 - gamma^L) ~= 0.023-0.036 for our +230-370-frame episodes at gamma = 0.9999, which is 2-4 of the 101 bins: the provenance gap survives but +the differences between 128 candidate actions at one state fall below one bin and the critic cannot rank +at all. Every run records its realised Q/V range in IFQL.json (`value_spread.q_range_in_bins`) so this +is checkable rather than assumed. + +STEP BUDGET: `--steps` gradient steps at IFQL's own batch size 256. Our RISE/IDQL policies (S0A, +S0Aidql) train for num_epochs=5000 x epoch_every_n_steps=100 = 500 000 gradient steps at batch 64, so +--steps 500000 matches them step for step (and gives IFQL 4x their sample presentations). + +RESUME: these runs sit on the PREEMPTABLE queue and LSF requeues a preempted job, so the trainer writes +a rolling `params_latest.pkl` + `resume.json` every `--resume-every` steps (25 000, ~2 min of work) and +continues from it on restart. Without that a preemption threw away up to the whole 500k-step run -- 5 of +the first 21 trainings restarted from step 1 before this existed. `train.seed` still fixes the network +initialisation, so a resumed run is the SAME arm; only the batch order after the restart differs, and the +data rng is re-seeded with (seed, start_step) so the resumed run does not replay batches it already saw. +`--no-resume` ignores the rolling checkpoint. + +OUTPUT (--out): params_.pkl (flax state dict, for resuming / re-export) and, at the end, +`ifql_bundle.pt` -- a TORCH file holding every weight as a plain numpy array plus the config and the +feat_stats path. Eval runs inside the RISE robomimic env, whose python has no JAX, so both the critic +backend (robomimic/algo/ifql_torch.py) and the flow actor read that bundle in torch. Numerical parity of +the two implementations is asserted by scripts/ifql_parity.py. + +usage (LSF only -- never on the login node): + scripts/rr_ifql.sh [extra train_ifql.py args] +""" +from __future__ import annotations + +import argparse +import json +import os +import pickle +import sys +import time +from pathlib import Path + +import numpy as np + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE / "impls")) # so `utils.*` / `agents.*` resolve as upstream expects + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +SD_FLOOR_DEFAULT, Z_CLIP_DEFAULT = 0.01, 10.0 + + +# --------------------------------------------------------------------------- data +def load_cache(cache: Path, hdf5: str | None, verbose=True): + """The DINO cache of one task -> (x [N,1545] float32 z-scored, a [N,7], rewards [N], ep_from, ep_to).""" + meta = np.load(cache / "meta.npz", allow_pickle=True) + ep_from, ep_to = np.asarray(meta["ep_from"]), np.asarray(meta["ep_to"]) + ep_succ = np.asarray(meta["ep_success"]).astype(np.float32) + ep_src = [str(s) for s in np.asarray(meta["ep_src"])] + z = np.load(cache / "z.f16.npy", mmap_mode="r") + pr = np.load(cache / "proprio.f32.npy", mmap_mode="r") + a = np.load(cache / "act.f32.npy").astype(np.float32) + n = z.shape[0] + assert pr.shape[0] == n == a.shape[0], (z.shape, pr.shape, a.shape) + feat = np.concatenate([np.asarray(z, np.float32), np.asarray(pr, np.float32)], 1) + st = np.load(cache / "feat_stats.npz") + mu, sd = np.asarray(st["mu"], np.float32), np.asarray(st["sd"], np.float32) + sd_floor, z_clip = SD_FLOOR_DEFAULT, Z_CLIP_DEFAULT + if "sd_floor" in st.files: + sd_floor = float(st["sd_floor"]) + if "z_clip" in st.files: + z_clip = float(st["z_clip"]) + pack = cache / "PACK.json" + if pack.is_file(): + pk = json.loads(pack.read_text()) + sd_floor = float(pk.get("sd_floor", sd_floor)) + z_clip = float(pk.get("z_clip", z_clip)) + x = (feat - mu) / np.maximum(sd, sd_floor) + if z_clip and z_clip > 0: + x = np.clip(x, -z_clip, z_clip) + x = x.astype(np.float32) + + # ---- provenance reward, from the SOURCE hdf5 (`rewards`), laid out in cache frame order ------------- + src = hdf5 or json.loads((cache / "PACK.json").read_text())["src"] + rew = np.zeros(n, np.float32) + import h5py + with h5py.File(src, "r") as f: + for k, i0, i1 in zip(ep_src, ep_from, ep_to): + r = np.asarray(f[f"data/{k}/rewards"], np.float32) + L = int(i1 - i0) + assert len(r) >= L, f"{k}: hdf5 has {len(r)} rewards, cache wants {L}" + u = np.unique(r[:L]) + assert u.size == 1, f"{k}: rewards are not constant over the episode ({u[:5]}) -- the " + rew[i0:i1] = float(u[0]) + # cross-check against the cache's own episode label (rewards.max() > 0) + got = np.array([rew[i0] > 0 for i0 in ep_from], np.float32) + assert np.array_equal(got, (ep_succ > 0).astype(np.float32)), "hdf5 rewards disagree with meta.ep_success" + if verbose: + print(f"[ifql] {n} frames, {len(ep_from)} episodes, {int(got.sum())} expert-provenance " + f"({100 * got.mean():.1f}%), state {x.shape[1]}-d, action {a.shape[1]}-d", flush=True) + return x, a, rew, ep_from.astype(np.int64), ep_to.astype(np.int64) + + +class EpisodeDataset: + """n-step transitions over episodes laid end to end, matching impls/utils/datasets.Dataset. + + TERMINAL CONVENTION (`terminal`), which decides what the value function can even represent here: + + "truncate" (default, and the faithful reading of the published agent). A robomimic demonstration + ends because the demonstration ends, not because the MDP reached an absorbing state -- that is + truncation, and the standard convention, which ogbench also follows, is masks = 1 for a truncated + transition, bootstrapping from the final observation. The Bellman fixed point at the last frame is + then V = (1-gamma) r + gamma V => V = r, so V(s) is the probability that the future from s looks + like expert data and spans the whole HL-Gauss support [0, 1]. This is exactly the quantity the RSM + membership head estimates, which is what makes the two columns comparable. + + "terminate". masks = 0 on the last frame, so the return is the truncated sum + sum_{k {'a/b/c': ndarray}""" + out = {} + for k, v in params.items(): + key = f"{prefix}{k}" + if hasattr(v, "items"): + out.update(flatten_params(v, key + "/")) + else: + out[key] = np.asarray(v) + return out + + +def export_bundle(agent, cfg, out_path, feat_stats, task, seed, step, obs_mode): + import torch + flat = flatten_params(_to_numpy_tree(agent.network.params)) + bundle = { + "kind": "ifql_bundle_v1", + "params": {k: torch.from_numpy(np.asarray(v, np.float32)) for k, v in flat.items()}, + "config": {k: (list(v) if isinstance(v, tuple) else v) for k, v in dict(cfg).items()}, + "feat_stats": str(feat_stats), + "task": task, "seed": int(seed), "step": int(step), "obs_mode": obs_mode, + "hl_gauss": {"num_bins": 101, "min": 0.0, "max": 1.0, "sigma_ratio": 0.75}, + "source": "rsm_rise/code/ifql/train_ifql.py (gen_q#264)", + } + os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True) + tmp = str(out_path) + ".tmp" + torch.save(bundle, tmp) + os.replace(tmp, out_path) + print(f"[ifql] exported {len(flat)} arrays -> {out_path}", flush=True) + return sorted(flat) + + +# --------------------------------------------------------------------------- main +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--task", required=True) + ap.add_argument("--cache", default="", help="default cache/") + 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() diff --git a/code_src/rise_code/README.md b/code_src/rise_code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..46ab8130256416a197daf65ad992c8ab53b9eaed --- /dev/null +++ b/code_src/rise_code/README.md @@ -0,0 +1,84 @@ +fig1 + +[![Python](https://img.shields.io/badge/python-3.10-blue.svg)](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 dependencies +conda env create -f environment.yaml +conda activate + +# pytorch3d (dependency for diffusion) must be installed separately +# due to bugs with downgrading torch to cpu +conda install pytorch3d -c pytorch3d + +# install sim-pipeline package +pip install -e . + +cd .. + +# install custom robosuite from source +git clone git@github.com:UWRobotLearning/robosuite.git +cd robosuite +pip install -e . + +# install custom robomimic from source +git clone git@github.com:UWRobotLearning/robomimic.git +cd robomimic +pip install -e . + +# install mimicgen_environments +git clone git@github.com:UWRobotLearning/mimicgen_environments.git +cd mimicgen_environments +pip 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= + +# Then convert to the proper format +python 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 --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= data.dataset_path= +``` + +To evaluate policies in simulation, run: + +``` +python scripts/eval.py -cn eval_robomimic_iql_diffusion exp.model_path= +env= +``` + +valid envs can be found in `configs/env`. Policies used in the paper can be downloaded here (pending). + diff --git a/code_src/rise_code/environment.yaml b/code_src/rise_code/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..54a2049759e8190feb73fa06fa2c8f37c37e562d --- /dev/null +++ b/code_src/rise_code/environment.yaml @@ -0,0 +1,50 @@ +name: ood_sim +channels: + - pytorch + - nvidia + - conda-forge + - defaults +dependencies: + - 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_collections \ No newline at end of file diff --git a/code_src/rise_code/scripts/collect_human_demonstrations.py b/code_src/rise_code/scripts/collect_human_demonstrations.py new file mode 100644 index 0000000000000000000000000000000000000000..3b7da741916a865fc05a8c39ce2ba6e54c080299 --- /dev/null +++ b/code_src/rise_code/scripts/collect_human_demonstrations.py @@ -0,0 +1,4 @@ +from sim_pipeline.data_collection.collect_human_demonstrations import collect + +if __name__ == '__main__': + collect() \ No newline at end of file diff --git a/code_src/rise_code/scripts/combine_datasets.py b/code_src/rise_code/scripts/combine_datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..2e0e387c016e59f364e97ae928119cd3470a52ea --- /dev/null +++ b/code_src/rise_code/scripts/combine_datasets.py @@ -0,0 +1,4 @@ +from sim_pipeline.data_manager.combine_datasets import combine_datasets_command + +if __name__ == '__main__': + combine_datasets_command() \ No newline at end of file diff --git a/code_src/rise_code/scripts/dataset_states_to_obs.py b/code_src/rise_code/scripts/dataset_states_to_obs.py new file mode 100644 index 0000000000000000000000000000000000000000..f69492f8a4a4c2509d5aafd4bd198c7233275dc5 --- /dev/null +++ b/code_src/rise_code/scripts/dataset_states_to_obs.py @@ -0,0 +1,4 @@ +from sim_pipeline.data_manager.dataset_states_to_obs import main + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/code_src/rise_code/scripts/eval.py b/code_src/rise_code/scripts/eval.py new file mode 100644 index 0000000000000000000000000000000000000000..73f4292dd07046908554526d1f84732d77f2d566 --- /dev/null +++ b/code_src/rise_code/scripts/eval.py @@ -0,0 +1,4 @@ +from sim_pipeline.eval.eval import eval + +if __name__ == "__main__": + eval() \ No newline at end of file diff --git a/code_src/rise_code/scripts/playback_dataset.py b/code_src/rise_code/scripts/playback_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..32a37ef3ef90e156cafb0f45719473e9c0b7be05 --- /dev/null +++ b/code_src/rise_code/scripts/playback_dataset.py @@ -0,0 +1,4 @@ +from sim_pipeline.data_manager.playback_dataset import playback_dataset + +if __name__ == '__main__': + playback_dataset() \ No newline at end of file diff --git a/code_src/rise_code/scripts/train_robomimic.py b/code_src/rise_code/scripts/train_robomimic.py new file mode 100644 index 0000000000000000000000000000000000000000..6caf642bc906a64ffd84cffc1dde6282c343329f --- /dev/null +++ b/code_src/rise_code/scripts/train_robomimic.py @@ -0,0 +1,4 @@ +from sim_pipeline.training.train_robomimic import train + +if __name__ == '__main__': + train() \ No newline at end of file diff --git a/code_src/rise_code/setup.py b/code_src/rise_code/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..3897f9e81cf4ce954eeb89ee8ae7fd8f4a8e9624 --- /dev/null +++ b/code_src/rise_code/setup.py @@ -0,0 +1,8 @@ +from setuptools import setup, find_packages + +setup( + name="sim_pipeline", + version="0.1.0", + packages=find_packages(), +) + diff --git a/code_src/rise_code/sim_pipeline/__init__.py b/code_src/rise_code/sim_pipeline/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..38d9990e56cbe7d3f8ba202e75bf5dca8f1561e1 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/__init__.py @@ -0,0 +1,35 @@ +import os +import warnings +from pathlib import Path + +warnings.filterwarnings('ignore', module='robosuite') +warnings.filterwarnings('ignore', module='robomimic') + +# required for running on hyak without docker +if 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 import +import robosuite +robosuite_path = Path(robosuite.__file__).parent +# make macros file +macros_path = robosuite_path / 'macros_private.py' +macros_path.touch() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/__init__.py b/code_src/rise_code/sim_pipeline/configs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code_src/rise_code/sim_pipeline/configs/_data_collection/data_collection.py b/code_src/rise_code/sim_pipeline/configs/_data_collection/data_collection.py new file mode 100644 index 0000000000000000000000000000000000000000..d9c0f338c80473329d81230149ea7621f6097087 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_data_collection/data_collection.py @@ -0,0 +1,47 @@ +from dataclasses import dataclass, field +from typing import Any +from sim_pipeline.configs.constants import IO_Devices, ROOT_DIR, DATA_DIR +from sim_pipeline.configs.env.robomimic_base import RobomimicEnvConfig +from sim_pipeline.configs.env.robomimic_square_ood import RobommimicSquareEnvOODConfig + + +@dataclass +class 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 = False \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_data_summary/data_summary.py b/code_src/rise_code/sim_pipeline/configs/_data_summary/data_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..a3490892db0757c486bd5ff61c90fc98b7901d30 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_data_summary/data_summary.py @@ -0,0 +1,6 @@ +from dataclasses import dataclass +from sim_pipeline.configs.data.base_data import BaseDataConfig + +@dataclass +class DataSummaryConfig: + data: BaseDataConfig = BaseDataConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_diffusion/base_diffusion.py b/code_src/rise_code/sim_pipeline/configs/_diffusion/base_diffusion.py new file mode 100644 index 0000000000000000000000000000000000000000..38e1b7ecfb5aca5726193696cafe4d6c883822ae --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_diffusion/base_diffusion.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass +import sim_pipeline.configs.default as default +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.training._diffusion.base_diffusion import DiffusionTrainingConfig +from sim_pipeline.configs.exp.diffusion_train import DiffusionExpConfig + +@dataclass +class DiffusionBaseConfig(default.TopLevelConfig): + name: str = 'diffusion_square' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: DiffusionExpConfig = DiffusionExpConfig() + training: DiffusionTrainingConfig = DiffusionTrainingConfig() + diff --git a/code_src/rise_code/sim_pipeline/configs/_diffusion/diffusion_image.py b/code_src/rise_code/sim_pipeline/configs/_diffusion/diffusion_image.py new file mode 100644 index 0000000000000000000000000000000000000000..3bcc38f0df60ead784edda0352415e720d986b28 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_diffusion/diffusion_image.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass +import sim_pipeline.configs.default as default +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square_image import RobomimicSquareImageEnvConfig +from sim_pipeline.configs.training._diffusion.diffusion_image import DiffusionImageTrainingConfig +from sim_pipeline.configs.exp.diffusion_train import DiffusionExpConfig + +@dataclass +class DiffusionImageConfig(default.TopLevelConfig): + name: str = 'diffusion_image_square' + env: BaseEnvConfig = RobomimicSquareImageEnvConfig() + exp: DiffusionExpConfig = DiffusionExpConfig() + training: DiffusionImageTrainingConfig = DiffusionImageTrainingConfig() + diff --git a/code_src/rise_code/sim_pipeline/configs/_diffusion/tycho_diffusion.py b/code_src/rise_code/sim_pipeline/configs/_diffusion/tycho_diffusion.py new file mode 100644 index 0000000000000000000000000000000000000000..d3aa147ab56109a615140942654e834e80fa39c5 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_diffusion/tycho_diffusion.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass +import sim_pipeline.configs.default as default +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.training._diffusion.tycho_diffusion import DiffusionTrainingConfig +from sim_pipeline.configs.exp.diffusion_train import DiffusionExpConfig + +@dataclass +class DiffusionBaseConfig(default.TopLevelConfig): + name: str = 'diffusion_square' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: DiffusionExpConfig = DiffusionExpConfig() + training: DiffusionTrainingConfig = DiffusionTrainingConfig() + diff --git a/code_src/rise_code/sim_pipeline/configs/_discriminator/robomimic_discriminator.py b/code_src/rise_code/sim_pipeline/configs/_discriminator/robomimic_discriminator.py new file mode 100644 index 0000000000000000000000000000000000000000..d4f8ee949a450c78aa4f7f345d24ccdf18d89393 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_discriminator/robomimic_discriminator.py @@ -0,0 +1,15 @@ +from dataclasses import dataclass +import sim_pipeline.configs.default as default +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.training._imitation_learning.base_imitation import ImitationTrainingConfig +from sim_pipeline.configs.training._imitation_learning.discriminator import DiscriminatorTrainingConfig +from sim_pipeline.configs.exp.robomimic_train import RobomimicTrainExpConfig +from sim_pipeline.configs.data.base_data import BaseDataConfig + +@dataclass +class RobomimicDiscriminatorConfig(default.TopLevelConfig): + name: str = 'discriminator_square' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: RobomimicTrainExpConfig = RobomimicTrainExpConfig() + training: ImitationTrainingConfig = DiscriminatorTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_env_configs/ood_pushing.py b/code_src/rise_code/sim_pipeline/configs/_env_configs/ood_pushing.py new file mode 100644 index 0000000000000000000000000000000000000000..e0b1a16f94da4fb40d0d42e02b6db796d7f7fd84 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_env_configs/ood_pushing.py @@ -0,0 +1,10 @@ +from dataclasses import dataclass +import sim_pipeline.configs.default as default + +from sim_pipeline.configs.env.robomimic_square_ood_pushing import RobommimicSquareEnvOODPushingConfig +from sim_pipeline.configs.training._reinforcement_learning.robomimic_sac import SACTrainingConfig + +@dataclass +class Config(default.TopLevelConfig): + name: str = '' + env: RobommimicSquareEnvOODPushingConfig = RobommimicSquareEnvOODPushingConfig() diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/hook_expert_lowdim.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/hook_expert_lowdim.py new file mode 100644 index 0000000000000000000000000000000000000000..903be85472f2192206246f98f6472d5b3959be72 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/hook_expert_lowdim.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.exp._eval._combined_individual.square_expert_diffusion_lowdim import DiffusionEvalExpConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.training._diffusion.base_diffusion import DiffusionTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + name: str ='diffusion_hook_expert' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: EvalExpConfig = DiffusionEvalExpConfig() + training: DiffusionTrainingConfig = DiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/pushing_expert_lowdim.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/pushing_expert_lowdim.py new file mode 100644 index 0000000000000000000000000000000000000000..89a907120ff6d341465737f8f038ff3835b79ca7 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/pushing_expert_lowdim.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square_ood import RobommimicSquareEnvOODConfig +from sim_pipeline.configs.exp._eval._combined_individual.pushing_expert_diffusion_lowdim import DiffusionEvalExpConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.training._diffusion.base_diffusion_rohan import DiffusionTrainingRohanConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + name: str ='diffusion_combined_lowdim_rohan' + env: BaseEnvConfig = RobommimicSquareEnvOODConfig() + exp: EvalExpConfig = DiffusionEvalExpConfig() + training: DiffusionTrainingRohanConfig = DiffusionTrainingRohanConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_combined_images.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_combined_images.py new file mode 100644 index 0000000000000000000000000000000000000000..02516e92fa968c5db471a32dc0da37f68acee527 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_combined_images.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.exp._eval._combined_individual.square_combined_diffusion_images import DiffusionEvalExpConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.training._diffusion.diffusion_image import DiffusionImageTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + name: str ='diffusion_square_combined_image' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: EvalExpConfig = DiffusionEvalExpConfig() + training: DiffusionImageTrainingConfig = DiffusionImageTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_expert_ll_lowdim.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_expert_ll_lowdim.py new file mode 100644 index 0000000000000000000000000000000000000000..4cb943c1f91a081723a864f6289e8a3e8e3d5b1b --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_expert_ll_lowdim.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.exp._eval.diffusion_eval import DiffusionEvalExpConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.training._diffusion.base_diffusion import DiffusionTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + name: str ='diffusion_square_expert_ll_lowdim' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: EvalExpConfig = DiffusionEvalExpConfig() + training: DiffusionTrainingConfig = DiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_expert_lowdim.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_expert_lowdim.py new file mode 100644 index 0000000000000000000000000000000000000000..ba809ef125f7a09e25fb1b907968e6aad9fb5be0 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_expert_lowdim.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.exp._eval._combined_individual.square_expert_diffusion_lowdim import DiffusionEvalExpConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.training._diffusion.base_diffusion import DiffusionTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + name: str ='diffusion_square_expert_lowdim' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: EvalExpConfig = DiffusionEvalExpConfig() + training: DiffusionTrainingConfig = DiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_expert_lowdim_rohan.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_expert_lowdim_rohan.py new file mode 100644 index 0000000000000000000000000000000000000000..567ff10a27c79111921bbd39d1fdbb63410c8459 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_expert_lowdim_rohan.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.exp._eval._combined_individual.square_expert_diffusion_lowdim_rohan import DiffusionEvalExpConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.training._diffusion.base_diffusion_rohan import DiffusionTrainingRohanConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + name: str ='diffusion_square_expert_lowdim_rohan' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: EvalExpConfig = DiffusionEvalExpConfig() + training: DiffusionTrainingRohanConfig = DiffusionTrainingRohanConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_iql_diffusion_300a_200e_image.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_iql_diffusion_300a_200e_image.py new file mode 100644 index 0000000000000000000000000000000000000000..eb4c1b1d02b95aad8424c5c9e880d25e9e70f347 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_iql_diffusion_300a_200e_image.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.exp._eval.robomimic_eval import RobomimicEvalExpConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion_image import IQLDiffusionTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + name: str ='iql_diffusion_push_300r_200e_expert_image_01_rew' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: EvalExpConfig = RobomimicEvalExpConfig() + training: IQLDiffusionTrainingConfig = IQLDiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_iql_diffusion_push_coverage_to_tl.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_iql_diffusion_push_coverage_to_tl.py new file mode 100644 index 0000000000000000000000000000000000000000..ab3796220c3a7c254639a88ad59ac15993d7b330 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_iql_diffusion_push_coverage_to_tl.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.exp._eval.robomimic_eval import RobomimicEvalExpConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion import IQLDiffusionTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + name: str ='iql_diffusion_push_to_tl_true' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: EvalExpConfig = RobomimicEvalExpConfig() + training: IQLDiffusionTrainingConfig = IQLDiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_iql_diffusion_push_to_mid.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_iql_diffusion_push_to_mid.py new file mode 100644 index 0000000000000000000000000000000000000000..4f0b878d00c842ba3c23dd5c5e0a107afd7e2a30 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_iql_diffusion_push_to_mid.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.exp._eval.robomimic_eval import RobomimicEvalExpConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion import IQLDiffusionTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + name: str ='iql_diffusion_push_coverage_300angled_mid' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: EvalExpConfig = RobomimicEvalExpConfig() + training: IQLDiffusionTrainingConfig = IQLDiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_manual_pushing_ll.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_manual_pushing_ll.py new file mode 100644 index 0000000000000000000000000000000000000000..5b4e8238fa10c3e6adc9c6fdb9d3b935c11fa6be --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_manual_pushing_ll.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.exp._eval.diffusion_eval import DiffusionEvalExpConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.training._diffusion.base_diffusion import DiffusionTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + name: str ='diffusion_square_push_ll_lowdim' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: EvalExpConfig = DiffusionEvalExpConfig() + training: DiffusionTrainingConfig = DiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_manual_pushing_tl.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_manual_pushing_tl.py new file mode 100644 index 0000000000000000000000000000000000000000..3bbcaa6d42c57769fe3786d07183731e93aecc7a --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_manual_pushing_tl.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.exp._eval.diffusion_eval import DiffusionEvalExpConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.training._diffusion.base_diffusion import DiffusionTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + name: str ='diffusion_square_manual_pushing_lowdim' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: EvalExpConfig = DiffusionEvalExpConfig() + training: DiffusionTrainingConfig = DiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_pushing_lowdim.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_pushing_lowdim.py new file mode 100644 index 0000000000000000000000000000000000000000..d81ee9f100e5c7fc58db5020be9a0faab589f193 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_pushing_lowdim.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.exp._eval._combined_individual.square_pushing_diffusion_lowdim import DiffusionEvalExpConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.training._diffusion.base_diffusion import DiffusionTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + name: str ='diffusion_square_pushing_lowdim' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: EvalExpConfig = DiffusionEvalExpConfig() + training: DiffusionTrainingConfig = DiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_rotation.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_rotation.py new file mode 100644 index 0000000000000000000000000000000000000000..d0e79421c2c82da9d26c2647020ee537cf223b3f --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_combined_individual/square_rotation.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.exp._eval.robomimic_eval import RobomimicEvalExpConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion import IQLDiffusionTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + name: str ='iql_diffusion_rotation' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: EvalExpConfig = RobomimicEvalExpConfig() + training: IQLDiffusionTrainingConfig = IQLDiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset.py new file mode 100644 index 0000000000000000000000000000000000000000..83618bb0dcdaee15cfa4f4f6b26c789929523e29 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square_ood import RobommimicSquareEnvOODConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.exp._eval.heuristic_reset_eval import HeuristicResetEvalExpConfig +from sim_pipeline.configs.training._diffusion.base_diffusion import DiffusionTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + env: BaseEnvConfig = RobommimicSquareEnvOODConfig() + exp: EvalExpConfig = HeuristicResetEvalExpConfig() + training: DiffusionTrainingConfig = DiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_idql_images.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_idql_images.py new file mode 100644 index 0000000000000000000000000000000000000000..9504262e72da5062f4bbe914f8f027301c2189e3 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_idql_images.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square_coverage_pushing import RobomimicSquareEnvOODConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.exp._eval.heuristic_reset_split_idql_image import HeuristicResetSplitEvalExpConfig +from sim_pipeline.configs.training._diffusion.diffusion_image import DiffusionImageTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + env: BaseEnvConfig = RobomimicSquareEnvOODConfig() + exp: EvalExpConfig = HeuristicResetSplitEvalExpConfig() + training: DiffusionImageTrainingConfig = DiffusionImageTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_images.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_images.py new file mode 100644 index 0000000000000000000000000000000000000000..5e6e88f01acf6568d509ded903ba7de4f62eecf0 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_images.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square_image_ood import RobommimicSquareImageEnvOODConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.exp._eval.heuristic_reset_images_eval import HeuristicResetImagesEvalExpConfig +from sim_pipeline.configs.training._diffusion.diffusion_image import DiffusionImageTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + env: BaseEnvConfig = RobommimicSquareImageEnvOODConfig() + exp: EvalExpConfig = HeuristicResetImagesEvalExpConfig() + training: DiffusionImageTrainingConfig = DiffusionImageTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_push_ll_manual.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_push_ll_manual.py new file mode 100644 index 0000000000000000000000000000000000000000..be2b95fe40611f585227c5f5ae88b75a3a4217a0 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_push_ll_manual.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square_ood import RobommimicSquareEnvOODConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.exp._eval.heuristic_reset_manual_ll_eval import HeuristicResetSplitEvalExpConfig +from sim_pipeline.configs.training._diffusion.base_diffusion import DiffusionTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + env: BaseEnvConfig = RobommimicSquareEnvOODConfig() + exp: EvalExpConfig = HeuristicResetSplitEvalExpConfig() + training: DiffusionTrainingConfig = DiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_push_mid.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_push_mid.py new file mode 100644 index 0000000000000000000000000000000000000000..56e08267e3bdcaad86b7106c909fd3ae40844ab0 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_push_mid.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square_coverage_pushing import RobomimicSquareEnvOODConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.exp._eval.heuristic_reset_push_mid import HeuristicResetSplitEvalExpConfig +from sim_pipeline.configs.training._diffusion.base_diffusion import DiffusionTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + env: BaseEnvConfig = RobomimicSquareEnvOODConfig() + exp: EvalExpConfig = HeuristicResetSplitEvalExpConfig() + training: DiffusionTrainingConfig = DiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_push_tl_coverage.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_push_tl_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..7a003001b5b4604b82222f2756e400b431444507 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_push_tl_coverage.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square_coverage import RobomimicSquareEnvOODConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.exp._eval.heuristic_reset_coverage_tl_eval import HeuristicResetSplitEvalExpConfig +from sim_pipeline.configs.training._diffusion.base_diffusion import DiffusionTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + env: BaseEnvConfig = RobomimicSquareEnvOODConfig() + exp: EvalExpConfig = HeuristicResetSplitEvalExpConfig() + training: DiffusionTrainingConfig = DiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_push_tl_manual.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_push_tl_manual.py new file mode 100644 index 0000000000000000000000000000000000000000..9112509b3845df430eb8d231d735df79607ef49d --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_push_tl_manual.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square_ood import RobommimicSquareEnvOODConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.exp._eval.heuristic_reset_manual_eval import HeuristicResetSplitEvalExpConfig +from sim_pipeline.configs.training._diffusion.base_diffusion import DiffusionTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + env: BaseEnvConfig = RobommimicSquareEnvOODConfig() + exp: EvalExpConfig = HeuristicResetSplitEvalExpConfig() + training: DiffusionTrainingConfig = DiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_rotation.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_rotation.py new file mode 100644 index 0000000000000000000000000000000000000000..6fe1f8cf84a5c425bcf6faabf0aa6341418549c4 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_rotation.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square_ood import RobommimicSquareEnvOODConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.exp._eval.heuristic_reset_rotation import HeuristicResetSplitEvalExpConfig +from sim_pipeline.configs.training._diffusion.base_diffusion import DiffusionTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + env: BaseEnvConfig = RobommimicSquareEnvOODConfig() + exp: EvalExpConfig = HeuristicResetSplitEvalExpConfig() + training: DiffusionTrainingConfig = DiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_split.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_split.py new file mode 100644 index 0000000000000000000000000000000000000000..1914813a883aad690b3e04a9fe4ec1f41e550c9f --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_split.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square_ood import RobommimicSquareEnvOODConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.exp._eval.heuristic_reset_split_eval import HeuristicResetSplitEvalExpConfig +from sim_pipeline.configs.training._diffusion.base_diffusion import DiffusionTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + env: BaseEnvConfig = RobommimicSquareEnvOODConfig() + exp: EvalExpConfig = HeuristicResetSplitEvalExpConfig() + training: DiffusionTrainingConfig = DiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_split_rohan.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_split_rohan.py new file mode 100644 index 0000000000000000000000000000000000000000..c1906f807e385cc4b59a7f08dc507c49ef3d79f3 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_split_rohan.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square_ood import RobommimicSquareEnvOODConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.exp._eval.heuristic_reset_split_eval2 import HeuristicResetSplitEvalExpConfig +from sim_pipeline.configs.training._diffusion.base_diffusion import DiffusionTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + env: BaseEnvConfig = RobommimicSquareEnvOODConfig() + exp: EvalExpConfig = HeuristicResetSplitEvalExpConfig() + training: DiffusionTrainingConfig = DiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_true_split.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_true_split.py new file mode 100644 index 0000000000000000000000000000000000000000..1914813a883aad690b3e04a9fe4ec1f41e550c9f --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/_heuristic_reset/eval_heuristic_reset_true_split.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square_ood import RobommimicSquareEnvOODConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.exp._eval.heuristic_reset_split_eval import HeuristicResetSplitEvalExpConfig +from sim_pipeline.configs.training._diffusion.base_diffusion import DiffusionTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + env: BaseEnvConfig = RobommimicSquareEnvOODConfig() + exp: EvalExpConfig = HeuristicResetSplitEvalExpConfig() + training: DiffusionTrainingConfig = DiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_base.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_base.py new file mode 100644 index 0000000000000000000000000000000000000000..72ed2b9c832259406353a0953712fb4388948c54 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_base.py @@ -0,0 +1,12 @@ +from dataclasses import dataclass +from typing import Any +import sim_pipeline.configs.default as default + +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class EvaluationConfig(default.TopLevelConfig): + name: str = 'eval_default' + env: BaseEnvConfig = BaseEnvConfig() + exp: EvalExpConfig = EvalExpConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_diffusion.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_diffusion.py new file mode 100644 index 0000000000000000000000000000000000000000..fc061141690941ba6daecfcf41f77d85dfb3ad1d --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_diffusion.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.exp._eval.diffusion_eval import DiffusionEvalExpConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.training._diffusion.base_diffusion import DiffusionTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: EvalExpConfig = DiffusionEvalExpConfig() + training: DiffusionTrainingConfig = DiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_diffusion_image.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_diffusion_image.py new file mode 100644 index 0000000000000000000000000000000000000000..dcb85212d6e6634b968f1667c51836733d9ea486 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_diffusion_image.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_base import RobomimicEnvConfig +from sim_pipeline.configs.exp._eval.diffusion_eval import DiffusionEvalExpConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.training._diffusion.diffusion_image import DiffusionImageTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + env: BaseEnvConfig = RobomimicEnvConfig() + exp: EvalExpConfig = DiffusionEvalExpConfig() + training: DiffusionImageTrainingConfig = DiffusionImageTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_ogbench.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_ogbench.py new file mode 100644 index 0000000000000000000000000000000000000000..540c3a7df8f7e0f68d5172d38c8df1b02c527cc1 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_ogbench.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +import sim_pipeline.configs.default as default +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.training._ogbench.crl import CRLTrainingConfig +from sim_pipeline.configs.exp._eval.ogbench_eval import OGBenchEvalExpConfig + +@dataclass +class OGBenchBaseConfig(default.TopLevelConfig): + name: str = 'ogbench_square' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: OGBenchEvalExpConfig = OGBenchEvalExpConfig() + training: CRLTrainingConfig = CRLTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_pd.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_pd.py new file mode 100644 index 0000000000000000000000000000000000000000..69f16b9346fea889a12bdc29e069be9f830f0227 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_pd.py @@ -0,0 +1,10 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square_ee_ood import RobommimicSquareEEOODEnvConfig +from sim_pipeline.configs.exp._eval.pd_eval import PDEvalExpConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + env: BaseEnvConfig = RobommimicSquareEEOODEnvConfig() + exp: PDEvalExpConfig = PDEvalExpConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_rl.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_rl.py new file mode 100644 index 0000000000000000000000000000000000000000..5473f3649a390a0609206d2d7268f250c365586f --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_rl.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass +from typing import Any +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.exp._eval.sb_eval import RLEvalExpConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.training._reinforcement_learning.robomimic_sac import SACTrainingConfig + +@dataclass +class RLEvalConfig(EvaluationConfig): + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: EvalExpConfig = RLEvalExpConfig() + training: Any = SACTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_rl_pushing.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_rl_pushing.py new file mode 100644 index 0000000000000000000000000000000000000000..51758b0a6cc3d1d4adc4c0ce2d7eddb2556c443a --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_rl_pushing.py @@ -0,0 +1,11 @@ +from dataclasses import dataclass +from sim_pipeline.configs._evaluation.eval_rl import RLEvalConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square_pushing import PushingRobomimicSquareEnvConfig +from sim_pipeline.configs.exp._eval.sb_eval import RLEvalExpConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class PushingRLEvalConfig(RLEvalConfig): + env: BaseEnvConfig = PushingRobomimicSquareEnvConfig() + exp: EvalExpConfig = RLEvalExpConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_robomimic.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_robomimic.py new file mode 100644 index 0000000000000000000000000000000000000000..cfce9a131fabca4eca62b5ad903b94bc2bbdc4fb --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_robomimic.py @@ -0,0 +1,12 @@ +from dataclasses import dataclass +from typing import Any +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.exp._eval.robomimic_eval import RobomimicEvalExpConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: EvalExpConfig = RobomimicEvalExpConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_robomimic_iql_diffusion.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_robomimic_iql_diffusion.py new file mode 100644 index 0000000000000000000000000000000000000000..217499c67ebad2790e51d79aaa454f5b77c27e4e --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_robomimic_iql_diffusion.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass +from typing import Any +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_base import RobomimicEnvConfig +from sim_pipeline.configs.exp._eval.robomimic_eval import RobomimicEvalExpConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion import IQLDiffusionTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + env: BaseEnvConfig = RobomimicEnvConfig() + exp: EvalExpConfig = RobomimicEvalExpConfig() + training: IQLDiffusionTrainingConfig = IQLDiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_robomimic_iql_diffusion_image.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_robomimic_iql_diffusion_image.py new file mode 100644 index 0000000000000000000000000000000000000000..2f7534a68ab66ff5428e917c301fce742f15bcb6 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/eval_robomimic_iql_diffusion_image.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass +from typing import Any +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_base import RobomimicEnvConfig +from sim_pipeline.configs.exp._eval.robomimic_eval import RobomimicEvalExpConfig +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion_image import IQLDiffusionImageTrainingConfig + +@dataclass +class RobomimicEvalConfig(EvaluationConfig): + env: BaseEnvConfig = RobomimicEnvConfig() + exp: EvalExpConfig = RobomimicEvalExpConfig() + training: IQLDiffusionImageTrainingConfig = IQLDiffusionImageTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_evaluation/iql_diagnostic.py b/code_src/rise_code/sim_pipeline/configs/_evaluation/iql_diagnostic.py new file mode 100644 index 0000000000000000000000000000000000000000..464aaf6c5969437e5594e7a086951f3c7fd0c629 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_evaluation/iql_diagnostic.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +import sim_pipeline.configs.default as default +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.training._imitation_learning._offline_rl.base_iql import IQLTrainingConfig +from sim_pipeline.configs.exp._eval.robomimic_eval import RobomimicEvalExpConfig + +@dataclass +class RobomimicIQLDiagnosticConfig(default.TopLevelConfig): + name: str = 'iql_diagnostic' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: RobomimicEvalExpConfig = RobomimicEvalExpConfig() + training: IQLTrainingConfig = IQLTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_imitation_learning/robomimic_imitation_base.py b/code_src/rise_code/sim_pipeline/configs/_imitation_learning/robomimic_imitation_base.py new file mode 100644 index 0000000000000000000000000000000000000000..913f72a977c97e20d8339e90be003f4bf96ce3b5 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_imitation_learning/robomimic_imitation_base.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +import sim_pipeline.configs.default as default +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.training._imitation_learning.base_imitation import ImitationTrainingConfig +from sim_pipeline.configs.exp.robomimic_train import RobomimicTrainExpConfig + +@dataclass +class RobomimicImitationBaseConfig(default.TopLevelConfig): + name: str = 'imitation_square' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: RobomimicTrainExpConfig = RobomimicTrainExpConfig() + training: ImitationTrainingConfig = ImitationTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_imitation_learning/square_bc_rnn_image.py b/code_src/rise_code/sim_pipeline/configs/_imitation_learning/square_bc_rnn_image.py new file mode 100644 index 0000000000000000000000000000000000000000..4a1cacadf408263f54dc055daa9a533423c4ae0f --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_imitation_learning/square_bc_rnn_image.py @@ -0,0 +1,9 @@ +from dataclasses import dataclass + +from sim_pipeline.configs._imitation_learning.robomimic_imitation_base import RobomimicImitationBaseConfig +from sim_pipeline.configs.training._imitation_learning.bcrnn_image import BCRNNImageTrainingConfig + +@dataclass +class RobomimicImitationBaseConfig(RobomimicImitationBaseConfig): + name: str = 'square_bc_rnn_image' + training: BCRNNImageTrainingConfig = BCRNNImageTrainingConfig() diff --git a/code_src/rise_code/sim_pipeline/configs/_imitation_learning/square_bc_rnn_lowdim.py b/code_src/rise_code/sim_pipeline/configs/_imitation_learning/square_bc_rnn_lowdim.py new file mode 100644 index 0000000000000000000000000000000000000000..003af3106157dff1c2fcdba9d7cf85363bae2f59 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_imitation_learning/square_bc_rnn_lowdim.py @@ -0,0 +1,7 @@ +from dataclasses import dataclass +from sim_pipeline.configs._imitation_learning.robomimic_imitation_base import RobomimicImitationBaseConfig +from sim_pipeline.configs.training._imitation_learning.base_imitation import ImitationTrainingConfig + +@dataclass +class RobomimicImitationBaseConfig(RobomimicImitationBaseConfig): + name: str = 'square_bc_rnn_lowdim' diff --git a/code_src/rise_code/sim_pipeline/configs/_offline_rl/crl.py b/code_src/rise_code/sim_pipeline/configs/_offline_rl/crl.py new file mode 100644 index 0000000000000000000000000000000000000000..d5d2cfed44ccaae8f764d382d380f3756e50ae3e --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_offline_rl/crl.py @@ -0,0 +1,12 @@ +from dataclasses import dataclass +import sim_pipeline.configs.default as default +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.training._ogbench.crl import CRLTrainingConfig +from sim_pipeline.configs.exp.robomimic_train import RobomimicTrainExpConfig +from sim_pipeline.configs._offline_rl.ogbench import OGBenchBaseConfig + +@dataclass +class CRLBaseConfig(OGBenchBaseConfig): + name: str = 'crl' + training: CRLTrainingConfig = CRLTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_offline_rl/iql_diffusion.py b/code_src/rise_code/sim_pipeline/configs/_offline_rl/iql_diffusion.py new file mode 100644 index 0000000000000000000000000000000000000000..6370b2dea61c50c470ad9078b3ad30d57e75188c --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_offline_rl/iql_diffusion.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +import sim_pipeline.configs.default as default +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion import IQLDiffusionTrainingConfig +from sim_pipeline.configs.exp.robomimic_train import RobomimicTrainExpConfig + +@dataclass +class RobomimicIQLBaseConfig(default.TopLevelConfig): + name: str = 'iql_diffusion_square' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: RobomimicTrainExpConfig = RobomimicTrainExpConfig() + training: IQLDiffusionTrainingConfig = IQLDiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_offline_rl/iql_diffusion_image.py b/code_src/rise_code/sim_pipeline/configs/_offline_rl/iql_diffusion_image.py new file mode 100644 index 0000000000000000000000000000000000000000..256c68b2099cd0fdc49bfbfc0887e96b035e842f --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_offline_rl/iql_diffusion_image.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +import sim_pipeline.configs.default as default +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion_image import IQLDiffusionImageTrainingConfig +from sim_pipeline.configs.exp.robomimic_train import RobomimicTrainExpConfig + +@dataclass +class RobomimicIQLBaseConfig(default.TopLevelConfig): + name: str = 'iql_diffusion_image_square' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: RobomimicTrainExpConfig = RobomimicTrainExpConfig() + training: IQLDiffusionImageTrainingConfig = IQLDiffusionImageTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_offline_rl/iql_diffusion_real_franka.py b/code_src/rise_code/sim_pipeline/configs/_offline_rl/iql_diffusion_real_franka.py new file mode 100644 index 0000000000000000000000000000000000000000..204eeff03f3138fcca2e5016ffa6e1ded55ac594 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_offline_rl/iql_diffusion_real_franka.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +import sim_pipeline.configs.default as default +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion_real_franka import IQLDiffusionTrainingConfig +from sim_pipeline.configs.exp.robomimic_train import RobomimicTrainExpConfig + +@dataclass +class RobomimicIQLBaseConfig(default.TopLevelConfig): + name: str = 'iql_diffusion_real_franka' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: RobomimicTrainExpConfig = RobomimicTrainExpConfig() + training: IQLDiffusionTrainingConfig = IQLDiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_offline_rl/iql_diffusion_tycho.py b/code_src/rise_code/sim_pipeline/configs/_offline_rl/iql_diffusion_tycho.py new file mode 100644 index 0000000000000000000000000000000000000000..a1eab4dd42e1b51e75baf383e170f835c727c555 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_offline_rl/iql_diffusion_tycho.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +import sim_pipeline.configs.default as default +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion_tycho import IQLDiffusionTrainingConfig +from sim_pipeline.configs.exp.robomimic_train import RobomimicTrainExpConfig + +@dataclass +class RobomimicIQLBaseConfig(default.TopLevelConfig): + name: str = 'iql_diffusion_tycho' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: RobomimicTrainExpConfig = RobomimicTrainExpConfig() + training: IQLDiffusionTrainingConfig = IQLDiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_offline_rl/iql_diffusion_tycho_image.py b/code_src/rise_code/sim_pipeline/configs/_offline_rl/iql_diffusion_tycho_image.py new file mode 100644 index 0000000000000000000000000000000000000000..9071756290c46eb8e8dcabbfc5bccc57fff6db1f --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_offline_rl/iql_diffusion_tycho_image.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +import sim_pipeline.configs.default as default +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion_tycho_image import IQLDiffusionTrainingConfig +from sim_pipeline.configs.exp.robomimic_train import RobomimicTrainExpConfig + +@dataclass +class RobomimicIQLBaseConfig(default.TopLevelConfig): + name: str = 'iql_diffusion_tycho_image' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: RobomimicTrainExpConfig = RobomimicTrainExpConfig() + training: IQLDiffusionTrainingConfig = IQLDiffusionTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_offline_rl/ogbench.py b/code_src/rise_code/sim_pipeline/configs/_offline_rl/ogbench.py new file mode 100644 index 0000000000000000000000000000000000000000..8757f20ca0eb90f3a11140787a2d5f5e43b3d772 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_offline_rl/ogbench.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +import sim_pipeline.configs.default as default +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.training._ogbench.ogbench import OGBenchTrainingConfig +from sim_pipeline.configs.exp.robomimic_train import RobomimicTrainExpConfig + +@dataclass +class OGBenchBaseConfig(default.TopLevelConfig): + name: str = 'ogbench_square' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: RobomimicTrainExpConfig = RobomimicTrainExpConfig() + training: OGBenchTrainingConfig = OGBenchTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_offline_rl/robomimic_iql_base.py b/code_src/rise_code/sim_pipeline/configs/_offline_rl/robomimic_iql_base.py new file mode 100644 index 0000000000000000000000000000000000000000..1ef08a1ccac10bee92ada884f7d9ad88fe6d701e --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_offline_rl/robomimic_iql_base.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +import sim_pipeline.configs.default as default +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.training._imitation_learning._offline_rl.base_iql import IQLTrainingConfig +from sim_pipeline.configs.exp.robomimic_train import RobomimicTrainExpConfig + +@dataclass +class RobomimicIQLBaseConfig(default.TopLevelConfig): + name: str = 'iql_square' + env: BaseEnvConfig = RobomimicSquareEnvConfig() + exp: RobomimicTrainExpConfig = RobomimicTrainExpConfig() + training: IQLTrainingConfig = IQLTrainingConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/_rl_expert/ppo_pick_cube.py b/code_src/rise_code/sim_pipeline/configs/_rl_expert/ppo_pick_cube.py new file mode 100644 index 0000000000000000000000000000000000000000..560608b7e5a0aef25759d7172c274d8438787dc3 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_rl_expert/ppo_pick_cube.py @@ -0,0 +1,9 @@ +from dataclasses import dataclass +from sim_pipeline.configs.env.franka_base import EnvConfigFranka +from sim_pipeline.configs.env.franka_cube import EnvConfigFrankaCube +import sim_pipeline.configs.default as default + +@dataclass +class Config(default.TopLevelConfig): + name: str = 'pick_cube' + env: EnvConfigFrankaCube = EnvConfigFrankaCube() diff --git a/code_src/rise_code/sim_pipeline/configs/_rl_expert/ppo_square.py b/code_src/rise_code/sim_pipeline/configs/_rl_expert/ppo_square.py new file mode 100644 index 0000000000000000000000000000000000000000..d122cb4c30d53beb88d0077f2d6e8ea4813072cc --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_rl_expert/ppo_square.py @@ -0,0 +1,11 @@ +from dataclasses import dataclass + +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.training._reinforcement_learning.robomimic_ppo import PPOTrainingConfig +import sim_pipeline.configs.default as default + +@dataclass +class Config(default.TopLevelConfig): + name: str = 'square_ppo' + env: RobomimicSquareEnvConfig = RobomimicSquareEnvConfig() + training: PPOTrainingConfig = PPOTrainingConfig() diff --git a/code_src/rise_code/sim_pipeline/configs/_rl_expert/sac_square.py b/code_src/rise_code/sim_pipeline/configs/_rl_expert/sac_square.py new file mode 100644 index 0000000000000000000000000000000000000000..1b068cf80b5cfa9e184ce8e59af1e599ed7b344a --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_rl_expert/sac_square.py @@ -0,0 +1,11 @@ +from dataclasses import dataclass +import sim_pipeline.configs.default as default + +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig +from sim_pipeline.configs.training._reinforcement_learning.robomimic_sac import SACTrainingConfig + +@dataclass +class Config(default.TopLevelConfig): + name: str = 'sac_square' + env: RobomimicSquareEnvConfig = RobomimicSquareEnvConfig() + training: SACTrainingConfig = SACTrainingConfig() diff --git a/code_src/rise_code/sim_pipeline/configs/_rl_expert/sac_square_pure_pushing.py b/code_src/rise_code/sim_pipeline/configs/_rl_expert/sac_square_pure_pushing.py new file mode 100644 index 0000000000000000000000000000000000000000..8116d52cc2c43fc18691a67ec29f22d11d3be79d --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_rl_expert/sac_square_pure_pushing.py @@ -0,0 +1,11 @@ +from dataclasses import dataclass +import sim_pipeline.configs.default as default + +from sim_pipeline.configs.env.robomimic_square_coverage_pure_pushing import PushingRobomimicSquareEnvConfig +from sim_pipeline.configs.training._reinforcement_learning.robomimic_sac import SACTrainingConfig + +@dataclass +class Config(default.TopLevelConfig): + name: str = 'sac_square_pushing' + env: PushingRobomimicSquareEnvConfig = PushingRobomimicSquareEnvConfig() + training: SACTrainingConfig = SACTrainingConfig() diff --git a/code_src/rise_code/sim_pipeline/configs/_rl_expert/sac_square_pushing.py b/code_src/rise_code/sim_pipeline/configs/_rl_expert/sac_square_pushing.py new file mode 100644 index 0000000000000000000000000000000000000000..6b124d04f5c252e274f225e64407ea67e4e55eb3 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_rl_expert/sac_square_pushing.py @@ -0,0 +1,11 @@ +from dataclasses import dataclass +import sim_pipeline.configs.default as default + +from sim_pipeline.configs.env.robomimic_square_pushing import PushingRobomimicSquareEnvConfig +from sim_pipeline.configs.training._reinforcement_learning.robomimic_sac import SACTrainingConfig + +@dataclass +class Config(default.TopLevelConfig): + name: str = 'sac_square_pushing' + env: PushingRobomimicSquareEnvConfig = PushingRobomimicSquareEnvConfig() + training: SACTrainingConfig = SACTrainingConfig() diff --git a/code_src/rise_code/sim_pipeline/configs/_rl_expert/sac_square_pushing_ll.py b/code_src/rise_code/sim_pipeline/configs/_rl_expert/sac_square_pushing_ll.py new file mode 100644 index 0000000000000000000000000000000000000000..74c2d5add35a1a4cd91b3df7b49513a0b1d84d2c --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/_rl_expert/sac_square_pushing_ll.py @@ -0,0 +1,11 @@ +from dataclasses import dataclass +import sim_pipeline.configs.default as default + +from sim_pipeline.configs.env.robomimic_square_pushing_ll import PushingLLRobomimicSquareEnvConfig +from sim_pipeline.configs.training._reinforcement_learning.robomimic_sac import SACTrainingConfig + +@dataclass +class Config(default.TopLevelConfig): + name: str = 'sac_square_pushing_ll' + env: PushingLLRobomimicSquareEnvConfig = PushingLLRobomimicSquareEnvConfig() + training: SACTrainingConfig = SACTrainingConfig() diff --git a/code_src/rise_code/sim_pipeline/configs/constants.py b/code_src/rise_code/sim_pipeline/configs/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..61cb4e2ac9220b0cebd29d55500e297a8642ab0d --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/constants.py @@ -0,0 +1,221 @@ +import numpy as np + +from enum import Enum +from pathlib import Path + +import mimicgen_envs + +class EnvType(Enum): + FRANKA = 'franka' + POINT_MAZE = 'point_maze' + ROBOMIMIC = 'robomimic' + +class RLAlgorithm(Enum): + PPO = "PPO" + SAC = "SAC" + + def get_algo(self): + from stable_baselines3 import PPO, SAC + + if self == RLAlgorithm.PPO: + return PPO + elif self == RLAlgorithm.SAC: + return SAC + else: + raise ValueError(f"Unknown algorithm {self}") + +class ImitationAlgorithm(Enum): + BC_RNN = 'bc_rnn' + BC = 'bc' + CQL = 'cql' + IQL = 'iql' + IDQL = 'idql' + IDQL_QSM = 'idql_qsm' + IQL_DIFFUSION = 'iql_diffusion' + DISCRIMINATOR = 'discriminator' + + def is_offline_rl(self): + return self in [ImitationAlgorithm.IQL, ImitationAlgorithm.CQL, ImitationAlgorithm.IQL_DIFFUSION, ImitationAlgorithm.IDQL_QSM, ImitationAlgorithm.IDQL] + + def is_diffusion(self): + return self in [ImitationAlgorithm.IQL_DIFFUSION, ImitationAlgorithm.IDQL, ImitationAlgorithm.IDQL_QSM] + +class PolicyType(Enum): + ROBOMIMIC = 'robomimic' + STABLE_BASELINES = 'sb3' + DIFFUSION = 'diffusion' + OGBENCH = 'ogbench' + COMPOSITE = 'composite' + PD = 'pd' + DISCRIMINATOR = 'discriminator' + QTRANSFORMER = 'qtransformer' + +class OGBenchAlgo(Enum): + GCBC = 'gcbc' + GCIQL = 'gciql' + HIQL = 'hiql' + CRL = 'crl' + + def get_agent(self): + from impls.agents import agents + + return agents[self.value] + +class CombinedPolicyType(Enum): + HEURISTIC_RESET = 'heuristic_reset' + HEURISTIC_RESET_SPLIT = 'heuristic_reset_split' +class RobomimicEnvType(Enum): + LIFT = 'Lift' + STACK = 'Stack' + NUT_ASSEMBLY = 'NutAssembly' + NUT_ASSEMBLY_SQUARE = 'NutAssemblySquare' + NUT_ASSEMBLY_ROUND = 'NutAssemblyRound' + NUT_ASSEMBLY_HANG_INSERT = 'NutAssemblyHangInsert' + PICK_PLACE = 'PickPlace' + DOOR = 'Door' + THREE_PIECE_ASSEMBLY = 'ThreePieceAssembly' + THREADING = 'Threading' + MUG_CLEANUP = 'MugCleanup' + COFFEE = 'Coffee' + TOOL_HANG = 'ToolHang' + + def get_object_names(self): + # see object names in robosuite environments, i.e. robosuite/environments/manipulation/nut_assembly.py:403 + if self in [RobomimicEnvType.NUT_ASSEMBLY, RobomimicEnvType.NUT_ASSEMBLY_SQUARE, RobomimicEnvType.NUT_ASSEMBLY_ROUND]: + return ['SquareNut', 'RoundNut'] + elif self == RobomimicEnvType.THREE_PIECE_ASSEMBLY: + return ['Base', 'Piece1'] + elif self == RobomimicEnvType.THREADING: + return ['Needle', 'Tripod'] + elif self == RobomimicEnvType.TOOL_HANG: + return ['standObject','frameObject','toolObject'] + else: + return [] + + def get_default_obj_init_ranges(self): + if self in [RobomimicEnvType.NUT_ASSEMBLY, RobomimicEnvType.NUT_ASSEMBLY_SQUARE, RobomimicEnvType.NUT_ASSEMBLY_ROUND]: + return { + 'SquareNut': + [ + [-0.115, -0.11], + [0.11, 0.225], + ], + 'RoundNut': + [ + [-1.0, -0.9], + # [-0.115, -0.11], + [-0.225, -0.11], + ] + } + elif self in [RobomimicEnvType.THREE_PIECE_ASSEMBLY]: + return { + 'Base': + [ + [0.0, 0.0], + [0.0, 0.0], + [0.0, 0.0], + ], + 'Piece1': + [ + [-0.22, 0.22], + [-0.22, 0.22], + [1.5708, 1.5708], + ], + # 'Piece2': + # [ + # [-0.22, 0.22], + # [-0.22, 0.22], + # [1.5708, 1.5708], + # ] + } + elif self == RobomimicEnvType.THREADING: + return { + 'Needle': + [ + [-0.2, -0.05], + [0.15, 0.25], + [-2. * np.pi / 3., -np.pi / 3.], + ], + 'Tripod': + [ + [0.0, 0.0], + [-0.15, -0.15], + [np.pi / 2., np.pi / 2.], + ] + } + elif self == RobomimicEnvType.TOOL_HANG: + return { + 'standObject': + [ + [-0.08, -0.08], + [0.0, 0.0], + [0.0, 0.0], + ], + 'frameObject': + [ + [-0.02, -0.06], + [-0.26, -0.22], + [(-np.pi / 2) + (np.pi / 6) - np.pi / 18, (-np.pi / 2) + (np.pi / 6) + np.pi / 18], + ], + 'toolObject': + [ + [-0.02, -0.06], + [-0.22, -0.18], + [(-np.pi / 2) - (np.pi / 9.0) - np.pi / 18, (-np.pi / 2) - (np.pi / 9.0) + np.pi / 18], + ], + } + else: + return {} + + def get_simple_name(self): + if self == RobomimicEnvType.NUT_ASSEMBLY_SQUARE: + return 'square' + else: + return self.value.lower() + + def get_surface_ref_pos(self): + # reference pos to pass into Placement Sampler + if self in [RobomimicEnvType.NUT_ASSEMBLY, RobomimicEnvType.NUT_ASSEMBLY_SQUARE, RobomimicEnvType.NUT_ASSEMBLY_ROUND]: + return np.array([0.0, 0.0, 0.82]) + elif self in [RobomimicEnvType.THREE_PIECE_ASSEMBLY, RobomimicEnvType.THREADING]: + return np.array([0.0, 0.0, 0.8]) + elif self == RobomimicEnvType.TOOL_HANG: + return np.array([0.0, 0.0, 0.8]) + else: + return [] + +class IO_Devices(Enum): + KEYBOARD = 'keyboard' + SPACEMOUSE = 'spacemouse' + SPAECMOUSE_ORIGINAL = 'spacemouse_original' + + def get_device(self, pos_sensitivity=1.0, rot_sensitivity=1.0): + if self == IO_Devices.KEYBOARD: + from sim_pipeline.data_collection.keyboard import Keyboard + + device = Keyboard(pos_sensitivity=pos_sensitivity, rot_sensitivity=rot_sensitivity) + elif self == IO_Devices.SPACEMOUSE: + from sim_pipeline.data_collection.spacemouse_hybrid import SpaceMouse as SpaceMouseHybrid + + device = SpaceMouseHybrid(pos_sensitivity=pos_sensitivity, rot_sensitivity=rot_sensitivity) + elif self == IO_Devices.SPAECMOUSE_ORIGINAL: + from robosuite.devices import SpaceMouse + + device = SpaceMouse(pos_sensitivity=pos_sensitivity, rot_sensitivity=rot_sensitivity) + else: + raise ValueError(f"Unknown device {self}") + + return device + +import sim_pipeline +ROOT_DIR = Path(sim_pipeline.__file__).parent +CONFIG_DIR = ROOT_DIR / 'configs' +LOG_DIR = ROOT_DIR / 'logs' +DATA_DIR = ROOT_DIR / 'data' +ROLLOUT_DATA_DIR = DATA_DIR / 'rollout_generated_data' +COMBINED_DATA_DIR = DATA_DIR / 'combined' +DATASET_DB_PATH = ROOT_DIR / 'datasets.db' +MODEL_DB_PATH = ROOT_DIR / 'models.db' + +CALIBRATION_PATH = (Path(__file__).parent.parent.parent.parent / 'weird_franka' / 'weird_franka' / 'perception' / 'cameras' / 'calibration' / + 'logs' / 'default.json') \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/data/base_data.py b/code_src/rise_code/sim_pipeline/configs/data/base_data.py new file mode 100644 index 0000000000000000000000000000000000000000..69b305e6e93c95a3725ca22b7165f469864248c3 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/data/base_data.py @@ -0,0 +1,23 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import RobomimicEnvType +from sim_pipeline.data_manager.dataset_metadata_enums import * + +@dataclass +class BaseDataConfig: + # override dataset_dir if you want to specify the dataset path explicitly + # instead of through the dataset manager + dataset_path: str = '' + + # override these values with the desired query + # empty string is equivalent to None + name: str | None = '' + env_name: str | None = None + env_type: list[str] | None = None + dataset_type: list[str] | None = None + action_type: str | None = None + reward_type: list[str] | None = None + obs_type: ObsType | None = None + + # if true, will not attempt to combine. if multiple datasets are + # returned, just error + do_not_combine: bool = False \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/data/pushing_data.py b/code_src/rise_code/sim_pipeline/configs/data/pushing_data.py new file mode 100644 index 0000000000000000000000000000000000000000..281d3c6f819078e25e4b2a622bc67d9d02189b3d --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/data/pushing_data.py @@ -0,0 +1,19 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import RobomimicEnvType +from sim_pipeline.data_manager.dataset_metadata_enums import * +from sim_pipeline.configs.data.base_data import BaseDataConfig + +@dataclass +class PushingDataConfig(BaseDataConfig): + # override dataset_dir if you want to specify the dataset path explicitly + # instead of through the dataset manager + dataset_path: str = '' + + # override these values with the desired query + name: str | None = 'push_converted' + env_name: str | None = RobomimicEnvType.NUT_ASSEMBLY_SQUARE.value + env_type: list[str] | None = field(default_factory=lambda: [EnvType.ROBOSUITE.value]) + dataset_type: list[str] | None = field(default_factory=lambda: [DatasetType.PLAY.value]) + action_type: str = ActionType.RELATIVE.value + reward_type: list[str] | None = field(default_factory=lambda: [RewardType.DENSE.value]) + obs_type: ObsType = ObsType.STATE \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/data/pushing_data_rew.py b/code_src/rise_code/sim_pipeline/configs/data/pushing_data_rew.py new file mode 100644 index 0000000000000000000000000000000000000000..b49f19682fa45e29008f2a142fce840dc936ed51 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/data/pushing_data_rew.py @@ -0,0 +1,19 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import RobomimicEnvType +from sim_pipeline.data_manager.dataset_metadata_enums import * +from sim_pipeline.configs.data.base_data import BaseDataConfig + +@dataclass +class PushingDataConfig(BaseDataConfig): + # override dataset_dir if you want to specify the dataset path explicitly + # instead of through the dataset manager + dataset_path: str = '' + + # override these values with the desired query + name: str | None = 'push_pushing_reward' + env_name: str | None = RobomimicEnvType.NUT_ASSEMBLY_SQUARE.value + env_type: list[str] | None = field(default_factory=lambda: [EnvType.ROBOSUITE.value]) + dataset_type: list[str] | None = field(default_factory=lambda: [DatasetType.PLAY.value]) + action_type: str = ActionType.RELATIVE.value + reward_type: list[str] | None = field(default_factory=lambda: [RewardType.DENSE.value]) + obs_type: ObsType = ObsType.STATE \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/data/pushing_data_rl.py b/code_src/rise_code/sim_pipeline/configs/data/pushing_data_rl.py new file mode 100644 index 0000000000000000000000000000000000000000..f73ccd41307dec525e9f5de75db0b264288b86e4 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/data/pushing_data_rl.py @@ -0,0 +1,19 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import RobomimicEnvType +from sim_pipeline.data_manager.dataset_metadata_enums import * +from sim_pipeline.configs.data.base_data import BaseDataConfig + +@dataclass +class PushingDataConfig(BaseDataConfig): + # override dataset_dir if you want to specify the dataset path explicitly + # instead of through the dataset manager + dataset_path: str = '' + + # override these values with the desired query + name: str | None = 'test_rl_push_data_converted' + env_name: str | None = RobomimicEnvType.NUT_ASSEMBLY_SQUARE.value + env_type: list[str] | None = None + dataset_type: list[str] | None = field(default_factory=lambda: [DatasetType.RL.value]) + action_type: str = ActionType.RELATIVE.value + reward_type: list[str] | None = None + obs_type: ObsType = ObsType.STATE \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/data/square_expert_image.py b/code_src/rise_code/sim_pipeline/configs/data/square_expert_image.py new file mode 100644 index 0000000000000000000000000000000000000000..266d6f21762f9dc459598a0109dd2d68aa40c33b --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/data/square_expert_image.py @@ -0,0 +1,19 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import RobomimicEnvType +from sim_pipeline.data_manager.dataset_metadata_enums import * +from sim_pipeline.configs.data.base_data import BaseDataConfig + +@dataclass +class PushingDataConfig(BaseDataConfig): + # override dataset_dir if you want to specify the dataset path explicitly + # instead of through the dataset manager + dataset_path: str = '' + + # override these values with the desired query + name: str | None = '' + env_name: str | None = RobomimicEnvType.NUT_ASSEMBLY_SQUARE.value + env_type: list[str] | None = field(default_factory=lambda: [EnvType.ROBOMIMIC.value]) + dataset_type: list[str] | None = field(default_factory=lambda: [DatasetType.PH.value]) + action_type: str = ActionType.RELATIVE.value + reward_type: list[str] | None = field(default_factory=lambda: [RewardType.SPARSE.value]) + obs_type: ObsType = ObsType.IMAGE \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/data/square_expert_lowdim.py b/code_src/rise_code/sim_pipeline/configs/data/square_expert_lowdim.py new file mode 100644 index 0000000000000000000000000000000000000000..e18888f3516a0a015141cb72e7453e2325c4ae46 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/data/square_expert_lowdim.py @@ -0,0 +1,19 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import RobomimicEnvType +from sim_pipeline.data_manager.dataset_metadata_enums import * +from sim_pipeline.configs.data.base_data import BaseDataConfig + +@dataclass +class PushingDataConfig(BaseDataConfig): + # override dataset_dir if you want to specify the dataset path explicitly + # instead of through the dataset manager + dataset_path: str = '' + + # override these values with the desired query + name: str | None = '' + env_name: str | None = RobomimicEnvType.NUT_ASSEMBLY_SQUARE.value + env_type: list[str] | None = field(default_factory=lambda: [EnvType.ROBOMIMIC.value]) + dataset_type: list[str] | None = field(default_factory=lambda: [DatasetType.PH.value]) + action_type: str = ActionType.RELATIVE.value + reward_type: list[str] | None = field(default_factory=lambda: [RewardType.DENSE.value]) + obs_type: ObsType = ObsType.STATE \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/default.py b/code_src/rise_code/sim_pipeline/configs/default.py new file mode 100644 index 0000000000000000000000000000000000000000..036aeb567a4bb5e61e7f25db8ca0c944a05a80f7 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/default.py @@ -0,0 +1,15 @@ +from dataclasses import dataclass +from typing import Any +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.data.base_data import BaseDataConfig +from sim_pipeline.configs.exp.base import BaseExpConfig +from sim_pipeline.configs.training._reinforcement_learning.base_rl import RLTrainingConfig + +@dataclass +class TopLevelConfig: + name: str = 'default_exp' + debug: bool = False + env: Any = BaseEnvConfig() + exp: Any = BaseExpConfig() + training: Any = RLTrainingConfig() + data: BaseDataConfig = BaseDataConfig() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/diffusion_base_configs/image_square_cnn.yaml b/code_src/rise_code/sim_pipeline/configs/diffusion_base_configs/image_square_cnn.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6ec8567e89facade2ba693d8d05399f5f69cccd0 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/diffusion_base_configs/image_square_cnn.yaml @@ -0,0 +1,273 @@ +_target_: diffusion_policy.workspace.train_diffusion_unet_hybrid_workspace.TrainDiffusionUnetHybridWorkspace +checkpoint: + save_last_ckpt: true + save_last_snapshot: false + topk: + format_str: epoch={epoch:04d}-test_mean_score={test_mean_score:.3f}.ckpt + k: 5 + mode: max + monitor_key: test_mean_score +dataloader: + batch_size: 64 + num_workers: 8 + persistent_workers: false + pin_memory: true + shuffle: true +dataset_obs_steps: 2 +ema: + _target_: diffusion_policy.model.diffusion.ema_model.EMAModel + inv_gamma: 1.0 + max_value: 0.9999 + min_value: 0.0 + power: 0.75 + update_after_step: 0 +exp_name: default +horizon: 16 +keypoint_visible_rate: 1.0 +logging: + group: null + id: null + mode: online + name: 2022.12.29-22.31.34_train_diffusion_unet_hybrid_square_image + project: diffusion_policy_debug + resume: true + tags: + - train_diffusion_unet_hybrid + - square_image + - default +multi_run: + run_dir: data/outputs/2022.12.29/22.31.34_train_diffusion_unet_hybrid_square_image + wandb_name_base: 2022.12.29-22.31.34_train_diffusion_unet_hybrid_square_image +n_action_steps: 8 +n_latency_steps: 0 +n_obs_steps: 2 +name: train_diffusion_unet_hybrid +obs_as_global_cond: true +optimizer: + _target_: torch.optim.AdamW + betas: + - 0.95 + - 0.999 + eps: 1.0e-08 + lr: 0.0001 + weight_decay: 1.0e-06 +past_action_visible: false +policy: + _target_: diffusion_policy.policy.diffusion_unet_hybrid_image_policy.DiffusionUnetHybridImagePolicy + cond_predict_scale: true + crop_shape: + - 76 + - 76 + diffusion_step_embed_dim: 128 + down_dims: + - 512 + - 1024 + - 2048 + eval_fixed_crop: true + horizon: 16 + kernel_size: 5 + n_action_steps: 8 + n_groups: 8 + n_obs_steps: 2 + noise_scheduler: + _target_: diffusers.schedulers.scheduling_ddim.DDIMScheduler + beta_end: 0.02 + beta_schedule: squaredcos_cap_v2 + beta_start: 0.0001 + clip_sample: true + num_train_timesteps: 100 + prediction_type: epsilon + num_inference_steps: 10 + obs_as_global_cond: true + obs_encoder_group_norm: true + shape_meta: + action: + shape: + - 7 + obs: + agentview_image: + shape: + - 3 + - 84 + - 84 + type: rgb + robot0_eef_pos: + shape: + - 3 + robot0_eef_quat: + shape: + - 4 + robot0_eye_in_hand_image: + shape: + - 3 + - 84 + - 84 + type: rgb + robot0_gripper_qpos: + shape: + - 2 +shape_meta: + action: + shape: + - 7 + obs: + agentview_image: + shape: + - 3 + - 84 + - 84 + type: rgb + robot0_eef_pos: + shape: + - 3 + robot0_eef_quat: + shape: + - 4 + robot0_eye_in_hand_image: + shape: + - 3 + - 84 + - 84 + type: rgb + robot0_gripper_qpos: + shape: + - 2 +task: + abs_action: false + dataset: + _target_: diffusion_policy.dataset.robomimic_replay_image_dataset.RobomimicReplayImageDataset + abs_action: false + dataset_path: /home/kevin/ood/robomimic/datasets/square/ph/image.hdf5 + horizon: 16 + n_obs_steps: 2 + pad_after: 7 + pad_before: 1 + rotation_rep: rotation_6d + seed: 42 + shape_meta: + action: + shape: + - 7 + obs: + agentview_image: + shape: + - 3 + - 84 + - 84 + type: rgb + robot0_eef_pos: + shape: + - 3 + robot0_eef_quat: + shape: + - 4 + robot0_eye_in_hand_image: + shape: + - 3 + - 84 + - 84 + type: rgb + robot0_gripper_qpos: + shape: + - 2 + use_cache: true + val_ratio: 0.02 + dataset_path: /home/kevin/ood/robomimic/datasets/square/ph/image.hdf5 + dataset_type: ph + env_runner: + _target_: diffusion_policy.env_runner.robomimic_image_runner.RobomimicImageRunner + abs_action: false + crf: 22 + dataset_path: /home/kevin/ood/robomimic/datasets/square/ph/image.hdf5 + fps: 10 + max_steps: 400 + n_action_steps: 8 + n_envs: 4 + n_obs_steps: 2 + n_test: 3 + n_test_vis: 3 + n_train: 1 + n_train_vis: 1 + past_action: false + render_obs_key: agentview_image + shape_meta: + action: + shape: + - 7 + obs: + agentview_image: + shape: + - 3 + - 84 + - 84 + type: rgb + robot0_eef_pos: + shape: + - 3 + robot0_eef_quat: + shape: + - 4 + robot0_eye_in_hand_image: + shape: + - 3 + - 84 + - 84 + type: rgb + robot0_gripper_qpos: + shape: + - 2 + test_start_seed: 100000 + tqdm_interval_sec: 1.0 + train_start_idx: 0 + name: square_image + shape_meta: + action: + shape: + - 7 + obs: + agentview_image: + shape: + - 3 + - 84 + - 84 + type: rgb + robot0_eef_pos: + shape: + - 3 + robot0_eef_quat: + shape: + - 4 + robot0_eye_in_hand_image: + shape: + - 3 + - 84 + - 84 + type: rgb + robot0_gripper_qpos: + shape: + - 2 + task_name: square +task_name: square_image +training: + checkpoint_every: 50 + debug: false + device: cuda:0 + gradient_accumulate_every: 1 + lr_scheduler: cosine + lr_warmup_steps: 500 + max_train_steps: null + max_val_steps: null + num_epochs: 8000 + resume: true + rollout_every: 50 + sample_every: 5 + seed: 42 + tqdm_interval_sec: 1.0 + use_ema: true + val_every: 1 +val_dataloader: + batch_size: 64 + num_workers: 8 + persistent_workers: false + pin_memory: true + shuffle: false diff --git a/code_src/rise_code/sim_pipeline/configs/diffusion_base_configs/lowdim_square_cnn.yaml b/code_src/rise_code/sim_pipeline/configs/diffusion_base_configs/lowdim_square_cnn.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b413978fcda9fd915d58b34b95fe4ec636c2827c --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/diffusion_base_configs/lowdim_square_cnn.yaml @@ -0,0 +1,171 @@ +_target_: diffusion_policy.workspace.train_diffusion_unet_lowdim_workspace.TrainDiffusionUnetLowdimWorkspace +action_dim: 7 +checkpoint: + save_last_ckpt: true + save_last_snapshot: false + topk: + format_str: epoch={epoch:04d}-test_mean_score={test_mean_score:.3f}.ckpt + k: 5 + mode: max + monitor_key: test_mean_score +dataloader: + batch_size: 256 + num_workers: 1 + persistent_workers: false + pin_memory: true + shuffle: true +ema: + _target_: diffusion_policy.model.diffusion.ema_model.EMAModel + inv_gamma: 1.0 + max_value: 0.9999 + min_value: 0.0 + power: 0.75 + update_after_step: 0 +exp_name: obs_global_rerun +horizon: 16 +keypoint_dim: 3 +keypoint_visible_rate: 1.0 +logging: + group: null + id: null + mode: online + name: 2023.02.23-19.51.08_train_diffusion_unet_lowdim_square_lowdim + project: diffusion_policy_debug + resume: true + tags: + - train_diffusion_unet_lowdim + - square_lowdim + - obs_global_rerun +multi_run: + run_dir: data/outputs/2023.02.23/19.51.08_train_diffusion_unet_lowdim_square_lowdim + wandb_name_base: 2023.02.23-19.51.08_train_diffusion_unet_lowdim_square_lowdim +n_action_steps: 8 +n_latency_steps: 0 +n_obs_steps: 2 +name: train_diffusion_unet_lowdim +obs_as_global_cond: true +obs_as_local_cond: false +obs_dim: 23 +optimizer: + _target_: torch.optim.AdamW + betas: + - 0.95 + - 0.999 + eps: 1.0e-08 + lr: 0.0001 + weight_decay: 1.0e-06 +past_action_visible: false +policy: + _target_: diffusion_policy.policy.diffusion_unet_lowdim_policy.DiffusionUnetLowdimPolicy + action_dim: 7 + horizon: 16 + model: + _target_: diffusion_policy.model.diffusion.conditional_unet1d.ConditionalUnet1D + cond_predict_scale: true + diffusion_step_embed_dim: 256 + down_dims: + - 256 + - 512 + - 1024 + global_cond_dim: 46 + input_dim: 7 + kernel_size: 5 + local_cond_dim: null + n_groups: 8 + n_action_steps: 8 + n_obs_steps: 2 + noise_scheduler: + _target_: diffusers.schedulers.scheduling_ddim.DDIMScheduler + beta_end: 0.02 + beta_schedule: squaredcos_cap_v2 + beta_start: 0.0001 + clip_sample: true + num_train_timesteps: 100 + prediction_type: epsilon + num_inference_steps: 10 + oa_step_convention: true + obs_as_global_cond: true + obs_as_local_cond: false + obs_dim: 23 + pred_action_steps_only: false +pred_action_steps_only: false +task: + abs_action: false + action_dim: 7 + dataset: + _target_: diffusion_policy.dataset.robomimic_replay_lowdim_dataset.RobomimicReplayLowdimDataset + abs_action: false + dataset_path: /home/kevin/ood/sim_pipeline/sim_pipeline/data/rollout_generated_data/push_rl_stable_converted.hdf5 + horizon: 16 + max_train_episodes: null + obs_keys: + - object + - robot0_eef_pos + - robot0_eef_quat + - robot0_gripper_qpos + pad_after: 7 + pad_before: 1 + seed: 42 + use_legacy_normalizer: false + val_ratio: 0.02 + dataset_path: /home/kevin/ood/sim_pipeline/sim_pipeline/data/rollout_generated_data/push_rl_stable_converted.hdf5 + dataset_type: ph + env_runner: + _target_: diffusion_policy.env_runner.robomimic_lowdim_runner.RobomimicLowdimRunner + abs_action: false + crf: 22 + dataset_path: /home/kevin/ood/sim_pipeline/sim_pipeline/data/rollout_generated_data/push_rl_stable_converted.hdf5 + fps: 10 + max_steps: 400 + n_action_steps: 8 + n_envs: 28 + n_latency_steps: 0 + n_obs_steps: 2 + n_test: 50 + n_test_vis: 4 + n_train: 6 + n_train_vis: 2 + obs_keys: + - object + - robot0_eef_pos + - robot0_eef_quat + - robot0_gripper_qpos + past_action: false + render_hw: + - 128 + - 128 + test_start_seed: 100000 + train_start_idx: 0 + keypoint_dim: 3 + name: square_lowdim + obs_dim: 23 + obs_keys: + - object + - robot0_eef_pos + - robot0_eef_quat + - robot0_gripper_qpos + task_name: square +task_name: square_lowdim +training: + checkpoint_every: 50 + debug: false + device: cuda:0 + gradient_accumulate_every: 1 + lr_scheduler: cosine + lr_warmup_steps: 500 + max_train_steps: null + max_val_steps: null + num_epochs: 5000 + resume: true + rollout_every: 50 + sample_every: 5 + seed: 42 + tqdm_interval_sec: 1.0 + use_ema: true + val_every: 1 +val_dataloader: + batch_size: 256 + num_workers: 1 + persistent_workers: false + pin_memory: true + shuffle: false diff --git a/code_src/rise_code/sim_pipeline/configs/diffusion_base_configs/lowdim_square_cnn_tycho.yaml b/code_src/rise_code/sim_pipeline/configs/diffusion_base_configs/lowdim_square_cnn_tycho.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3552efd95ab91cf1cf809a6bcda76ae99c4f02b8 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/diffusion_base_configs/lowdim_square_cnn_tycho.yaml @@ -0,0 +1,165 @@ +_target_: diffusion_policy.workspace.train_diffusion_unet_lowdim_workspace.TrainDiffusionUnetLowdimWorkspace +action_dim: 8 +checkpoint: + save_last_ckpt: true + save_last_snapshot: false + topk: + format_str: epoch={epoch:04d}-test_mean_score={test_mean_score:.3f}.ckpt + k: 5 + mode: max + monitor_key: test_mean_score +dataloader: + batch_size: 256 + num_workers: 1 + persistent_workers: false + pin_memory: true + shuffle: true +ema: + _target_: diffusion_policy.model.diffusion.ema_model.EMAModel + inv_gamma: 1.0 + max_value: 0.9999 + min_value: 0.0 + power: 0.75 + update_after_step: 0 +exp_name: obs_global_rerun +horizon: 16 +keypoint_dim: 3 +keypoint_visible_rate: 1.0 +logging: + group: null + id: null + mode: online + name: 2023.02.23-19.51.08_train_diffusion_unet_lowdim_square_lowdim + project: diffusion_policy_debug + resume: true + tags: + - train_diffusion_unet_lowdim + - square_lowdim + - obs_global_rerun +multi_run: + run_dir: data/outputs/2023.02.23/19.51.08_train_diffusion_unet_lowdim_square_lowdim + wandb_name_base: 2023.02.23-19.51.08_train_diffusion_unet_lowdim_square_lowdim +n_action_steps: 8 +n_latency_steps: 0 +n_obs_steps: 2 +name: train_diffusion_unet_lowdim +obs_as_global_cond: true +obs_as_local_cond: false +obs_dim: 11 +optimizer: + _target_: torch.optim.AdamW + betas: + - 0.95 + - 0.999 + eps: 1.0e-08 + lr: 0.0001 + weight_decay: 1.0e-06 +past_action_visible: false +policy: + _target_: diffusion_policy.policy.diffusion_unet_lowdim_policy.DiffusionUnetLowdimPolicy + action_dim: 8 + horizon: 16 + model: + _target_: diffusion_policy.model.diffusion.conditional_unet1d.ConditionalUnet1D + cond_predict_scale: true + diffusion_step_embed_dim: 256 + down_dims: + - 256 + - 512 + - 1024 + global_cond_dim: 22 + input_dim: 8 + kernel_size: 5 + local_cond_dim: null + n_groups: 8 + n_action_steps: 8 + n_obs_steps: 2 + noise_scheduler: + _target_: diffusers.schedulers.scheduling_ddim.DDIMScheduler + beta_end: 0.02 + beta_schedule: squaredcos_cap_v2 + beta_start: 0.0001 + clip_sample: true + num_train_timesteps: 100 + prediction_type: epsilon + num_inference_steps: 10 + oa_step_convention: true + obs_as_global_cond: true + obs_as_local_cond: false + obs_dim: 11 + pred_action_steps_only: false +pred_action_steps_only: false +task: + abs_action: false + action_dim: 8 + dataset: + _target_: diffusion_policy.dataset.robomimic_replay_lowdim_dataset.RobomimicReplayLowdimDataset + abs_action: false + dataset_path: /home/kevin/ood/sim_pipeline/sim_pipeline/data/rollout_generated_data/push_rl_stable_converted.hdf5 + horizon: 16 + max_train_episodes: null + obs_keys: + - object + - robot0_eef_pos + - robot0_eef_quat + - robot0_gripper_qpos + pad_after: 7 + pad_before: 1 + seed: 42 + use_legacy_normalizer: false + val_ratio: 0.02 + dataset_path: /home/kevin/ood/sim_pipeline/sim_pipeline/data/rollout_generated_data/push_rl_stable_converted.hdf5 + dataset_type: ph + env_runner: + _target_: diffusion_policy.env_runner.robomimic_lowdim_runner.RobomimicLowdimRunner + abs_action: false + crf: 22 + dataset_path: /home/kevin/ood/sim_pipeline/sim_pipeline/data/rollout_generated_data/push_rl_stable_converted.hdf5 + fps: 10 + max_steps: 400 + n_action_steps: 8 + n_envs: 28 + n_latency_steps: 0 + n_obs_steps: 2 + n_test: 50 + n_test_vis: 4 + n_train: 6 + n_train_vis: 2 + obs_keys: + - states + past_action: false + render_hw: + - 128 + - 128 + test_start_seed: 100000 + train_start_idx: 0 + keypoint_dim: 3 + name: square_lowdim + obs_dim: 11 + obs_keys: + - states + task_name: square +task_name: square_lowdim +training: + checkpoint_every: 50 + debug: false + device: cuda:0 + gradient_accumulate_every: 1 + lr_scheduler: cosine + lr_warmup_steps: 500 + max_train_steps: null + max_val_steps: null + num_epochs: 5000 + resume: true + rollout_every: 50 + sample_every: 5 + seed: 42 + tqdm_interval_sec: 1.0 + use_ema: true + val_every: 1 +val_dataloader: + batch_size: 256 + num_workers: 1 + persistent_workers: false + pin_memory: true + shuffle: false diff --git a/code_src/rise_code/sim_pipeline/configs/env/base.py b/code_src/rise_code/sim_pipeline/configs/env/base.py new file mode 100644 index 0000000000000000000000000000000000000000..60a283623d2ac3a5a9e9451e5d110182194c05d1 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/base.py @@ -0,0 +1,9 @@ +from dataclasses import dataclass +from omegaconf import MISSING +from sim_pipeline.configs.constants import EnvType + +@dataclass +class BaseEnvConfig: + env_type: EnvType = MISSING + + diff --git a/code_src/rise_code/sim_pipeline/configs/env/franka_base.py b/code_src/rise_code/sim_pipeline/configs/env/franka_base.py new file mode 100644 index 0000000000000000000000000000000000000000..12974757b0d925fb4ff6ac5412a961c4a700fed5 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/franka_base.py @@ -0,0 +1,29 @@ +from dataclasses import dataclass, field +from typing import Dict, Tuple +from sim_pipeline.configs.constants import EnvType + +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.robot.base_franka import RobotConfigFranka + +@dataclass +class EnvConfigFranka(BaseEnvConfig): + env_type: EnvType = EnvType.FRANKA + obj_id: str = "cube" + obj_pos_noise: bool = True + goal_obj_delta_pose: Dict[str, float] = field(default_factory=lambda: + { + "x": 0.25, + # "y": 0.0, + }) + obj_pose_noise_dict: Dict[str, Dict[str, float]] = field(default_factory=lambda: + { + "x": { "min": 0.00, "max": 0.00 }, + "y": { "min": 0.0, "max": 0.0 }, + "yaw": { "min": 0.0, "max": 0.0 }, + }) + safety_penalty: float = 0.0 + obs_keys: Tuple[str] = ("lowdim_ee", "lowdim_qpos", "obj_pose") + flatten: bool = True + + robot_config: RobotConfigFranka = RobotConfigFranka() + diff --git a/code_src/rise_code/sim_pipeline/configs/env/franka_cube.py b/code_src/rise_code/sim_pipeline/configs/env/franka_cube.py new file mode 100644 index 0000000000000000000000000000000000000000..a99f5430f31b32c827311d7af2e1f14604194072 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/franka_cube.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass, field +from typing import Dict +from sim_pipeline.configs.env.franka_base import EnvConfigFranka + +@dataclass +class EnvConfigFrankaCube(EnvConfigFranka): + obj_id: str = "cube" + obj_pose_noise_dict: Dict[str, Dict[str, float]] = field(default_factory=lambda: + { + "x": { "min": -0.02, "max": 0.05 }, + "y": { "min": -0.25, "max": 0.25 }, + "yaw": { "min": 0.0, "max": 1.5 }, + }) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/env/iterate_square_nut_configs_and_plot.py b/code_src/rise_code/sim_pipeline/configs/env/iterate_square_nut_configs_and_plot.py new file mode 100644 index 0000000000000000000000000000000000000000..2f97c13b0ac604bcfca9bdcb420e6219328b2058 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/iterate_square_nut_configs_and_plot.py @@ -0,0 +1,120 @@ +import os +import ast +import matplotlib.pyplot as plt +from matplotlib.patches import Rectangle +import colorsys +import random + +def extract_squarenut_range(file_path): + try: + with open(file_path, 'r') as file: + content = file.read() + tree = ast.parse(content) + for node in ast.walk(tree): + if isinstance(node, ast.Dict): + for key, value in zip(node.keys, node.values): + if isinstance(key, ast.Str) and key.s == 'SquareNut': + if isinstance(value, ast.List) and len(value.elts) == 2: + x_range = ast.literal_eval(value.elts[0]) + y_range = ast.literal_eval(value.elts[1]) + return x_range, y_range + except Exception as e: + print(f"Error processing file {file_path}: {str(e)}") + return None, None + +def generate_distinct_colors(n): + colors = [] + for i in range(n): + hue = i / n + saturation = 0.7 + (i % 3) * 0.1 # Slight variation in saturation + lightness = 0.4 + (i % 2) * 0.1 # Slight variation in lightness + rgb = colorsys.hls_to_rgb(hue, lightness, saturation) + colors.append(rgb) + return colors + +def plot_ranges(directory=None): + if directory is None: + directory = os.path.dirname(os.path.abspath(__file__)) + + fig, ax = plt.subplots(figsize=(12, 12)) + ax.set_xlim(-0.3, 0.3) + ax.set_ylim(-0.3, 0.3) + ax.set_xlabel('X') + ax.set_ylabel('Y') + ax.set_title('SquareNut Ranges') + + # Get list of files and generate colors + files = [f for f in os.listdir(directory) if f.endswith('.py')] + colors = generate_distinct_colors(len(files)) + + # List to keep track of all label positions and bounding boxes + label_positions = [] + bounding_boxes = [] + + for filename, color in zip(files, colors): + file_path = os.path.join(directory, filename) + x_range, y_range = extract_squarenut_range(file_path) + + if x_range and y_range: + width = x_range[1] - x_range[0] + height = y_range[1] - y_range[0] + + # Check for overlap and apply x-jitter if necessary + x_jitter = 0 + for existing_box in bounding_boxes: + if (existing_box[0] <= x_range[0] <= existing_box[1] or + existing_box[0] <= x_range[1] <= existing_box[1] or + x_range[0] <= existing_box[0] <= x_range[1]) and \ + (existing_box[2] <= y_range[0] <= existing_box[3] or + existing_box[2] <= y_range[1] <= existing_box[3] or + y_range[0] <= existing_box[2] <= y_range[1]): + x_jitter = random.uniform(-0.01, 0.01) + break + + # Apply the x-jitter to the bounding box + x_range = (x_range[0] + x_jitter, x_range[1] + x_jitter) + + rect = Rectangle((x_range[0], y_range[0]), width, height, + fill=False, edgecolor=color, linewidth=2) + ax.add_patch(rect) + + # Add the new bounding box to the list + bounding_boxes.append((x_range[0], x_range[1], y_range[0], y_range[1])) + + # Initial label position + label_x = x_range[1] + label_y = y_range[1] + + # Apply iterative jitter to labels + jitter_attempts = 0 + while jitter_attempts < 50: # Limit attempts to prevent infinite loop + overlap = False + for pos in label_positions: + if abs(pos[0] - label_x) < 0.03 and abs(pos[1] - label_y) < 0.03: + overlap = True + break + + if not overlap: + break + + # If overlap, apply additional jitter + label_x += random.uniform(0.01, 0.03) * (1 if random.random() > 0.5 else -1) + label_y += random.uniform(0.01, 0.03) * (1 if random.random() > 0.5 else -1) + jitter_attempts += 1 + + label_positions.append((label_x, label_y)) + + ax.text(label_x, label_y, filename, fontsize=8, + color=color, fontweight='bold', + verticalalignment='bottom', + horizontalalignment='left', + bbox=dict(facecolor='white', edgecolor='none', alpha=0.7)) + else: + print(f"Skipping file {filename}: No SquareNut field found or invalid format") + + plt.grid(True) + plt.tight_layout() + plt.show() + +if __name__ == '__main__': + plot_ranges(os.path.dirname(os.path.abspath(__file__))) diff --git a/code_src/rise_code/sim_pipeline/configs/env/point_maze.py b/code_src/rise_code/sim_pipeline/configs/env/point_maze.py new file mode 100644 index 0000000000000000000000000000000000000000..663c9d087c2e867e34b5a64744f2f0ca6aab656d --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/point_maze.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass, field +from typing import Dict, Tuple +from sim_pipeline.configs.constants import EnvType + +from sim_pipeline.configs.env.base import BaseEnvConfig + +@dataclass +class EnvConfigPointMaze(BaseEnvConfig): + env_type: EnvType = EnvType.POINT_MAZE + + maze_id: str = 'train_easy' + render_mode: str = 'rgb_array' + max_ep_steps: int = 1000 + reward_type: str = 'sparse' diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_base.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_base.py new file mode 100644 index 0000000000000000000000000000000000000000..4535fa1fc79de9a256b429d4229cea338ff14c00 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_base.py @@ -0,0 +1,67 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import EnvType +from sim_pipeline.configs.constants import RobomimicEnvType +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.data_manager.dataset_metadata_enums import ObsType +from sim_pipeline.reward_functions import RewardFunction + +@dataclass +class RobomimicEnvConfig(BaseEnvConfig): + env_type: EnvType = EnvType.ROBOMIMIC + env_name: RobomimicEnvType = RobomimicEnvType.NUT_ASSEMBLY_SQUARE + + # whether to render in window + render: bool = True + render_offscreen: bool = False + + ignore_done: bool = False + # len of episode, no effect if ignore_done is True + horizon: int = 200 + + # use robosuite instead of robomimic wrapper when doing data collection + data_collection: bool = False + + # obs keys that are included in flattened observations (only applicable to RL currently) + obs_keys: list[str] = field(default_factory=lambda: [ + 'eef_pos', + 'eef_quat', + 'gripper_qpos', + 'object-state', + ]) + # names of cameras to render. only used if obs_type includes images/depth + camera_names: list[str] = field(default_factory=lambda: [ + 'agentview', + 'robot0_eye_in_hand' + ]) + # determines whether or not env should return images as part of its obs dict + obs_type: ObsType = ObsType.IMAGE + # custom reward + reward_function: RewardFunction | None = None + + ## Initialization Config + + custom_ee_init: bool = False + # x, y, z, [min, max] (default robomimic values are listed here) + init_ee_range: list[list[float]] = field(default_factory=lambda: [ + [-0.1031, -0.103], + [-0.0035, -0.0034], + [1.0174, 1.0175] + ]) + custom_obj_init: bool = False + # rsm_rise: per-object rotation axis for the placement sampler ('z' = flat, the release's hard-coded value; + # 'x' / 'y' put the object on its side, used by the piece-assembly "tipping" eval env) + init_obj_rotation_axis: dict[str, str] = field(default_factory=lambda: {}) + # rsm_rise: per-object z offset override for the placement sampler (metres above the reference surface) + init_obj_z_offset: dict[str, float] = field(default_factory=lambda: {}) + # rsm_rise: JSON with {"episodes": [{"state0": [...]}]} -> every eval episode resets to one of these sim states + # (drawn with the eval seed); reproduces a dataset's initial-state distribution exactly (used by the tipping eval env) + reset_states_file: str | None = None + init_obj_range: dict[str, list[list[float]]] = field(default_factory=lambda: + { + 'SquareNut': + [ + [0, 0.12], + [-0.225, 0.0], + + ], + }) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_coffee.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_coffee.py new file mode 100644 index 0000000000000000000000000000000000000000..151a4423fead266bfd204bb2f4fb4c597674cfcd --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_coffee.py @@ -0,0 +1,10 @@ +import numpy as np +from dataclasses import dataclass, field +from typing import Dict, List +from sim_pipeline.configs.constants import RobomimicEnvType +from sim_pipeline.configs.env.robomimic_base import RobomimicEnvConfig + +@dataclass +class RobomimicCoffeeEnvConfig(RobomimicEnvConfig): + env_name: RobomimicEnvType = RobomimicEnvType.COFFEE + render_offscreen: bool = True diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_mug.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_mug.py new file mode 100644 index 0000000000000000000000000000000000000000..ca21b543c95ebe86010fc0f2c74551232aa6e77e --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_mug.py @@ -0,0 +1,10 @@ +import numpy as np +from dataclasses import dataclass, field +from typing import Dict, List +from sim_pipeline.configs.constants import RobomimicEnvType +from sim_pipeline.configs.env.robomimic_base import RobomimicEnvConfig + +@dataclass +class RobomimicMugEnvConfig(RobomimicEnvConfig): + env_name: RobomimicEnvType = RobomimicEnvType.MUG_CLEANUP + render_offscreen: bool = True diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_square.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square.py new file mode 100644 index 0000000000000000000000000000000000000000..75fca76ad78bc3d1cb4cbcbc5f588ba577c04322 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square.py @@ -0,0 +1,9 @@ +from dataclasses import dataclass, field +from typing import Dict, List +from sim_pipeline.configs.constants import RobomimicEnvType +from sim_pipeline.configs.env.robomimic_base import RobomimicEnvConfig + +@dataclass +class RobomimicSquareEnvConfig(RobomimicEnvConfig): + env_name: RobomimicEnvType = RobomimicEnvType.NUT_ASSEMBLY_SQUARE + render_offscreen: bool = True \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_coverage.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..8448ee37c44328578e520991b3bcc41e69cf64cf --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_coverage.py @@ -0,0 +1,21 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig + +@dataclass +class RobomimicSquareEnvOODConfig(RobomimicSquareEnvConfig): + custom_ee_init: bool = False + # x, y, z, [min, max] + init_ee_range: list[list[float]] = field(default_factory=lambda: [ + [-0.12, -0.08], + [-0.1, 0.05], + [0.9, 1.012] + ]) + custom_obj_init: bool = True + init_obj_range: dict[str, list[list[float]]] = field(default_factory=lambda: + { + 'SquareNut': + [ + [-0.16, 0.16], + [-0.2, 0.2], + ], + }) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_coverage_hook.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_coverage_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..a6181dabc02171ed7169c0c51a29e07ef6828f30 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_coverage_hook.py @@ -0,0 +1,21 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig + +@dataclass +class RobomimicSquareEnvOODConfig(RobomimicSquareEnvConfig): + custom_ee_init: bool = False + # x, y, z, [min, max] + init_ee_range: list[list[float]] = field(default_factory=lambda: [ + [-0.12, -0.08], + [-0.1, 0.05], + [0.9, 1.012] + ]) + custom_obj_init: bool = True + init_obj_range: dict[str, list[list[float]]] = field(default_factory=lambda: + { + 'SquareNut': + [ + [-0.09, 0.20], + [-0.10, 0.21], + ], + }) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_coverage_pure_pushing.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_coverage_pure_pushing.py new file mode 100644 index 0000000000000000000000000000000000000000..26dca4e15703d6bf67667901c70ccddc24c219c2 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_coverage_pure_pushing.py @@ -0,0 +1,12 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.env.robomimic_square_coverage import RobomimicSquareEnvOODConfig +from sim_pipeline.reward_functions import RewardFunction +from sim_pipeline.success_functions import SuccessFunction + +@dataclass +class PushingRobomimicSquareEnvConfig(RobomimicSquareEnvOODConfig): + custom_ee_init: bool = False + + horizon = 300 + reward_function: RewardFunction | None = RewardFunction.SQUARE_REWARD_PUSHING_REWARD #RewardFunction.SQUARE_REWARD_REACH_AND_PUSH_REWARD + success_function: SuccessFunction | None = SuccessFunction.SQUARE_SUCCESS_PUSHING_SUCCESS diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_coverage_pushing.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_coverage_pushing.py new file mode 100644 index 0000000000000000000000000000000000000000..a37473fd6c61bc20da5608088aab955a698a22cc --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_coverage_pushing.py @@ -0,0 +1,12 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.env.robomimic_square_coverage import RobomimicSquareEnvOODConfig +from sim_pipeline.reward_functions import RewardFunction +from sim_pipeline.success_functions import SuccessFunction + +@dataclass +class PushingRobomimicSquareEnvConfig(RobomimicSquareEnvOODConfig): + custom_ee_init: bool = False + + horizon = 300 + reward_function: RewardFunction | None = RewardFunction.SQUARE_REWARD_STABLE_PUSHING_REWARD #RewardFunction.SQUARE_REWARD_REACH_AND_PUSH_REWARD + success_function: SuccessFunction | None = SuccessFunction.SQUARE_SUCCESS_PUSHING_SUCCESS diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_ee_ood.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_ee_ood.py new file mode 100644 index 0000000000000000000000000000000000000000..b31fa7d383dd0bd19696d01829f74634e000fc3b --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_ee_ood.py @@ -0,0 +1,12 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig + +@dataclass +class RobommimicSquareEEOODEnvConfig(RobomimicSquareEnvConfig): + custom_ee_init: bool = True + # x, y, z, [min, max] + init_ee_range: list[list[float]] = field(default_factory=lambda: [ + [-0.32, -0.34], + [0.34, 0.35], + [0.65, 0.65] + ]) diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_image.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_image.py new file mode 100644 index 0000000000000000000000000000000000000000..a8e5ad9fcaa690201aa7413e965d676e2d08c808 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_image.py @@ -0,0 +1,12 @@ +from dataclasses import dataclass, field +from typing import Dict, List +from sim_pipeline.configs.constants import RobomimicEnvType +from sim_pipeline.data_manager.dataset_metadata_enums import ObsType +from sim_pipeline.configs.env.robomimic_base import RobomimicEnvConfig + +@dataclass +class RobomimicSquareImageEnvConfig(RobomimicEnvConfig): + env_name: RobomimicEnvType = RobomimicEnvType.NUT_ASSEMBLY_SQUARE + render_offscreen: bool = True + + obs_type: ObsType = ObsType.IMAGE \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_image_ood.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_image_ood.py new file mode 100644 index 0000000000000000000000000000000000000000..15854a324dc068ad30856c8b3152a1fe617330ff --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_image_ood.py @@ -0,0 +1,22 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.env.robomimic_square_image import RobomimicSquareImageEnvConfig + +@dataclass +class RobommimicSquareImageEnvOODConfig(RobomimicSquareImageEnvConfig): + custom_ee_init: bool = False + # x, y, z, [min, max] + init_ee_range: list[list[float]] = field(default_factory=lambda: [ + [-0.12, -0.08], + [-0.1, 0.05], + [0.9, 1.012] + ]) + custom_obj_init: bool = True + init_obj_range: dict[str, list[list[float]]] = field(default_factory=lambda: + { + 'SquareNut': + [ + [-0.115, -0.09], + [-0.12, 0.11], + + ], + }) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_init_left.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_init_left.py new file mode 100644 index 0000000000000000000000000000000000000000..bd470ba9445791c8f725012f6308d3859cf9c4f1 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_init_left.py @@ -0,0 +1,22 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig + +@dataclass +class LeftRobomimicSquareEnvConfig(RobomimicSquareEnvConfig): + custom_ee_init: bool = False + # x, y, z, [min, max] + init_ee_range: list[list[float]] = field(default_factory=lambda: [ + [-0.12, -0.08], + [-0.1, 0.05], + [0.9, 1.012] + ]) + custom_obj_init: bool = True + init_obj_range: dict[str, list[list[float]]] = field(default_factory=lambda: + { + 'SquareNut': + [ + [-0.08, 0.03], + [-0.075, -0.045], + + ], + }) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_init_ood_center.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_init_ood_center.py new file mode 100644 index 0000000000000000000000000000000000000000..a59e180f1a3561402cd2372c444a2dea1907a5a1 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_init_ood_center.py @@ -0,0 +1,22 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig + +@dataclass +class LLOODRobomimicSquareEnvConfig(RobomimicSquareEnvConfig): + custom_ee_init: bool = False + # x, y, z, [min, max] + init_ee_range: list[list[float]] = field(default_factory=lambda: [ + [-0.12, -0.08], + [-0.1, 0.05], + [0.9, 1.012] + ]) + custom_obj_init: bool = True + init_obj_range: dict[str, list[list[float]]] = field(default_factory=lambda: + { + 'SquareNut': + [ + [-0.05, 0.0], + [0.05, 0.15], + + ], + }) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_init_ood_ll.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_init_ood_ll.py new file mode 100644 index 0000000000000000000000000000000000000000..557de168fb079a79de4e9e1157d88a8368e1be5d --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_init_ood_ll.py @@ -0,0 +1,22 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig + +@dataclass +class LLOODRobomimicSquareEnvConfig(RobomimicSquareEnvConfig): + custom_ee_init: bool = False + # x, y, z, [min, max] + init_ee_range: list[list[float]] = field(default_factory=lambda: [ + [-0.12, -0.08], + [-0.1, 0.05], + [0.9, 1.012] + ]) + custom_obj_init: bool = True + init_obj_range: dict[str, list[list[float]]] = field(default_factory=lambda: + { + 'SquareNut': + [ + [0.0, 0.12], + [-0.12, 0.00], + + ], + }) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_init_ood_lr.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_init_ood_lr.py new file mode 100644 index 0000000000000000000000000000000000000000..db5a5cd8ec973d6b318d39849381ff559be4be32 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_init_ood_lr.py @@ -0,0 +1,22 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig + +@dataclass +class LROODRobomimicSquareEnvConfig(RobomimicSquareEnvConfig): + custom_ee_init: bool = False + # x, y, z, [min, max] + init_ee_range: list[list[float]] = field(default_factory=lambda: [ + [-0.12, -0.08], + [-0.1, 0.05], + [0.9, 1.012] + ]) + custom_obj_init: bool = True + init_obj_range: dict[str, list[list[float]]] = field(default_factory=lambda: + { + 'SquareNut': + [ + [-0.09, 0.1], + [0.11, 0.225], + + ], + }) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_init_ood_ul.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_init_ood_ul.py new file mode 100644 index 0000000000000000000000000000000000000000..2f74440138d63478f39579fa07dcba828d1c0c78 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_init_ood_ul.py @@ -0,0 +1,22 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig + +@dataclass +class ULOODRobomimicSquareEnvConfig(RobomimicSquareEnvConfig): + custom_ee_init: bool = False + # x, y, z, [min, max] + init_ee_range: list[list[float]] = field(default_factory=lambda: [ + [-0.12, -0.08], + [-0.1, 0.05], + [0.9, 1.012] + ]) + custom_obj_init: bool = True + init_obj_range: dict[str, list[list[float]]] = field(default_factory=lambda: + { + 'SquareNut': + [ + [-0.115, -0.09], + [-0.12, 0.11], + + ], + }) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_init_ur.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_init_ur.py new file mode 100644 index 0000000000000000000000000000000000000000..8ba2933b39088c33b517a9ae8a71b66817ceb6fd --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_init_ur.py @@ -0,0 +1,24 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig + +# This is identical to the ID (w.r.t. robomimic expert square nut) location for the original RobosuiteSquareEnv +# UR = Upper Right +@dataclass +class URRobomimicSquareEnvConfig(RobomimicSquareEnvConfig): + custom_ee_init: bool = False + # x, y, z, [min, max] + init_ee_range: list[list[float]] = field(default_factory=lambda: [ + [-0.12, -0.08], + [-0.1, 0.05], + [0.9, 1.012] + ]) + custom_obj_init: bool = True + init_obj_range: dict[str, list[list[float]]] = field(default_factory=lambda: + { + 'SquareNut': + [ + [-0.115, -0.11], + [0.11, 0.225], + + ], + }) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_ood.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_ood.py new file mode 100644 index 0000000000000000000000000000000000000000..d90712fafdfa33191568dd0e655a69e2d08ced65 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_ood.py @@ -0,0 +1,22 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig + +@dataclass +class RobommimicSquareEnvOODConfig(RobomimicSquareEnvConfig): + custom_ee_init: bool = False + # x, y, z, [min, max] + init_ee_range: list[list[float]] = field(default_factory=lambda: [ + [-0.12, -0.08], + [-0.1, 0.05], + [0.9, 1.012] + ]) + custom_obj_init: bool = True + init_obj_range: dict[str, list[list[float]]] = field(default_factory=lambda: + { + 'SquareNut': + [ + [-0.115, -0.09], + [-0.12, 0.11], + + ], + }) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_ood_pushing.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_ood_pushing.py new file mode 100644 index 0000000000000000000000000000000000000000..e57b3239eaa3b25ce19ee5b3d08b7c9b2ff8c6b2 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_ood_pushing.py @@ -0,0 +1,11 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.env.robomimic_square_ood import RobommimicSquareEnvOODConfig +from sim_pipeline.reward_functions import RewardFunction +from sim_pipeline.success_functions import SuccessFunction + +@dataclass +class RobommimicSquareEnvOODPushingConfig(RobommimicSquareEnvOODConfig): + horizon = 300 + + reward_function: RewardFunction | None = RewardFunction.SQUARE_REWARD_REACH_AND_PUSH_REWARD_MID #RewardFunction.SQUARE_REWARD_REACH_AND_PUSH_REWARD + success_function: SuccessFunction | None = SuccessFunction.SQUARE_SUCCESS_PUSHING_SUCCESS diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_pushing.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_pushing.py new file mode 100644 index 0000000000000000000000000000000000000000..dbd9270dcd0f11cd851d02994bb1c545bdc7a965 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_pushing.py @@ -0,0 +1,12 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.env.robomimic_square_ood import RobommimicSquareEnvOODConfig +from sim_pipeline.reward_functions import RewardFunction +from sim_pipeline.success_functions import SuccessFunction + +@dataclass +class PushingRobomimicSquareEnvConfig(RobommimicSquareEnvOODConfig): + custom_ee_init: bool = False + + horizon = 100 + reward_function: RewardFunction | None = RewardFunction.SQUARE_REWARD_STABLE_PUSHING_REWARD #RewardFunction.SQUARE_REWARD_REACH_AND_PUSH_REWARD + success_function: SuccessFunction | None = SuccessFunction.SQUARE_SUCCESS_PUSHING_SUCCESS diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_pushing_ll.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_pushing_ll.py new file mode 100644 index 0000000000000000000000000000000000000000..7a84cfc1edc6eb37c889ed428f3b5944332f69f6 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_pushing_ll.py @@ -0,0 +1,10 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.env.robomimic_square_ood import RobommimicSquareEnvOODConfig +from sim_pipeline.reward_functions import RewardFunction + +@dataclass +class PushingLLRobomimicSquareEnvConfig(RobommimicSquareEnvOODConfig): + custom_ee_init: bool = False + + horizon = 100 + reward_function: RewardFunction | None = RewardFunction.SQUARE_REWARD_STABLE_PUSHING_REWARD_LL #RewardFunction.SQUARE_REWARD_REACH_AND_PUSH_REWARD diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_stitch.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_stitch.py new file mode 100644 index 0000000000000000000000000000000000000000..377aca0ea94e0dee4806f789e61f94a069ea5fce --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_square_stitch.py @@ -0,0 +1,21 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.env.robomimic_square import RobomimicSquareEnvConfig + +@dataclass +class RobomimicSquareEnvOODConfig(RobomimicSquareEnvConfig): + custom_ee_init: bool = False + # x, y, z, [min, max] + init_ee_range: list[list[float]] = field(default_factory=lambda: [ + [-0.12, -0.08], + [-0.1, 0.05], + [0.9, 1.012] + ]) + custom_obj_init: bool = True + init_obj_range: dict[str, list[list[float]]] = field(default_factory=lambda: + { + 'SquareNut': + [ + [0.08, 0.12], + [-0.11, -0.07], + ], + }) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_threading.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_threading.py new file mode 100644 index 0000000000000000000000000000000000000000..c032ff5457772148dd6914c1a9481657e043a992 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_threading.py @@ -0,0 +1,26 @@ +import numpy as np +from dataclasses import dataclass, field +from typing import Dict, List +from sim_pipeline.configs.constants import RobomimicEnvType +from sim_pipeline.configs.env.robomimic_base import RobomimicEnvConfig + +@dataclass +class RobomimicThreadingEnvConfig(RobomimicEnvConfig): + env_name: RobomimicEnvType = RobomimicEnvType.THREADING + render_offscreen: bool = True + custom_obj_init: bool = True + init_obj_range: dict[str, list[list[float]]] = field(default_factory=lambda: + { + 'Needle': + [ + [-0.2, -0.05], + [0.15, 0.25], + [-2. * np.pi / 3., -np.pi / 3.], + ], + 'Tripod': + [ + [0.0, 0.0], + [-0.15, -0.15], + [np.pi / 2., np.pi / 2.], + ], + }) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_threading_coverage.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_threading_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..4923a736f3991b21240360b2bc7407a319711e19 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_threading_coverage.py @@ -0,0 +1,26 @@ +import numpy as np +from dataclasses import dataclass, field +from typing import Dict, List +from sim_pipeline.configs.constants import RobomimicEnvType +from sim_pipeline.configs.env.robomimic_base import RobomimicEnvConfig + +@dataclass +class RobomimicThreadingEnvConfig(RobomimicEnvConfig): + env_name: RobomimicEnvType = RobomimicEnvType.THREADING + render_offscreen: bool = True + custom_obj_init: bool = True + init_obj_range: dict[str, list[list[float]]] = field(default_factory=lambda: + { + 'Needle': + [ + [-0.2, 0.12], + [0.05, 0.25], + [-2. * np.pi / 3., -np.pi / 3.], + ], + 'Tripod': + [ + [0.0, 0.0], + [-0.15, -0.15], + [np.pi / 2., np.pi / 2.], + ], + }) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_three_piece_assembly.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_three_piece_assembly.py new file mode 100644 index 0000000000000000000000000000000000000000..8a03def666413e384182cdd0dcf0d5d5859258e9 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_three_piece_assembly.py @@ -0,0 +1,32 @@ +from dataclasses import dataclass, field +from typing import Dict, List +from sim_pipeline.configs.constants import RobomimicEnvType +from sim_pipeline.configs.env.robomimic_base import RobomimicEnvConfig + +@dataclass +class RobomimicThreePieceAssemblyEnvConfig(RobomimicEnvConfig): + env_name: RobomimicEnvType = RobomimicEnvType.THREE_PIECE_ASSEMBLY + render_offscreen: bool = True + + custom_obj_init: bool = True + init_obj_range: dict[str, list[list[float]]] = field(default_factory=lambda: + { + 'Base': + [ + [0.0, 0.0], + [0.0, 0.0], + [0.0, 0.0], + ], + 'Piece1': + [ + [-0.22, 0.22], + [-0.22, 0.22], + [1.5708, 1.5708], + ], + # 'Piece2': + # [ + # [-0.22, 0.22], + # [-0.22, 0.22], + # [1.5708, 1.5708], + # ] + }) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_three_piece_assembly_test.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_three_piece_assembly_test.py new file mode 100644 index 0000000000000000000000000000000000000000..88ba95d4a11106fddfc4aed5d281398c86fb96c3 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_three_piece_assembly_test.py @@ -0,0 +1,32 @@ +from dataclasses import dataclass, field +from typing import Dict, List +from sim_pipeline.configs.constants import RobomimicEnvType +from sim_pipeline.configs.env.robomimic_base import RobomimicEnvConfig + +@dataclass +class RobomimicThreePieceAssemblyEnvConfig(RobomimicEnvConfig): + env_name: RobomimicEnvType = RobomimicEnvType.THREE_PIECE_ASSEMBLY + render_offscreen: bool = True + + custom_obj_init: bool = True + init_obj_range: dict[str, list[list[float]]] = field(default_factory=lambda: + { + 'Base': + [ + [0.0, 0.0], + [0.0, 0.0], + [0.0, 0.0], + ], + 'Piece1': + [ + [0.2, 0.2], + [0.15, 0.15], + [1.5708, 1.5708], + ], + # 'Piece2': + # [ + # [-0.22, 0.22], + # [-0.22, 0.22], + # [1.5708, 1.5708], + # ] + }) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_three_piece_assembly_tipped.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_three_piece_assembly_tipped.py new file mode 100644 index 0000000000000000000000000000000000000000..666c7c479fc44479b63009f1e48d1e450cde6c04 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_three_piece_assembly_tipped.py @@ -0,0 +1,17 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import RobomimicEnvType +from sim_pipeline.configs.env.robomimic_base import RobomimicEnvConfig + +@dataclass +class RobomimicThreePieceAssemblyTippedEnvConfig(RobomimicEnvConfig): + """rsm_rise: piece-assembly "tipping" coverage eval — Piece1 starts on its side (quat xyzw = (0.5, 0.5, -0.5, 0.5)) anywhere + on the table, exactly the 104 tipped initial states of two_piece_expert_play_tipping.hdf5 (Table IV 'Partial Tipping (104)').""" + env_name: RobomimicEnvType = RobomimicEnvType.THREE_PIECE_ASSEMBLY + render_offscreen: bool = True + custom_obj_init: bool = True # same table-wide sampler as robomimic_three_piece_assembly (only used before reset_to) + init_obj_range: dict[str, list[list[float]]] = field(default_factory=lambda: + { + 'Base': [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0]], + 'Piece1': [[-0.22, 0.22], [-0.22, 0.22], [1.5708, 1.5708]], + }) + reset_states_file: str | None = '/proj/dmfexp/zwhong/rsm_rise/data/derived/two_piece_tipped_init_states.json' diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_three_piece_assembly_top_left.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_three_piece_assembly_top_left.py new file mode 100644 index 0000000000000000000000000000000000000000..46c95bd70e84296b3f262435d8c9bcd5e4cf205e --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_three_piece_assembly_top_left.py @@ -0,0 +1,32 @@ +from dataclasses import dataclass, field +from typing import Dict, List +from sim_pipeline.configs.constants import RobomimicEnvType +from sim_pipeline.configs.env.robomimic_base import RobomimicEnvConfig + +@dataclass +class RobomimicThreePieceAssemblyEnvConfig(RobomimicEnvConfig): + env_name: RobomimicEnvType = RobomimicEnvType.THREE_PIECE_ASSEMBLY + render_offscreen: bool = True + + custom_obj_init: bool = True + init_obj_range: dict[str, list[list[float]]] = field(default_factory=lambda: + { + 'Base': + [ + [0.0, 0.0], + [0.0, 0.0], + [0.0, 0.0], + ], + 'Piece1': + [ + [-0.22, -0.0], + [-0.2, 0.0], + [1.5708, 1.5708], + ], + # 'Piece2': + # [ + # [-0.22, 0.22], + # [-0.22, 0.22], + # [1.5708, 1.5708], + # ] + }) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_three_piece_assembly_top_right.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_three_piece_assembly_top_right.py new file mode 100644 index 0000000000000000000000000000000000000000..654c793df1c7bca4338a1809dd06634791d2f761 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_three_piece_assembly_top_right.py @@ -0,0 +1,32 @@ +from dataclasses import dataclass, field +from typing import Dict, List +from sim_pipeline.configs.constants import RobomimicEnvType +from sim_pipeline.configs.env.robomimic_base import RobomimicEnvConfig + +@dataclass +class RobomimicThreePieceAssemblyEnvConfig(RobomimicEnvConfig): + env_name: RobomimicEnvType = RobomimicEnvType.THREE_PIECE_ASSEMBLY + render_offscreen: bool = True + + custom_obj_init: bool = True + init_obj_range: dict[str, list[list[float]]] = field(default_factory=lambda: + { + 'Base': + [ + [0.0, 0.0], + [0.0, 0.0], + [0.0, 0.0], + ], + 'Piece1': + [ + [-0.22, -0.0], + [0.0, 0.22], + [1.3708, 1.7708], + ], + # 'Piece2': + # [ + # [-0.22, 0.22], + # [-0.22, 0.22], + # [1.5708, 1.5708], + # ] + }) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_tool.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..ec0995ed3c46b117cbd90809beb268541be5bdc5 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_tool.py @@ -0,0 +1,32 @@ +import numpy as np +from dataclasses import dataclass, field +from typing import Dict, List +from sim_pipeline.configs.constants import RobomimicEnvType +from sim_pipeline.configs.env.robomimic_base import RobomimicEnvConfig + +@dataclass +class RobomimicToolHangEnvConfig(RobomimicEnvConfig): + env_name: RobomimicEnvType = RobomimicEnvType.TOOL_HANG + render_offscreen: bool = True + custom_obj_init: bool = False + init_obj_range: dict[str, list[list[float]]] = field(default_factory=lambda: + { + 'standObject': + [ + [-0.08, -0.08], + [0.0, 0.0], + [0.0, 0.0], + ], + 'frameObject': + [ + [-0.06, -0.02], + [-0.26, -0.22], + [(-np.pi / 2) + (np.pi / 6) - np.pi / 18, (-np.pi / 2) + (np.pi / 6) + np.pi / 18], + ], + 'toolObject': + [ + [0.02, 0.06], + [-0.22, -0.18], + [(-np.pi / 2) - (np.pi / 9.0) - np.pi / 18, (-np.pi / 2) - (np.pi / 9.0) + np.pi / 18], + ], + }) diff --git a/code_src/rise_code/sim_pipeline/configs/env/robomimic_tool_ood.py b/code_src/rise_code/sim_pipeline/configs/env/robomimic_tool_ood.py new file mode 100644 index 0000000000000000000000000000000000000000..8154459dbc3d18986434b8da8644be4c24e3b6ac --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/env/robomimic_tool_ood.py @@ -0,0 +1,32 @@ +import numpy as np +from dataclasses import dataclass, field +from typing import Dict, List +from sim_pipeline.configs.constants import RobomimicEnvType +from sim_pipeline.configs.env.robomimic_tool import RobomimicToolHangEnvConfig + +@dataclass +class RobomimicToolHangEnvConfig(RobomimicToolHangEnvConfig): + env_name: RobomimicEnvType = RobomimicEnvType.TOOL_HANG + render_offscreen: bool = True + custom_obj_init: bool = True + init_obj_range: dict[str, list[list[float]]] = field(default_factory=lambda: + { + 'standObject': + [ + [-0.08, -0.08], + [0.0, 0.0], + [0.0, 0.0], + ], + 'frameObject': + [ + [-0.15, -0.02], + [-0.26, -0.22], + [(-np.pi / 2) + (np.pi / 6) - np.pi / 18, (-np.pi / 2) + (np.pi / 6) + np.pi / 18], + ], + 'toolObject': + [ + [0.02, 0.15], + [-0.22, -0.18], + [(-np.pi / 2) - (np.pi / 9.0) - np.pi / 18, (-np.pi / 2) - (np.pi / 9.0) + np.pi / 18], + ], + }) diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/_combined_individual/pushing_expert_diffusion_lowdim.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/_combined_individual/pushing_expert_diffusion_lowdim.py new file mode 100644 index 0000000000000000000000000000000000000000..f70827f89d3caff89e331eb9ad260d70218b5ea7 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/_combined_individual/pushing_expert_diffusion_lowdim.py @@ -0,0 +1,9 @@ +from dataclasses import dataclass +from sim_pipeline.configs.constants import PolicyType +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class DiffusionEvalExpConfig(EvalExpConfig): + policy_type: PolicyType = PolicyType.DIFFUSION + date_string: str = '0' + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/_combined_individual/square_combined_diffusion_images.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/_combined_individual/square_combined_diffusion_images.py new file mode 100644 index 0000000000000000000000000000000000000000..f70827f89d3caff89e331eb9ad260d70218b5ea7 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/_combined_individual/square_combined_diffusion_images.py @@ -0,0 +1,9 @@ +from dataclasses import dataclass +from sim_pipeline.configs.constants import PolicyType +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class DiffusionEvalExpConfig(EvalExpConfig): + policy_type: PolicyType = PolicyType.DIFFUSION + date_string: str = '0' + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/_combined_individual/square_expert_diffusion_lowdim.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/_combined_individual/square_expert_diffusion_lowdim.py new file mode 100644 index 0000000000000000000000000000000000000000..59eebe7677e2a0ff6d46f64d16f6b5e8b471806b --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/_combined_individual/square_expert_diffusion_lowdim.py @@ -0,0 +1,9 @@ +from dataclasses import dataclass +from sim_pipeline.configs.constants import PolicyType +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class DiffusionEvalExpConfig(EvalExpConfig): + policy_type: PolicyType = PolicyType.DIFFUSION + date_string: str = '20240818182405' + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/_combined_individual/square_expert_diffusion_lowdim_rohan.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/_combined_individual/square_expert_diffusion_lowdim_rohan.py new file mode 100644 index 0000000000000000000000000000000000000000..f70827f89d3caff89e331eb9ad260d70218b5ea7 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/_combined_individual/square_expert_diffusion_lowdim_rohan.py @@ -0,0 +1,9 @@ +from dataclasses import dataclass +from sim_pipeline.configs.constants import PolicyType +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class DiffusionEvalExpConfig(EvalExpConfig): + policy_type: PolicyType = PolicyType.DIFFUSION + date_string: str = '0' + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/_combined_individual/square_pushing_diffusion_lowdim.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/_combined_individual/square_pushing_diffusion_lowdim.py new file mode 100644 index 0000000000000000000000000000000000000000..0a8103573b9828c4b327763f1f4da5e06d430886 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/_combined_individual/square_pushing_diffusion_lowdim.py @@ -0,0 +1,9 @@ +from dataclasses import dataclass +from sim_pipeline.configs.constants import PolicyType +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class DiffusionEvalExpConfig(EvalExpConfig): + policy_type: PolicyType = PolicyType.DIFFUSION + date_string: str = '20240816155424' + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/diffusion_eval.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/diffusion_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..681dff6325d30dbde540edcaa0de3ad0fc4e303e --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/diffusion_eval.py @@ -0,0 +1,9 @@ +from dataclasses import dataclass +from sim_pipeline.configs.constants import PolicyType +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class DiffusionEvalExpConfig(EvalExpConfig): + policy_type: PolicyType = PolicyType.DIFFUSION + date_string: str = '' + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/evaluation.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..2c3f373fda4901cafc6a08f0ff5a56e884793be8 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/evaluation.py @@ -0,0 +1,81 @@ +from dataclasses import dataclass, field +from omegaconf import MISSING +from sim_pipeline.configs.exp.base import BaseExpConfig +from sim_pipeline.configs.constants import PolicyType + +@dataclass +class EvalExpConfig(BaseExpConfig): + # seed eval + eval_seed: int = MISSING + + model_path: str | None = None + + # what type of policy to roll out + policy_type: PolicyType = PolicyType.ROBOMIMIC + + # whether to save video of evaluation rollouts + log_video: bool = True + # dimensions to render video + video_dims: tuple | None = field(default_factory=lambda: [196,196]) + # only record every nth frame to save space + video_skip: int = 5 + + num_rollouts: int = 20 + rollout_horizon: int = 400 + + # whether to save trajectories to a new dataset + save_to_dataset: bool = False + # if saving to dataset, name of file to save to + dataset_name: str = 'eval_default' + + # if > 1, use vectorized env with this many parallel envs + num_workers: int = 1 + + # print out stats every episode + verbose: bool = True + + # whether to use the model manager. Otherwise, specify + # the identifier (i.e. the date string for diffusion/robomimic) + use_model_manager: bool = True + + # whether to reset to the exact intial states in the dataset + reset_to_data: bool = False + + manual_lookahead: bool = False + opex: bool = False + + discriminator_name: str | None = None + use_discriminator: bool = False + + # rsm_rise additions + # write per-episode results + success rate to this JSON path (None = off) + results_json: str | None = None + # stop an episode at the first success (the success metric is "any step", so it is unchanged) + end_on_success: bool = False + # 'idql' = RISE default (128 samples, critic argmax); 'bc' = one sample from the diffusion policy + policy_mode: str = 'idql' + # rsm_rise (stream D): continue a crashed/preempted cell from its .partial[_best] + resume_partial: bool = True + # rsm_rise (stream D): the real checkpoint file behind exp.model_path (which is a temp symlink dir); + # recorded in results_json and used as the resume identity key + eval_ckpt: str = '' + # rsm_rise (stream D): free-form tags copied into results_json (cell name, task label) + eval_cell: str = '' + eval_task: str = '' + # rsm_rise gen_q#264: roll out IFQL AS PUBLISHED instead of a robomimic policy -- its own flow actor + # proposes `ifql_num_samples` candidates and its own critic picks one (column (a) of the flagship's + # IFQL pair; column (b) is training.rsm_backend=ifql in the existing planner, which needs none of + # these keys). `exp.eval_ckpt` is the ifql_bundle.pt; eval_cell.sh already sets it. + ifql_policy: bool = False + ifql_num_samples: int = 128 + # the task cache's feat_stats.npz; '' = the one the bundle recorded at training time + ifql_feat_stats: str = '' + + # rsm_rise gen_q#289 (worker WM_NATIVE) -- the APPENDIX row: roll a world model under ITS OWN + # published planner (CEM over the full open-loop action sequence), not under the shared-candidate + # read-out of the main table. Selected by exp.policy_mode='wm_cem'; this holds the planner spec as + # a JSON string (or a path to a .json), e.g. + # {"family": "lewm", "ckpt": ".../ckpt_s100000.pt", "feat_stats": ".../feat_stats.npz", "seed": 0} + # Unset keys fall back to the PUBLISHED defaults in robomimic.algo.wm_native_cem.PUBLISHED, so a + # cell that names nothing is the as-published cell. There is NO actor on this path. + wm_cem_json: str = '' diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_coverage_tl_eval.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_coverage_tl_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..bd9f71e79766629090e8a6d5655b7db037ea3643 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_coverage_tl_eval.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import PolicyType, CombinedPolicyType +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class HeuristicResetSplitEvalExpConfig(EvalExpConfig): + policy_type: PolicyType = PolicyType.COMPOSITE + policy_configs: list[str] = field(default_factory=lambda: [ + 'square_iql_diffusion_push_coverage_to_tl', + 'eval_pd', + 'square_expert_lowdim_rohan', + ]) + combined_policy_type: CombinedPolicyType = CombinedPolicyType.HEURISTIC_RESET_SPLIT + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_eval.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..dc841c6d9eed69e27efc9a409a9dabc0aecf4693 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_eval.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import PolicyType, CombinedPolicyType +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class HeuristicResetEvalExpConfig(EvalExpConfig): + policy_type: PolicyType = PolicyType.COMPOSITE + policy_configs: list[str] = field(default_factory=lambda: [ + 'pushing_expert_lowdim', + 'eval_pd', + ]) + combined_policy_type: CombinedPolicyType = CombinedPolicyType.HEURISTIC_RESET + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_images_eval.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_images_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..a90503132a1506e3db8c96c526d95fb7d5df2a08 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_images_eval.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import PolicyType, CombinedPolicyType +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class HeuristicResetImagesEvalExpConfig(EvalExpConfig): + policy_type: PolicyType = PolicyType.COMPOSITE + policy_configs: list[str] = field(default_factory=lambda: [ + 'square_combined_images', + 'eval_pd', + ]) + combined_policy_type: CombinedPolicyType = CombinedPolicyType.HEURISTIC_RESET + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_manual_eval.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_manual_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..1fb776d6a17c8b4c7986b1f4ad521eb63e3ff6cd --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_manual_eval.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import PolicyType, CombinedPolicyType +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class HeuristicResetSplitEvalExpConfig(EvalExpConfig): + policy_type: PolicyType = PolicyType.COMPOSITE + policy_configs: list[str] = field(default_factory=lambda: [ + 'square_manual_pushing_tl', + 'eval_pd', + 'square_expert_lowdim_rohan', + ]) + combined_policy_type: CombinedPolicyType = CombinedPolicyType.HEURISTIC_RESET_SPLIT + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_manual_ll_eval.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_manual_ll_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..79d3e868a5122f779aff8aa807c48d92c55d81c9 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_manual_ll_eval.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import PolicyType, CombinedPolicyType +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class HeuristicResetSplitEvalExpConfig(EvalExpConfig): + policy_type: PolicyType = PolicyType.COMPOSITE + policy_configs: list[str] = field(default_factory=lambda: [ + 'square_manual_pushing_ll', + 'eval_pd', + 'square_expert_ll_lowdim', + ]) + combined_policy_type: CombinedPolicyType = CombinedPolicyType.HEURISTIC_RESET_SPLIT + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_push_mid.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_push_mid.py new file mode 100644 index 0000000000000000000000000000000000000000..bae05e828aa60d85d3206e048a32885b4226f248 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_push_mid.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import PolicyType, CombinedPolicyType +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class HeuristicResetSplitEvalExpConfig(EvalExpConfig): + policy_type: PolicyType = PolicyType.COMPOSITE + policy_configs: list[str] = field(default_factory=lambda: [ + 'square_iql_diffusion_push_to_mid', + 'eval_pd', + 'hook_expert_lowdim', + ]) + combined_policy_type: CombinedPolicyType = CombinedPolicyType.HEURISTIC_RESET_SPLIT + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_rotation.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_rotation.py new file mode 100644 index 0000000000000000000000000000000000000000..a65806632822351ae8a2e967d3c9881cc5e753cc --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_rotation.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import PolicyType, CombinedPolicyType +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class HeuristicResetSplitEvalExpConfig(EvalExpConfig): + policy_type: PolicyType = PolicyType.COMPOSITE + policy_configs: list[str] = field(default_factory=lambda: [ + 'square_rotation', + 'eval_pd', + 'hook_expert_lowdim', + ]) + combined_policy_type: CombinedPolicyType = CombinedPolicyType.HEURISTIC_RESET_SPLIT + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_split_eval.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_split_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..8fd7a53827108f85773a06785801571afc55c041 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_split_eval.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import PolicyType, CombinedPolicyType +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class HeuristicResetSplitEvalExpConfig(EvalExpConfig): + policy_type: PolicyType = PolicyType.COMPOSITE + policy_configs: list[str] = field(default_factory=lambda: [ + 'pushing_expert_lowdim', + 'eval_pd', + 'square_expert_lowdim', + ]) + combined_policy_type: CombinedPolicyType = CombinedPolicyType.HEURISTIC_RESET + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_split_eval2.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_split_eval2.py new file mode 100644 index 0000000000000000000000000000000000000000..596d3d7c5909c48fcfc590722977f1ddd3b8bfe9 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_split_eval2.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import PolicyType, CombinedPolicyType +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class HeuristicResetSplitEvalExpConfig(EvalExpConfig): + policy_type: PolicyType = PolicyType.COMPOSITE + policy_configs: list[str] = field(default_factory=lambda: [ + 'pushing_expert_lowdim', + 'eval_pd', + 'square_expert_lowdim_rohan', + ]) + combined_policy_type: CombinedPolicyType = CombinedPolicyType.HEURISTIC_RESET + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_split_idql_image.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_split_idql_image.py new file mode 100644 index 0000000000000000000000000000000000000000..1b6916363a0e25ce8efb1f14379371c22d4f2b73 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_split_idql_image.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import PolicyType, CombinedPolicyType +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class HeuristicResetSplitEvalExpConfig(EvalExpConfig): + policy_type: PolicyType = PolicyType.COMPOSITE + policy_configs: list[str] = field(default_factory=lambda: [ + 'square_iql_diffusion_300a_200e_image', + 'eval_pd', + 'square_combined_images', + ]) + combined_policy_type: CombinedPolicyType = CombinedPolicyType.HEURISTIC_RESET_SPLIT + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_true_split_eval.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_true_split_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..81fba4b22684186739fd752e6d6496799229ca96 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/heuristic_reset_true_split_eval.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import PolicyType, CombinedPolicyType +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class HeuristicResetSplitEvalExpConfig(EvalExpConfig): + policy_type: PolicyType = PolicyType.COMPOSITE + policy_configs: list[str] = field(default_factory=lambda: [ + 'square_pushing_lowdim', + 'eval_pd', + 'square_expert_lowdim_rohan', + ]) + combined_policy_type: CombinedPolicyType = CombinedPolicyType.HEURISTIC_RESET + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/ogbench_eval.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/ogbench_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..b1faf45eb55f38a9614bb13b9b0b9b83c94b4ed3 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/ogbench_eval.py @@ -0,0 +1,8 @@ +from dataclasses import dataclass +from sim_pipeline.configs.constants import PolicyType +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class OGBenchEvalExpConfig(EvalExpConfig): + policy_type: PolicyType = PolicyType.OGBENCH + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/pd_eval.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/pd_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..440a43f0006c1d2a73d2d668563a48a488d02177 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/pd_eval.py @@ -0,0 +1,11 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import PolicyType +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class PDEvalExpConfig(EvalExpConfig): + policy_type: PolicyType = PolicyType.PD + # default robomimic ee init + target_pos: list[float] = field(default_factory=lambda: + [-0.1031, -0.0035, 1.015] + ) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/robomimic_eval.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/robomimic_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..e01764446c002f0db75b44e019fe85312ff25783 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/robomimic_eval.py @@ -0,0 +1,9 @@ +from dataclasses import dataclass +from sim_pipeline.configs.constants import PolicyType +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class RobomimicEvalExpConfig(EvalExpConfig): + policy_type: PolicyType = PolicyType.ROBOMIMIC + date_string: str = '' + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/robomimic_eval_save_data.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/robomimic_eval_save_data.py new file mode 100644 index 0000000000000000000000000000000000000000..83943078df83b74acb01efd88a082a40d646864d --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/robomimic_eval_save_data.py @@ -0,0 +1,7 @@ +from dataclasses import dataclass +from sim_pipeline.configs.exp._eval.robomimic_eval import RobomimicEvalExpConfig + +@dataclass +class RobomimicEvalSaveDataExpConfig(RobomimicEvalExpConfig): + save_to_dataset: bool = True + verbose: bool = False \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/_eval/sb_eval.py b/code_src/rise_code/sim_pipeline/configs/exp/_eval/sb_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..38be37e6fca03d532ee56ea5c5a9c524fd30de19 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/_eval/sb_eval.py @@ -0,0 +1,8 @@ +from dataclasses import dataclass +from sim_pipeline.configs.constants import PolicyType +from sim_pipeline.configs.exp._eval.evaluation import EvalExpConfig + +@dataclass +class RLEvalExpConfig(EvalExpConfig): + # what type of policy to roll out + policy_type: PolicyType = PolicyType.STABLE_BASELINES \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/base.py b/code_src/rise_code/sim_pipeline/configs/exp/base.py new file mode 100644 index 0000000000000000000000000000000000000000..488a9dde220759287e5356a3e40d6342df8ce7e1 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/base.py @@ -0,0 +1,16 @@ +from dataclasses import dataclass +from typing import Tuple +from omegaconf import MISSING +from sim_pipeline.configs.constants import LOG_DIR +@dataclass +class BaseExpConfig: + num_workers: int = 16 + seed: int = MISSING + device_id: int = 0 + logdir: str = LOG_DIR + log_interval: int = 10 + eval_interval: int = 500 + save_interval: int = 500 + format_strings: Tuple = ('stdout','tensorboard', 'wandb') + entity: str = 'kehuang' + project: str = 'iql_diffusion' \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/exp/diffusion_train.py b/code_src/rise_code/sim_pipeline/configs/exp/diffusion_train.py new file mode 100644 index 0000000000000000000000000000000000000000..71ce369b0cc9a16ab0c1a6f05bf237308ebbcbf5 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/diffusion_train.py @@ -0,0 +1,9 @@ +from dataclasses import dataclass +from sim_pipeline.configs.exp.base import BaseExpConfig + +@dataclass +class DiffusionExpConfig(BaseExpConfig): + # rollout every n epochs + eval_interval: int = 500 + # checkpoint every n epochs + save_interval: int = 500 diff --git a/code_src/rise_code/sim_pipeline/configs/exp/robomimic_train.py b/code_src/rise_code/sim_pipeline/configs/exp/robomimic_train.py new file mode 100644 index 0000000000000000000000000000000000000000..a87997f380ebddeef3f68ca114a552e8e5b18581 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/exp/robomimic_train.py @@ -0,0 +1,7 @@ +from dataclasses import dataclass +from sim_pipeline.configs.exp.base import BaseExpConfig + +@dataclass +class RobomimicTrainExpConfig(BaseExpConfig): + # eval every n epochs + eval_interval: int = 250 diff --git a/code_src/rise_code/sim_pipeline/configs/hydra/launcher/submitit_slurm_custom.yaml b/code_src/rise_code/sim_pipeline/configs/hydra/launcher/submitit_slurm_custom.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dc8bd283feac568ee0109f3effadc1ef013cf352 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/hydra/launcher/submitit_slurm_custom.yaml @@ -0,0 +1,28 @@ +defaults: + - submitit_slurm + +submitit_folder: ${hydra.sweep.dir}/.submitit/%j +timeout_min: 3600 +cpus_per_task: 16 +gpus_per_node: 1 +tasks_per_node: 1 +mem_gb: 64 +nodes: 1 +name: ${hydra.job.name}d +_target_: hydra_plugins.hydra_submitit_launcher.submitit_launcher.SlurmLauncher +partition: 'gpu-l40s' +qos: null +comment: null +constraint: null +exclude: null +gres: null +cpus_per_gpu: null +gpus_per_task: null +mem_per_gpu: null +mem_per_cpu: null +account: weirdlab +signal_delay_s: 120 +max_num_timeout: 0 +additional_parameters: {} +array_parallelism: 256 +setup: null diff --git a/code_src/rise_code/sim_pipeline/configs/parse_config.py b/code_src/rise_code/sim_pipeline/configs/parse_config.py new file mode 100644 index 0000000000000000000000000000000000000000..8bf52ec797d62bff52b4ca5970c4fbfb512a4df2 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/parse_config.py @@ -0,0 +1,74 @@ +import importlib +from typing import Type +from types import ModuleType +from pathlib import Path +from contextlib import contextmanager +from hydra.core.config_store import ConfigStore +from sim_pipeline.configs.constants import CONFIG_DIR + +@contextmanager +def add_to_path(p): + import sys + old_path = sys.path + sys.path = sys.path[:] + sys.path.insert(0, p) + try: + yield + finally: + sys.path = old_path + + +def find_config_class(module: ModuleType) -> Type: + md = module.__dict__ + class_list = [md[c] for c in md if (isinstance(md[c], type) and md[c].__module__ == module.__name__)] + if len(class_list) > 1: + print(f"WARNING: Multiple classes found in config {module.__name__}. Config invalid") + return None + elif len(class_list) == 0: + print(f"WARNING: No classes found in config {module.__name__}. Config invalid") + return None + return class_list[0] + + +def import_config(module_location: str, abs_path: str) -> Type: + spec = importlib.util.spec_from_file_location(module_location, abs_path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return find_config_class(module) + + +def recursive_find_config(curr_dir: Path, module_path: list[str], cs: ConfigStore, excluded_names: list[str]): + for path in curr_dir.iterdir(): + if path.is_file() and path.suffix == '.py' and path.stem not in excluded_names: + mp = '.'.join(module_path) + try: + config_class = import_config(f'{mp}.{path.stem}', path) + except Exception as e: # rsm_rise patch: skip configs whose deps are absent (e.g. ogbench, jax, weird_franka) + print(f"WARNING: Skipping config {path.stem}: {type(e).__name__}: {e}") + continue + if config_class is None: + continue + try: + group = '/'.join([x for x in module_path if x[0] != '_']) + if group: + cs.store(group=group, name=path.stem, node=config_class) + else: + cs.store(name=path.stem, node=config_class) + except Exception as e: + print(f"WARNING: Error storing config {path.stem}: {e}. Skipping config.") + continue + if path.is_dir() and path.stem not in excluded_names: + new_module_path = module_path + [path.stem] + recursive_find_config(path, new_module_path, cs, excluded_names) + + +def parse_config(config_path=None, exclude=('constants',)): + if config_path is None: + config_path = CONFIG_DIR + this_file = Path(__file__).stem + + with add_to_path(str(config_path)): + cs = ConfigStore.instance() + + excluded = [*exclude, this_file, '__init__', '__pycache__'] + recursive_find_config(config_path, [], cs, excluded) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/robot/base_franka.py b/code_src/rise_code/sim_pipeline/configs/robot/base_franka.py new file mode 100644 index 0000000000000000000000000000000000000000..f013b44757cb8f397d714d756db35c9f1fba1a3c --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/robot/base_franka.py @@ -0,0 +1,36 @@ +from dataclasses import dataclass +from typing import Tuple, Optional +from pathlib import Path +from sim_pipeline.configs.constants import CALIBRATION_PATH + +@dataclass +class RobotConfigFranka: + control_hz: int = 10 + DoF: int = 2 + gripper: bool = False + + # Franka model: 'panda' 'fr3' + robot_type: str = "panda" + + # randomize arm position on reset + randomize_ee_on_reset: bool = True + # allows user to pause to reset reset of the environment + pause_after_reset: bool = False + + # observation space configuration + qpos: bool = True + ee_pos: bool = True + imgs: bool = False + normalize: bool = False + + # pass IP if not running on NUC "localhost" if running on NUC None if running sim + ip_address: Optional[str] = None + # specify path length if resetting after a fixed length + max_path_length: int = 40 + # camera type to use: 'realsense' 'zed' + camera_model: Optional[str] = None + camera_resolution: Tuple[int, int] = (480, 640) # (128 128) -> HxW + calibration_file: str = CALIBRATION_PATH + # Mujoco: model name + model_name: str = "base_franka" + on_screen_rendering: bool = False \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_diffusion/base_diffusion.py b/code_src/rise_code/sim_pipeline/configs/training/_diffusion/base_diffusion.py new file mode 100644 index 0000000000000000000000000000000000000000..339761e2e2559ce410126991e454199acc02dd88 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_diffusion/base_diffusion.py @@ -0,0 +1,30 @@ +from dataclasses import dataclass, field +from pathlib import Path +from sim_pipeline.configs.constants import CONFIG_DIR + +@dataclass +class DiffusionTrainingConfig: + num_epochs: int = 5000 + batch_size: int = 256 + + default_config_path: str = str(CONFIG_DIR / 'diffusion_base_configs' / 'lowdim_square_cnn.yaml') + + low_dim_keys: list[str] = field(default_factory=lambda: [ + "robot0_gripper_qpos", + "robot0_eef_pos", + "robot0_eef_quat", + "object" + ]) + + rgb_keys: list[str] = field(default_factory=lambda: [ + ]) + + depth_keys: list[str] = field(default_factory=lambda: [ + ]) + + execution_horizon: int = 8 + obs_horizon: int = 2 + prediction_horizon: int = 16 + + render_video: bool = True + rollout_horizon: int = 200 \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_diffusion/base_diffusion_rohan.py b/code_src/rise_code/sim_pipeline/configs/training/_diffusion/base_diffusion_rohan.py new file mode 100644 index 0000000000000000000000000000000000000000..5b7ed8bb2411809244ea2ddb054435e937ace9a4 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_diffusion/base_diffusion_rohan.py @@ -0,0 +1,31 @@ +from dataclasses import dataclass, field +from pathlib import Path +from sim_pipeline.configs.constants import CONFIG_DIR +from sim_pipeline.configs.training._diffusion.base_diffusion import DiffusionTrainingConfig + +@dataclass +class DiffusionTrainingRohanConfig(DiffusionTrainingConfig): + num_epochs: int = 5000 + batch_size: int = 256 + + default_config_path: str = str(CONFIG_DIR / 'diffusion_base_configs' / 'lowdim_square_cnn.yaml') + + low_dim_keys: list[str] = field(default_factory=lambda: [ + "object", + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + ]) + + rgb_keys: list[str] = field(default_factory=lambda: [ + ]) + + depth_keys: list[str] = field(default_factory=lambda: [ + ]) + + execution_horizon: int = 8 + obs_horizon: int = 2 + prediction_horizon: int = 16 + + render_video: bool = True + rollout_horizon: int = 400 \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_diffusion/diffusion_image.py b/code_src/rise_code/sim_pipeline/configs/training/_diffusion/diffusion_image.py new file mode 100644 index 0000000000000000000000000000000000000000..6c1c787011e9424e873ff6e05519da6a05f30499 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_diffusion/diffusion_image.py @@ -0,0 +1,31 @@ +from dataclasses import dataclass, field +from pathlib import Path +from sim_pipeline.configs.constants import CONFIG_DIR + +@dataclass +class DiffusionImageTrainingConfig: + num_epochs: int = 8000 + batch_size: int = 64 + + default_config_path: str = str(CONFIG_DIR / 'diffusion_base_configs' / 'image_square_cnn.yaml') + + low_dim_keys: list[str] = field(default_factory=lambda: [ + "robot0_gripper_qpos", + "robot0_eef_pos", + "robot0_eef_quat", + ]) + + rgb_keys: list[str] = field(default_factory=lambda: [ + "agentview_image", + "robot0_eye_in_hand_image", + ]) + + depth_keys: list[str] = field(default_factory=lambda: [ + ]) + + execution_horizon: int = 8 + obs_horizon: int = 2 + prediction_horizon: int = 16 + + render_video: bool = True + rollout_horizon: int = 200 \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_diffusion/tycho_diffusion.py b/code_src/rise_code/sim_pipeline/configs/training/_diffusion/tycho_diffusion.py new file mode 100644 index 0000000000000000000000000000000000000000..3b7ac7869b638cea3390514ffcafd511024bd170 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_diffusion/tycho_diffusion.py @@ -0,0 +1,27 @@ +from dataclasses import dataclass, field +from pathlib import Path +from sim_pipeline.configs.constants import CONFIG_DIR + +@dataclass +class DiffusionTrainingConfig: + num_epochs: int = 5000 + batch_size: int = 256 + + default_config_path: str = str(CONFIG_DIR / 'diffusion_base_configs' / 'lowdim_square_cnn.yaml') + + low_dim_keys: list[str] = field(default_factory=lambda: [ + "states", + ]) + + rgb_keys: list[str] = field(default_factory=lambda: [ + ]) + + depth_keys: list[str] = field(default_factory=lambda: [ + ]) + + execution_horizon: int = 8 + obs_horizon: int = 2 + prediction_horizon: int = 16 + + render_video: bool = False + rollout_horizon: int = 200 \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/cooking.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/cooking.py new file mode 100644 index 0000000000000000000000000000000000000000..5f27949d6c7eb2199cb61c25d813ece9093c1a90 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/cooking.py @@ -0,0 +1,36 @@ +from dataclasses import dataclass, field + +from robomimic.algo.iql_diffusion import MultiStepMethod + +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion_spectral_image import IQLDiffusionSpectralImageTrainingConfig + +# rsm_rise (#263): REAL FR3 cooking play data (rsm_cooking_v5) converted to the sim hdf5 layout by +# scripts/real/convert_cooking_hdf5.py. Same recipe as piece_assembly.py (T 0.08) -- the kNN distance for the +# image-observation augmentation is computed in normalised DINOv2 feature space (dataset._extract_state_for_distance), +# not in EE space, so the sim thresholds carry over; the log prints the neighbour distances for a sanity check. +# Proprio: 10-d absolute EE [xyz, rot6d, gripper] + a binary gripper key (robot0_gripper_qpos, 1 = closed) that the +# augmentation's gripper-equality test and the critic's late fusion need (continuous widths never compare equal). +@dataclass +class CookingConfig(IQLDiffusionSpectralImageTrainingConfig): + low_dim_keys: list[str] = field(default_factory=lambda: [ + "robot0_eef_pos", + "robot0_eef_rot6d", + "robot0_gripper_width", + "robot0_gripper_qpos", + ]) + + rgb_keys: list[str] = field(default_factory=lambda: [ + "agentview_image", + "robot0_eye_in_hand_image", + ]) + + late_fusion_key: str | None = 'robot0_gripper_qpos' + + spectral_norm_policy: bool = True + policy_bottleneck_beta: float = 0.1 + + action_augmentation: bool = True + advanced_augmentation: bool = True + distance_threshold: float = 0.15 + num_neighbors: int = 15 diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/mug.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/mug.py new file mode 100644 index 0000000000000000000000000000000000000000..43963f054081b8663654496b496779893031bf56 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/mug.py @@ -0,0 +1,27 @@ +from dataclasses import dataclass, field + +from robomimic.algo.iql_diffusion import MultiStepMethod + +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion_spectral_image import IQLDiffusionSpectralImageTrainingConfig + +@dataclass +class ThreadingConfig(IQLDiffusionSpectralImageTrainingConfig): + low_dim_keys: list[str] = field(default_factory=lambda: [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + ]) + + rgb_keys: list[str] = field(default_factory=lambda: [ + "agentview_image", + "robot0_eye_in_hand_image", + ]) + + spectral_norm_policy: bool = True + policy_bottleneck_beta: float = 0.001 + + action_augmentation: bool = True + advanced_augmentation: bool = True + distance_threshold: float = 0.05 + num_neighbors: int = 15 \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/piece_assembly.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/piece_assembly.py new file mode 100644 index 0000000000000000000000000000000000000000..9b7bebeb41fe51f4868e1510781deb069986d8e0 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/piece_assembly.py @@ -0,0 +1,27 @@ +from dataclasses import dataclass, field + +from robomimic.algo.iql_diffusion import MultiStepMethod + +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion_spectral_image import IQLDiffusionSpectralImageTrainingConfig + +@dataclass +class TwoPieceConfig(IQLDiffusionSpectralImageTrainingConfig): + low_dim_keys: list[str] = field(default_factory=lambda: [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + ]) + + rgb_keys: list[str] = field(default_factory=lambda: [ + "agentview_image", + "robot0_eye_in_hand_image", + ]) + + spectral_norm_policy: bool = True + policy_bottleneck_beta: float = 0.1 + + action_augmentation: bool = True + advanced_augmentation: bool = True + distance_threshold: float = 0.08 + num_neighbors: int = 15 \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/piece_assembly_suboptimal.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/piece_assembly_suboptimal.py new file mode 100644 index 0000000000000000000000000000000000000000..5f4efd1de08ea6f0647fa391660dbe31e53e41ab --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/piece_assembly_suboptimal.py @@ -0,0 +1,27 @@ +from dataclasses import dataclass, field + +from robomimic.algo.iql_diffusion import MultiStepMethod + +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion_spectral_image import IQLDiffusionSpectralImageTrainingConfig + +@dataclass +class PieceAssemblySuboptimalConfig(IQLDiffusionSpectralImageTrainingConfig): + low_dim_keys: list[str] = field(default_factory=lambda: [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + ]) + + rgb_keys: list[str] = field(default_factory=lambda: [ + "agentview_image", + "robot0_eye_in_hand_image", + ]) + + spectral_norm_policy: bool = True + policy_bottleneck_beta: float = 0.001 + + action_augmentation: bool = True + advanced_augmentation: bool = True + distance_threshold: float = 0.15 + num_neighbors: int = 15 \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/real_franka.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/real_franka.py new file mode 100644 index 0000000000000000000000000000000000000000..a37e70fcf1ae62856192efc74324d456df9cad43 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/real_franka.py @@ -0,0 +1,31 @@ +from dataclasses import dataclass, field + +from robomimic.algo.iql_diffusion import MultiStepMethod + +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion import IQLDiffusionTrainingConfig + +@dataclass +class IQLDiffusionImageTrainingConfig(IQLDiffusionTrainingConfig): + low_dim_keys: list[str] = field(default_factory=lambda: [ + "states", + ]) + + rgb_keys: list[str] = field(default_factory=lambda: [ + "front_image", + "wrist_image", + ]) + + diffusion_step_embed_dim: int = 128 + num_epochs: int = 5000 + batch_size: int = 64 + + cache_mode: str | None = 'all' + + spectral_norm_policy: bool = True + policy_bottleneck_beta: float = 0.1 + + action_augmentation: bool = True + advanced_augmentation: bool = True + distance_threshold: float = 0.022 + num_neighbors: int = 15 \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/square.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/square.py new file mode 100644 index 0000000000000000000000000000000000000000..4f56663039ebd22553656913a6ec58c1e4ee6585 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/square.py @@ -0,0 +1,27 @@ +from dataclasses import dataclass, field + +from robomimic.algo.iql_diffusion import MultiStepMethod + +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion_spectral_image import IQLDiffusionSpectralImageTrainingConfig + +@dataclass +class SquareConfig(IQLDiffusionSpectralImageTrainingConfig): + low_dim_keys: list[str] = field(default_factory=lambda: [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + ]) + + rgb_keys: list[str] = field(default_factory=lambda: [ + "agentview_image", + "robot0_eye_in_hand_image", + ]) + + spectral_norm_policy: bool = True + policy_bottleneck_beta: float = 0.1 + + action_augmentation: bool = True + advanced_augmentation: bool = True + distance_threshold: float = 0.15 + num_neighbors: int = 15 \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/square_suboptimal.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/square_suboptimal.py new file mode 100644 index 0000000000000000000000000000000000000000..79acd000509657fbbab3ad4c5729fcae47b443a4 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/square_suboptimal.py @@ -0,0 +1,27 @@ +from dataclasses import dataclass, field + +from robomimic.algo.iql_diffusion import MultiStepMethod + +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion_spectral_image import IQLDiffusionSpectralImageTrainingConfig + +@dataclass +class SquareSuboptimalConfig(IQLDiffusionSpectralImageTrainingConfig): + low_dim_keys: list[str] = field(default_factory=lambda: [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + ]) + + rgb_keys: list[str] = field(default_factory=lambda: [ + "agentview_image", + "robot0_eye_in_hand_image", + ]) + + spectral_norm_policy: bool = True + policy_bottleneck_beta: float = 0.001 + + action_augmentation: bool = True + advanced_augmentation: bool = True + distance_threshold: float = 0.15 + num_neighbors: int = 15 \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/threading.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/threading.py new file mode 100644 index 0000000000000000000000000000000000000000..d9d13dfa0781eee2d95398ff97bcad05b402f165 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/_experiments/threading.py @@ -0,0 +1,27 @@ +from dataclasses import dataclass, field + +from robomimic.algo.iql_diffusion import MultiStepMethod + +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion_spectral_image import IQLDiffusionSpectralImageTrainingConfig + +@dataclass +class ThreadingConfig(IQLDiffusionSpectralImageTrainingConfig): + low_dim_keys: list[str] = field(default_factory=lambda: [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + ]) + + rgb_keys: list[str] = field(default_factory=lambda: [ + "agentview_image", + "robot0_eye_in_hand_image", + ]) + + spectral_norm_policy: bool = True + policy_bottleneck_beta: float = 0.1 + + action_augmentation: bool = True + advanced_augmentation: bool = True + distance_threshold: float = 0.08 + num_neighbors: int = 15 \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/base_iql.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/base_iql.py new file mode 100644 index 0000000000000000000000000000000000000000..1ff0b563011095ccee0e26d5ac482cda10734cb0 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/base_iql.py @@ -0,0 +1,21 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning.base_imitation import ImitationTrainingConfig + +@dataclass +class IQLTrainingConfig(ImitationTrainingConfig): + algo: ImitationAlgorithm = ImitationAlgorithm.IQL + + layer_dims: list[int] = field(default_factory=lambda: [ + 300, + 400 + ]) + + vf_quantile: float = 0.9 + target_tau: float = 0.01 + beta: float = 1.0 + learning_rate: float = 0.0001 + discount_rate: float = 0.99 + + net_arch: str = 'gmm' + gmm_heads: int = 8 \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion.py new file mode 100644 index 0000000000000000000000000000000000000000..b02d07d9d96b8d3bfd95130c1117ef2b68e468cc --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion.py @@ -0,0 +1,196 @@ +from dataclasses import dataclass, field + +from robomimic.algo.iql_diffusion import MultiStepMethod + +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning.base_imitation import ImitationTrainingConfig + +@dataclass +class IQLDiffusionTrainingConfig(ImitationTrainingConfig): + algo: ImitationAlgorithm = ImitationAlgorithm.IDQL + + layer_dims: list[int] = field(default_factory=lambda: [ + 300, + 400, + 300 + ]) + + vf_quantile: float = 0.9 + target_tau: float = 0.01 + beta: float = 1.0 + learning_rate: float = 0.0001 + discount_rate: float = 0.99 + + down_dims: list[int] = field(default_factory=lambda: [ + 256, + 512, + 1024 + ]) + diffusion_step_embed_dim: int = 256 + + multi_step_method: MultiStepMethod = MultiStepMethod.ONE_STEP + + # don't update actor until this epoch + actor_freeze_until_epoch: int | None = None + + observation_horizon: int = 2 + action_horizon: int = 8 + prediction_horizon: int = 16 + + use_bc: bool = False + + bottleneck_value: bool = False + bottleneck_policy: bool = False + + lipschitz: bool = False + lipschitz_slack: bool = False + lipschitz_constant: float = 3.0 + lipschitz_weight: float = 0.005 + lipschitz_denoiser: bool = False + + q_bottleneck_beta: float = 0.2 + policy_bottleneck_beta: float = 0.2 + + spectral_norm_value: bool = False + spectral_norm_policy: bool = False + + late_fusion_key: str | None = 'robot0_gripper_qpos' + late_fusion_layer_index: int = 1 + multiply_late_fusion_key: bool = False + multiply_constant: int = 1 + + use_dino_features: bool = False + + l2_policy: float = 0.0 + l2_value: float = 0.0 + + action_augmentation: bool = False + advanced_augmentation: bool = False + augment_init_cutoff_threshold: int = 50 + augment_init_cutoff_thresh_expert: int = 20 + distance_threshold: float = 0.08 + num_neighbors: int = 10 + augment_play: bool = True + mask_augmentation: bool = False + proprio_keys: list[str] = field(default_factory=lambda: ['robot0_eef_pos', 'robot0_eef_quat']) + + pretrained: bool = False + + # ---- rsm_rise gen_q#265 (RISE-actor sweep) ------------------------------------------------------------- + # expert:play sampling mixture: None = natural (released, uniform over sequences); r = expert:play drawn + # r:1 in expectation (robomimic train.expert_play_ratio -> SequenceDataset.sequence_weights). + expert_play_ratio: float | None = None + # AWR advantage clip (robomimic algo.adv.clip_adv_value); None = released (weights still final-clipped at 100). + clip_adv_value: float | None = None + # opt-in advantage-weighted actor loss for algo=idql (robomimic algo.awr_actor); False = released plain BC. + awr_actor: bool = False + # wave 2 critic fix (gen_q#265): Q/V also train on the kNN-augmented rows (algo.critic_on_augmented) and the + # file's success-flag `dones` are rewritten to terminal-only at load (train.done_mode_terminal_only). + critic_on_augmented: bool = False + done_mode_terminal_only: bool = False + + # ---- rsm_rise BASE_TOPUP (gen_q#287) FAST CRITIC PATH, 2026-09-26 ------------------------------------- + # `critic_only`: train Q/V only, no diffusion-actor loss and no actor update. The flagship's + # `critic:dino` cells take the action proposer from a SEPARATE (published, pixel) checkpoint, so the + # co-trained actor is never read; and the critic's gradients cannot change, because + # _compute_critic_loss/_update_critic never read the actor and the advantage weights are .detach()ed. + # `critic_skip_even_epochs`: reproduce the released critic update SCHEDULE (odd epochs only, which is + # what `action_augmentation=True` implies for the critic) on a run whose augmentation is OFF -- so a + # precomputed-feature run makes the SAME 250k critic updates and still checkpoints at epoch 5000. + critic_only: bool = False + critic_skip_even_epochs: bool = False + + # ---- rsm_rise Stage 3: best-of-N planner (E1) and RSM advantage (E2) ---------------------- + # Every key is copied verbatim into the robomimic algo config (train_robomimic.get_robomimic_config) + # and, at eval time, pushed into the loaded policy with `configure_planner` (eval.load_policy), so the + # eval config -- not the checkpoint -- decides the planner. Hydra: `training.plan_n=64` etc. + # Defaults reproduce the released behaviour (plan_n=None -> one sample; IDQL keeps its N=128 critic + # rollout policy). Setting plan_n (even 1) switches the eval to the plain rollout policy + get_action. + plan_n: int | None = None + plan_rule: str = 'argmax' # argmax | softmax | topk_uniform | random | permuted | argmin + plan_temp: float = 0.2 + plan_topk: int = 8 + plan_chunk: int = 8 + plan_particles: int = 16 + plan_mode: str = 'fold' # d1 | fold | recursive + plan_depth: int = 2 + plan_beta: float = 0.95 + plan_gamma: float = 0.99 + # gen_q#273 -- DINO-WM as TRUE MPC. plan_mode=mpc|mpc_disc rolls the world model OPEN-LOOP for + # plan_mpc_horizon FRAMES = ceil(H / hop_frames) chunks (hop_frames comes from the LOADED model, + # never a hard-coded 8) and scores the terminal latent (mpc) or the gamma-discounted, sum-normalised + # score over the roll-out (mpc_disc). H and gamma are tied by H = 1/(1-gamma), so the launcher + # derives gamma from H and the cell name, the discount and the rolled length cannot disagree. + # 0 = OFF: every non-MPC cell takes the identical code path it took before (additive mode). + plan_mpc_horizon: int = 0 # H in FRAMES (0 = off); gamma = 1 - 1/H + plan_flow_steps: int = 8 + plan_seed: int = -1 + rsm_backend: str = 'mlp' # mlp | dwm | mc | iql + rsm_ckpt: str = '' + rsm_hop_ckpt: str = '' + rsm_feat_stats: str = '' + rsm_img_layout: str = 'chw' + rsm_dwm_module: str = 'dwm_readout' + plan_score: str = 'prob' # prob (mean sigmoid, released) | logit (mean raw logit over particles) + # | prob_log (prob folded in log space: same quantity, total order) + plan_rescore_top: int = 0 # two-stage screening: rescore the top-K of the ranking (0 = off) + plan_particles_rescore: int = 0 # ... with M particles (0 = off) + plan_temperature: float = 0.0 # 0: checkpoint calib.json T (else 1.0); > 0 overrides the sigmoid T + plan_lcb_quantile: float = 0.1 # plan_score=conformal_lcb: particle quantile that ranks (0.1 = 10th pct) + plan_sample_batch: int = 0 # >0: DDPM-sample the candidates in slices of this many rows (0 = off) + plan_max_rows: int = 0 # >0: scorer row-slice width (cand x particles); 0 = rsm_scorer.MAX_ROWS + # coin-terminated beta chain (gen_q#267). plan_mode=chain walks a Bernoulli(p) number of + # beta-hops, p = (gamma-beta)/(gamma*(1-beta)) [ogbench_genq/rsm.py:113], and reads membership + # ONCE at the frozen node; the composed frame offset is then EXACTLY Geom(1-gamma). + # plan_chain_cap=0 => computed from plan_chain_tail_eps (the 1e-3 truncation tail). The cap is + # a truncation GUARD, never a tuning knob -- plan_depth is ignored in chain mode. + plan_chain_cap: int = 0 # 0 = compute from the tail; >0 = explicit cap (sweep only) + plan_chain_tail_eps: float = 1e-3 # P(walk longer than cap) <= this + plan_chain_seed: int = -1 # <0 = follow the cell's eval seed; >=0 = pin the coin/CRN draws + # BEAM_RISE (2026-11-09): plan_mode=beam (robomimic/algo/rsm_beam.py). All default None, and + # planner_kwargs() skips None, so no existing cell's planner_overrides / resume fingerprint changes. + plan_beam_width: int | None = None + plan_beam_branch: int | None = None + plan_beam_depth: int | None = None + plan_beam_root_keep: int | None = None + plan_beam_nwm: int | None = None + plan_beam_beta_t: float | None = None + plan_beam_tail_k: int | None = None + plan_beam_agg: str | None = None + plan_beam_rescore: int | None = None + plan_beam_reward: int | None = None + plan_beam_select: str | None = None + plan_beam_select_q: float | None = None # BEAM_RISE run 6 (gen_q #115 quantile) + plan_beam_lcb_lambda: float | None = None # BEAM_RISE run 6 (gen_q #115 LCB) + rsm_adv_v_expectile: float = 0.5 + rsm_adv_v_samples: int = 16 + rsm_adv_scale: str = 'td' # td | std + rsm_adv_permute: bool = False + + +PLANNER_KEYS = ( + 'plan_n', 'plan_rule', 'plan_temp', 'plan_topk', 'plan_chunk', 'plan_particles', 'plan_mode', + 'plan_depth', 'plan_beta', 'plan_gamma', 'plan_mpc_horizon', 'plan_flow_steps', 'plan_seed', + 'rsm_backend', 'rsm_ckpt', 'rsm_hop_ckpt', 'rsm_feat_stats', 'rsm_img_layout', 'rsm_dwm_module', + 'plan_score', 'plan_rescore_top', 'plan_particles_rescore', 'plan_temperature', 'plan_lcb_quantile', + 'plan_sample_batch', 'plan_max_rows', 'plan_chain_cap', 'plan_chain_tail_eps', 'plan_chain_seed', + 'rsm_adv_v_expectile', 'rsm_adv_v_samples', 'rsm_adv_scale', 'rsm_adv_permute', + # BEAM_RISE 2026-11-09 (None-default: skipped by planner_kwargs unless set) + 'plan_beam_width', 'plan_beam_branch', 'plan_beam_depth', 'plan_beam_root_keep', 'plan_beam_nwm', + 'plan_beam_beta_t', 'plan_beam_tail_k', 'plan_beam_agg', 'plan_beam_rescore', 'plan_beam_reward', 'plan_beam_select', + 'plan_beam_select_q', 'plan_beam_lcb_lambda', +) + + +def planner_kwargs(train_cfg) -> dict: + """The planner/RSM keys of a (hydra) training config as a plain dict (missing keys skipped).""" + out = {} + for k in PLANNER_KEYS: + try: + v = train_cfg[k] if not hasattr(train_cfg, k) else getattr(train_cfg, k) + except Exception: + continue + if v is None and k != 'plan_n': + continue + out[k] = v + return out diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_bottleneck.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_bottleneck.py new file mode 100644 index 0000000000000000000000000000000000000000..252f8e3898ad0e64a726a4712018b1c65128fd4f --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_bottleneck.py @@ -0,0 +1,26 @@ +from dataclasses import dataclass, field + +from robomimic.algo.iql_diffusion import MultiStepMethod + +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion import IQLDiffusionTrainingConfig + +@dataclass +class IQLDiffusionBottleneckTrainingConfig(IQLDiffusionTrainingConfig): + layer_dims: list[int] = field(default_factory=lambda: [ + 300, + 400 + ]) + + down_dims: list[int] = field(default_factory=lambda: [ + 128, + 256, + 512 + ]) + diffusion_step_embed_dim: int = 128 + + bottleneck_value: bool = False + bottleneck_policy: bool = True + + q_bottleneck_beta: float = 0.2 + policy_bottleneck_beta: float = 0.2 \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_image.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_image.py new file mode 100644 index 0000000000000000000000000000000000000000..af6f332b27cbb4f64df47b284afd1e2c0f97e2bd --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_image.py @@ -0,0 +1,36 @@ +from dataclasses import dataclass, field + +from robomimic.algo.iql_diffusion import MultiStepMethod + +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion import IQLDiffusionTrainingConfig + +@dataclass +class IQLDiffusionImageTrainingConfig(IQLDiffusionTrainingConfig): + low_dim_keys: list[str] = field(default_factory=lambda: [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + ]) + + rgb_keys: list[str] = field(default_factory=lambda: [ + "agentview_image", + "robot0_eye_in_hand_image", + ]) + + layer_dims: list[int] = field(default_factory=lambda: [ + 300, + 400, + 300 + ]) + + down_dims: list[int] = field(default_factory=lambda: [ + 512, + 1024, + 2048 + ]) + diffusion_step_embed_dim: int = 128 + num_epochs: int = 5000 + batch_size: int = 64 + + cache_mode: str | None = 'all' \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_image_real.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_image_real.py new file mode 100644 index 0000000000000000000000000000000000000000..df999a2a7f92ca57f6d090621adceee50d9fd444 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_image_real.py @@ -0,0 +1,33 @@ +from dataclasses import dataclass, field + +from robomimic.algo.iql_diffusion import MultiStepMethod + +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion import IQLDiffusionTrainingConfig + +@dataclass +class IQLDiffusionImageTrainingConfig(IQLDiffusionTrainingConfig): + low_dim_keys: list[str] = field(default_factory=lambda: [ + "states", + ]) + + rgb_keys: list[str] = field(default_factory=lambda: [ + "front_image", + "wrist_image", + ]) + + layer_dims: list[int] = field(default_factory=lambda: [ + 300, + 400 + ]) + + down_dims: list[int] = field(default_factory=lambda: [ + 512, + 1024, + 2048 + ]) + diffusion_step_embed_dim: int = 128 + num_epochs: int = 5000 + batch_size: int = 64 + + cache_mode: str | None = 'all' \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_lipschitz.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_lipschitz.py new file mode 100644 index 0000000000000000000000000000000000000000..935de0b6d797d140ad8cdf8254d752935ef75fa0 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_lipschitz.py @@ -0,0 +1,36 @@ +from dataclasses import dataclass, field + +from robomimic.algo.iql_diffusion import MultiStepMethod + +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion import IQLDiffusionTrainingConfig + +@dataclass +class IQLDiffusionLipschitzTrainingConfig(IQLDiffusionTrainingConfig): + layer_dims: list[int] = field(default_factory=lambda: [ + 300, + 400, + 300 + ]) + + down_dims: list[int] = field(default_factory=lambda: [ + 256, + 512, + 1024 + ]) + diffusion_step_embed_dim: int = 256 + + bottleneck_value: bool = False + bottleneck_policy: bool = False + + spectral_norm_value: bool = False + spectral_norm_policy: bool = False + + lipschitz: bool = True + lipschitz_slack: bool = True + lipschitz_constant: float = 3.0 + lipschitz_weight: float = 0.005 + lipschitz_denoiser: bool = True + + q_bottleneck_beta: float = 0.2 + policy_bottleneck_beta: float = 0.2 \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_lipschitz_image.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_lipschitz_image.py new file mode 100644 index 0000000000000000000000000000000000000000..8f8bd517979f48b5e62e94d50d37cf621f6f0820 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_lipschitz_image.py @@ -0,0 +1,48 @@ +from dataclasses import dataclass, field + +from robomimic.algo.iql_diffusion import MultiStepMethod + +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion_image import IQLDiffusionImageTrainingConfig + +@dataclass +class IQLDiffusionLipschitzTrainingConfig(IQLDiffusionImageTrainingConfig): + low_dim_keys: list[str] = field(default_factory=lambda: [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + ]) + + rgb_keys: list[str] = field(default_factory=lambda: [ + "agentview_image", + "robot0_eye_in_hand_image", + ]) + + layer_dims: list[int] = field(default_factory=lambda: [ + 300, + 400, + 300 + ]) + + down_dims: list[int] = field(default_factory=lambda: [ + 512, + 1024, + 2048 + ]) + + diffusion_step_embed_dim: int = 256 + + bottleneck_value: bool = False + bottleneck_policy: bool = False + + spectral_norm_value: bool = False + spectral_norm_policy: bool = False + + lipschitz: bool = True + lipschitz_slack: bool = True + lipschitz_constant: float = 3.0 + lipschitz_weight: float = 0.005 + lipschitz_denoiser: bool = True + + q_bottleneck_beta: float = 0.2 + policy_bottleneck_beta: float = 0.2 \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_no_chunking.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_no_chunking.py new file mode 100644 index 0000000000000000000000000000000000000000..63e9ced4b6ad571d1498dbb8a3f6bb696ab05ec0 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_no_chunking.py @@ -0,0 +1,40 @@ +from dataclasses import dataclass, field + +from robomimic.algo.iql_diffusion import MultiStepMethod + +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning.base_imitation import ImitationTrainingConfig +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion import IQLDiffusionTrainingConfig + +@dataclass +class IQLDiffusionNoChunkingTrainingConfig(IQLDiffusionTrainingConfig): + algo: ImitationAlgorithm = ImitationAlgorithm.IQL_DIFFUSION + + layer_dims: list[int] = field(default_factory=lambda: [ + 300, + 400 + ]) + + vf_quantile: float = 0.9 + target_tau: float = 0.01 + beta: float = 1.0 + learning_rate: float = 0.0001 + discount_rate: float = 0.99 + + down_dims: list[int] = field(default_factory=lambda: [ + 256, + 512, + 1024 + ]) + diffusion_step_embed_dim: int = 256 + + multi_step_method: MultiStepMethod = MultiStepMethod.ONE_STEP + + # don't update actor until this epoch + actor_freeze_until_epoch: int | None = None + + observation_horizon: int = 2 + action_horizon: int = 1 + prediction_horizon: int = 1 + + use_bc: bool = False \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_real_franka.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_real_franka.py new file mode 100644 index 0000000000000000000000000000000000000000..17dac34d733288ee8ec8a89d409c6dca8a880554 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_real_franka.py @@ -0,0 +1,26 @@ +from dataclasses import dataclass, field + +from robomimic.algo.iql_diffusion import MultiStepMethod + +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion_image import IQLDiffusionImageTrainingConfig + +@dataclass +class IQLDiffusionTrainingConfig(IQLDiffusionImageTrainingConfig): + algo: ImitationAlgorithm = ImitationAlgorithm.IQL_DIFFUSION + + low_dim_keys: list[str] = field(default_factory=lambda: [ + "lowdim_ee", + ]) + + rgb_keys: list[str] = field(default_factory=lambda: [ + "agentview_image", + "eye_in_hand_image", + ]) + + # don't update actor until this epoch + actor_freeze_until_epoch: int | None = None + + observation_horizon: int = 2 + action_horizon: int = 8 + prediction_horizon: int = 16 \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_spectral.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_spectral.py new file mode 100644 index 0000000000000000000000000000000000000000..63bc1ea080ac57bf4ddb41a47d36f660bc82f98b --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_spectral.py @@ -0,0 +1,30 @@ +from dataclasses import dataclass, field + +from robomimic.algo.iql_diffusion import MultiStepMethod + +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion import IQLDiffusionTrainingConfig + +@dataclass +class IQLDiffusionSpectralTrainingConfig(IQLDiffusionTrainingConfig): + layer_dims: list[int] = field(default_factory=lambda: [ + 300, + 400, + 300 + ]) + + down_dims: list[int] = field(default_factory=lambda: [ + 256, + 512, + 1024 + ]) + diffusion_step_embed_dim: int = 256 + + bottleneck_value: bool = False + bottleneck_policy: bool = False + + spectral_norm_value: bool = False + spectral_norm_policy: bool = True + + q_bottleneck_beta: float = 0.2 + policy_bottleneck_beta: float = 0.2 \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_spectral_image.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_spectral_image.py new file mode 100644 index 0000000000000000000000000000000000000000..47bc82431331b3bd9cec97447a8f9f397c51e904 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_spectral_image.py @@ -0,0 +1,51 @@ +from dataclasses import dataclass, field + +from robomimic.algo.iql_diffusion import MultiStepMethod + +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion_image import IQLDiffusionImageTrainingConfig + +@dataclass +class IQLDiffusionSpectralImageTrainingConfig(IQLDiffusionImageTrainingConfig): + low_dim_keys: list[str] = field(default_factory=lambda: [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + ]) + + rgb_keys: list[str] = field(default_factory=lambda: [ + "agentview_image", + "robot0_eye_in_hand_image", + ]) + + layer_dims: list[int] = field(default_factory=lambda: [ + 300, + 400, + 300 + ]) + + down_dims: list[int] = field(default_factory=lambda: [ + 512, + 1024, + 2048 + ]) + diffusion_step_embed_dim: int = 256 + num_epochs: int = 5000 + batch_size: int = 64 + + cache_mode: str | None = 'all' + + bottleneck_value: bool = False + bottleneck_policy: bool = False + + spectral_norm_value: bool = False + spectral_norm_policy: bool = True + + q_bottleneck_beta: float = 0.2 + policy_bottleneck_beta: float = 0.2 + + lipschitz: bool = False + lipschitz_slack: bool = False + lipschitz_constant: float = 3.0 + lipschitz_weight: float = 0.005 + lipschitz_denoiser: bool = False \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_spectral_image_real.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_spectral_image_real.py new file mode 100644 index 0000000000000000000000000000000000000000..b3727f4bcecb87a088ccd0521e76f7996fee91a9 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_spectral_image_real.py @@ -0,0 +1,48 @@ +from dataclasses import dataclass, field + +from robomimic.algo.iql_diffusion import MultiStepMethod + +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion import IQLDiffusionTrainingConfig + +@dataclass +class IQLDiffusionSpectralImageTrainingConfig(IQLDiffusionTrainingConfig): + low_dim_keys: list[str] = field(default_factory=lambda: [ + "states", + ]) + + rgb_keys: list[str] = field(default_factory=lambda: [ + "front_image", + "wrist_image", + ]) + + layer_dims: list[int] = field(default_factory=lambda: [ + 300, + 400 + ]) + + down_dims: list[int] = field(default_factory=lambda: [ + 512, + 1024, + 2048 + ]) + diffusion_step_embed_dim: int = 128 + num_epochs: int = 5000 + batch_size: int = 64 + + cache_mode: str | None = 'all' + + bottleneck_value: bool = False + bottleneck_policy: bool = False + + spectral_norm_value: bool = False + spectral_norm_policy: bool = True + + q_bottleneck_beta: float = 0.2 + policy_bottleneck_beta: float = 0.2 + + lipschitz: bool = False + lipschitz_slack: bool = False + lipschitz_constant: float = 3.0 + lipschitz_weight: float = 0.005 + lipschitz_denoiser: bool = False \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_tycho.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_tycho.py new file mode 100644 index 0000000000000000000000000000000000000000..ad259bca0f0be75194df0a0e935ac8690cc2d4b6 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_tycho.py @@ -0,0 +1,41 @@ +from dataclasses import dataclass, field + +from robomimic.algo.iql_diffusion import MultiStepMethod + +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning.base_imitation import ImitationTrainingConfig + +@dataclass +class IQLDiffusionTrainingConfig(ImitationTrainingConfig): + algo: ImitationAlgorithm = ImitationAlgorithm.IQL_DIFFUSION + + low_dim_keys: list[str] = field(default_factory=lambda: [ + "states" + ]) + + layer_dims: list[int] = field(default_factory=lambda: [ + 300, + 400 + ]) + + vf_quantile: float = 0.9 + target_tau: float = 0.01 + beta: float = 1.0 + learning_rate: float = 0.0001 + discount_rate: float = 0.99 + + down_dims: list[int] = field(default_factory=lambda: [ + 256, + 512, + 1024 + ]) + diffusion_step_embed_dim: int = 256 + + multi_step_method: MultiStepMethod = MultiStepMethod.ONE_STEP + + # don't update actor until this epoch + actor_freeze_until_epoch: int | None = None + + observation_horizon: int = 2 + action_horizon: int = 8 + prediction_horizon: int = 16 \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_tycho_image.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_tycho_image.py new file mode 100644 index 0000000000000000000000000000000000000000..12536cd1f2a15a0fb26588b2c1cb254daf573e5a --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/_offline_rl/iql_diffusion_tycho_image.py @@ -0,0 +1,16 @@ +from dataclasses import dataclass, field + +from robomimic.algo.iql_diffusion import MultiStepMethod + +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion_image import IQLDiffusionImageTrainingConfig + +@dataclass +class IQLDiffusionTrainingConfig(IQLDiffusionImageTrainingConfig): + low_dim_keys: list[str] = field(default_factory=lambda: [ + "states", + ]) + + rgb_keys: list[str] = field(default_factory=lambda: [ + "imgs" + ]) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/base_imitation.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/base_imitation.py new file mode 100644 index 0000000000000000000000000000000000000000..589fcf1a59e4de256ffe90a0ecb6105348d35f57 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/base_imitation.py @@ -0,0 +1,32 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import ImitationAlgorithm + +@dataclass +class ImitationTrainingConfig: + algo: ImitationAlgorithm = ImitationAlgorithm.BC_RNN + + resume: bool = True + + low_dim_keys: list[str] = field(default_factory=lambda: [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ]) + + rgb_keys: list[str] = field(default_factory=lambda: [ + ]) + + depth_keys: list[str] = field(default_factory=lambda: [ + ]) + + # only for robomimic, either 'low_dim', 'all' or None + cache_mode: str | None = 'low_dim' + batch_size: int = 100 + num_epochs: int = 2000 + epoch_every_n_steps: int = 100 + + render_video: bool = True + rollout_horizon: int = 200 + + pad_seq_length: bool = True \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/bcrnn_image.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/bcrnn_image.py new file mode 100644 index 0000000000000000000000000000000000000000..965cff5adf2b402bcd5777a1adbab7fbbecfc6b6 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/bcrnn_image.py @@ -0,0 +1,15 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning.base_imitation import ImitationTrainingConfig + +@dataclass +class BCRNNImageTrainingConfig(ImitationTrainingConfig): + algo: ImitationAlgorithm = ImitationAlgorithm.BC_RNN + rgb_keys: list[str] = field(default_factory=lambda: [ + "agentview_image", + "robot0_eye_in_hand_image" + ]) + + batch_size: int = 16 + num_epochs: int = 600 + epoch_every_n_steps: int = 500 \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/discriminator.py b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/discriminator.py new file mode 100644 index 0000000000000000000000000000000000000000..8b859a2fc37ecc2dcf0a3040b725eb9f4382860d --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_imitation_learning/discriminator.py @@ -0,0 +1,11 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import ImitationAlgorithm +from sim_pipeline.configs.training._imitation_learning.base_imitation import ImitationTrainingConfig + +@dataclass +class DiscriminatorTrainingConfig(ImitationTrainingConfig): + algo: ImitationAlgorithm = ImitationAlgorithm.DISCRIMINATOR + + batch_size: int = 100 + num_epochs: int = 10 + epoch_every_n_steps: int = 500 \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_q_transformer/base_q_transformer.py b/code_src/rise_code/sim_pipeline/configs/training/_q_transformer/base_q_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..1652b4140e898ae109381092007a1d0e472afb12 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_q_transformer/base_q_transformer.py @@ -0,0 +1,19 @@ +from dataclasses import dataclass, field +from sim_pipeline.configs.constants import ImitationAlgorithm + +@dataclass +class QTransformerTrainingConfig: + low_dim_keys: list[str] = field(default_factory=lambda: [ + ]) + + rgb_keys: list[str] = field(default_factory=lambda: [ + "agentview_image", + "robot0_eye_in_hand_image", + ]) + + depth_keys: list[str] = field(default_factory=lambda: [ + ]) + + batch_size: int = 16 + num_epochs: int = 10000 + learning_rate: float = 3e-4 \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_reinforcement_learning/base_rl.py b/code_src/rise_code/sim_pipeline/configs/training/_reinforcement_learning/base_rl.py new file mode 100644 index 0000000000000000000000000000000000000000..305dfab2a0d8dcd77dfafd777907a0b11b607633 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_reinforcement_learning/base_rl.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass, field +from enum import Enum +from sim_pipeline.configs.constants import RLAlgorithm + +@dataclass +class RLTrainingConfig: + algo: RLAlgorithm = RLAlgorithm.PPO + total_timesteps: int = 1_000_000 + policy_kwargs: dict = field(default_factory=lambda: { + + }) + policy: str = 'MlpPolicy' + + resume: bool = True \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/_reinforcement_learning/robomimic_ppo.py b/code_src/rise_code/sim_pipeline/configs/training/_reinforcement_learning/robomimic_ppo.py new file mode 100644 index 0000000000000000000000000000000000000000..df96c089759236da680845f9fe331fa5422acc99 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_reinforcement_learning/robomimic_ppo.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass, field +from enum import Enum +from sim_pipeline.configs.constants import RLAlgorithm + +from sim_pipeline.configs.training._reinforcement_learning.base_rl import RLTrainingConfig + +@dataclass +class PPOTrainingConfig(RLTrainingConfig): + algo: RLAlgorithm = RLAlgorithm.PPO + policy_kwargs: dict = field(default_factory=lambda: { + 'net_arch': [128, 128], + }) + policy: str = 'MlpPolicy' diff --git a/code_src/rise_code/sim_pipeline/configs/training/_reinforcement_learning/robomimic_sac.py b/code_src/rise_code/sim_pipeline/configs/training/_reinforcement_learning/robomimic_sac.py new file mode 100644 index 0000000000000000000000000000000000000000..b36fe514ee853e5d7fe54c72984408897cee9467 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/_reinforcement_learning/robomimic_sac.py @@ -0,0 +1,15 @@ +from dataclasses import dataclass, field +from enum import Enum + +from sim_pipeline.configs.constants import RLAlgorithm +from sim_pipeline.configs.data.base_data import BaseDataConfig +from sim_pipeline.configs.training._reinforcement_learning.base_rl import RLTrainingConfig + +@dataclass +class SACTrainingConfig(RLTrainingConfig): + algo: RLAlgorithm = RLAlgorithm.SAC + policy_kwargs: dict = field(default_factory=lambda: { + 'net_arch': [128, 128], + }) + policy: str = 'MlpPolicy' + init_buffer: bool = True \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/configs/training/point_maze.py b/code_src/rise_code/sim_pipeline/configs/training/point_maze.py new file mode 100644 index 0000000000000000000000000000000000000000..405ced4204aa0b053bc0875a643e74f44a7bd87b --- /dev/null +++ b/code_src/rise_code/sim_pipeline/configs/training/point_maze.py @@ -0,0 +1,11 @@ +from dataclasses import dataclass, field +from enum import Enum +from sim_pipeline.configs.constants import RLAlgorithm + +@dataclass +class TrainingConfig: + algo: RLAlgorithm = RLAlgorithm.PPO + policy_kwargs: dict = field(default_factory=lambda: { + + }) + policy: str = 'MultiInputPolicy' diff --git a/code_src/rise_code/sim_pipeline/data_collection/collect_human_demonstrations.py b/code_src/rise_code/sim_pipeline/data_collection/collect_human_demonstrations.py new file mode 100644 index 0000000000000000000000000000000000000000..2abe0766798b381dfa5072b09c16b90c7bb35a02 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_collection/collect_human_demonstrations.py @@ -0,0 +1,122 @@ +import hydra +import time +import json +import os +import torch + +import robomimic.utils.file_utils as FileUtils +from robosuite import load_controller_config +from robosuite.wrappers import DataCollectionWrapper, VisualizationWrapper +from sim_pipeline.configs.constants import IO_Devices +from sim_pipeline.configs._data_collection.data_collection import DataCollectionConfig +from sim_pipeline.data_collection.teleop_utils import collect_human_trajectory, gather_demonstrations_as_hdf5 +from sim_pipeline.envs.make_env import make_env +from sim_pipeline.envs.initialization_wrapper import InitializationWrapper +from sim_pipeline.data_manager.edit_dataset_description import edit_dataset_description + +@hydra.main(version_base=None, config_path='../configs', config_name='data_collection') +def collect(cfg: DataCollectionConfig): + env_config = cfg.env + env_config.data_collection = True + env_config.ignore_done = True + env_config.render = True + if cfg.discriminator and cfg.model_path is not None: + env_config.render_offscreen = True + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + policy, _ = FileUtils.policy_from_checkpoint(ckpt_path=cfg.model_path, device=device, verbose=True, discriminator=True) + else: + env_config.render_offscreen = False + policy = None + + if cfg.model_path is not None and not cfg.discriminator: + env_config.render_offscreen = True + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + policy, _ = FileUtils.policy_from_checkpoint(ckpt_path=cfg.model_path, device=device, verbose=True, discriminator=False) + if cfg.eval_value: + value_function = policy.policy.nets['vf'] + q_function = policy.policy.nets['critic'][0] + else: + value_function = None + q_function = None + else: + value_function = None + q_function = None + + if not cfg.discriminator and not cfg.eval_model: + eval_model = None + + if cfg.record_image_embedding: + env_config.render_offscreen = True + + controller_config = load_controller_config(default_controller='OSC_POSE') + # Create argument configuration + config = { + "env_name": env_config.env_name.value, + "robots": ['Panda'], + "controller_configs": controller_config, + } + + # Create environment + env = make_env(env_config) + if isinstance(env, InitializationWrapper): + env_name = env.env.__class__.__name__ + else: + try: + env_name = env.serialize()['env_name'] + except AttributeError: + env_name = env.__class__.__name__ + + # Wrap this with visualization wrapper + env = VisualizationWrapper(env) + + # Grab reference to controller config and convert it to json-encoded string + env_info = json.dumps(config) + + # wrap the environment with data collection wrapper + tmp_directory = "/tmp/{}".format(str(time.time()).replace(".", "_")) + env = DataCollectionWrapper(env, tmp_directory) + + device = cfg.device.get_device() + + # make a new timestamped directory + t1, t2 = str(time.time()).split(".") + data_name = cfg.data_name + new_dir = os.path.join(cfg.directory, f"{data_name}_{t1}_{t2}") + if not cfg.debug: + os.makedirs(new_dir) + + if cfg.device == IO_Devices.KEYBOARD or cfg.device == IO_Devices.SPACEMOUSE: + # set keyboard repeat delay to be faster for smoother keyboard teleop + # os.system('xset r rate 50 33') + pass + try: + # collect demonstrations + ep = 1 + while True: + continue_collection, success = collect_human_trajectory( + env, + device, + 'right', + 'single-arm-opposed', + print_rew=cfg.print_rew, + eval_model=policy, + lowdim_keys=cfg.lowdim_keys, + rgb_keys=cfg.rgb_keys, + value_function=value_function, + q_function=q_function, + n_obs_steps=cfg.n_obs_steps, + record_image_embedding=cfg.record_image_embedding, + use_dino_features=cfg.use_dino_features, + ) + if success: + print(f'Collected {ep} successful demonstrations\r', end='', flush=True) + ep += 1 + if not cfg.debug: + hdf5_path = gather_demonstrations_as_hdf5(tmp_directory, new_dir, env_info, env_name, data_name) + if not continue_collection: + break + finally: + os.system('xset r rate 500 33') + + if not cfg.debug: + edit_dataset_description(hdf5_path) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/data_collection/keyboard.py b/code_src/rise_code/sim_pipeline/data_collection/keyboard.py new file mode 100644 index 0000000000000000000000000000000000000000..d860feafe4117cc3c4377091265f1dd0f8a1ddce --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_collection/keyboard.py @@ -0,0 +1,183 @@ +""" +Driver class for Keyboard controller. +""" + +import numpy as np +from pynput.keyboard import Controller, Key, Listener + +from robosuite.devices import Device +from robosuite.utils.transform_utils import rotation_matrix +from sim_pipeline.data_collection.spacemouse_hybrid import ResetState + +class Keyboard(Device): + """ + A minimalistic driver class for a Keyboard. + Args: + pos_sensitivity (float): Magnitude of input position command scaling + rot_sensitivity (float): Magnitude of scale input rotation commands scaling + """ + + def __init__(self, pos_sensitivity=1.0, rot_sensitivity=1.0): + + self._display_controls() + self._reset_internal_state() + + self._reset_state = ResetState.CONTINUE + self._enabled = False + self._pos_step = 0.05 + + self.pos_sensitivity = pos_sensitivity + self.rot_sensitivity = rot_sensitivity + + # make a thread to listen to keyboard and register our callback functions + self.listener = Listener(on_press=self.on_press, on_release=self.on_release) + + # start listening + self.listener.start() + + @staticmethod + def _display_controls(): + """ + Method to pretty print controls. + """ + + def print_command(char, info): + char += " " * (10 - len(char)) + print("{}\t{}".format(char, info)) + + print("") + print_command("Keys", "Command") + print_command("q", "reset simulation and discard") + print_command("j", "reset simulation and save") + print_command("spacebar", "toggle gripper (open/close)") + print_command("w-a-s-d", "move arm horizontally in x-y plane") + print_command("r-f", "move arm vertically") + print_command("z-x", "rotate arm about x-axis") + print_command("t-g", "rotate arm about y-axis") + print_command("c-v", "rotate arm about z-axis") + print_command("p", "end data collection") + print("") + + def _reset_internal_state(self): + """ + Resets internal state of controller, except for the reset signal. + """ + self.rotation = np.array([[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]]) + self.raw_drotation = np.zeros(3) # immediate roll, pitch, yaw delta values from keyboard hits + self.last_drotation = np.zeros(3) + self.pos = np.zeros(3) # (x, y, z) + self.last_pos = np.zeros(3) + self.grasp = False + + def start_control(self): + """ + Method that should be called externally before controller can + start receiving commands. + """ + self._reset_internal_state() + self._reset_state = ResetState.CONTINUE + self._enabled = True + self.terminate = False + + def get_controller_state(self): + """ + Grabs the current state of the keyboard. + Returns: + dict: A dictionary containing dpos, orn, unmodified orn, grasp, and reset + """ + + dpos = self.pos - self.last_pos + self.last_pos = np.array(self.pos) + raw_drotation = ( + self.raw_drotation - self.last_drotation + ) # create local variable to return, then reset internal drotation + self.last_drotation = np.array(self.raw_drotation) + # print(raw_drotation, self.rotation, dpos) + return dict( + dpos=dpos, + rotation=self.rotation, + raw_drotation=raw_drotation, + grasp=int(self.grasp), + reset=self._reset_state, + ) + + def on_press(self, key): + """ + Key handler for key presses. + Args: + key (str): key that was pressed + """ + + try: + # controls for moving position + if key.char == "w": + self.pos[0] -= self._pos_step * self.pos_sensitivity # dec x + elif key.char == "s": + self.pos[0] += self._pos_step * self.pos_sensitivity # inc x + elif key.char == "a": + self.pos[1] -= self._pos_step * self.pos_sensitivity # dec y + elif key.char == "d": + self.pos[1] += self._pos_step * self.pos_sensitivity # inc y + elif key.char == "f": + self.pos[2] -= self._pos_step * self.pos_sensitivity # dec z + elif key.char == "r": + self.pos[2] += self._pos_step * self.pos_sensitivity # inc z + + # controls for moving orientation + elif key.char == "z": + drot = rotation_matrix(angle=0.1 * self.rot_sensitivity, direction=[1.0, 0.0, 0.0])[:3, :3] + self.rotation = self.rotation.dot(drot) # rotates x + self.raw_drotation[1] -= 0.1 * self.rot_sensitivity + elif key.char == "x": + drot = rotation_matrix(angle=-0.1 * self.rot_sensitivity, direction=[1.0, 0.0, 0.0])[:3, :3] + self.rotation = self.rotation.dot(drot) # rotates x + self.raw_drotation[1] += 0.1 * self.rot_sensitivity + elif key.char == "t": + drot = rotation_matrix(angle=0.1 * self.rot_sensitivity, direction=[0.0, 1.0, 0.0])[:3, :3] + self.rotation = self.rotation.dot(drot) # rotates y + self.raw_drotation[0] += 0.1 * self.rot_sensitivity + elif key.char == "g": + drot = rotation_matrix(angle=-0.1 * self.rot_sensitivity, direction=[0.0, 1.0, 0.0])[:3, :3] + self.rotation = self.rotation.dot(drot) # rotates y + self.raw_drotation[0] -= 0.1 * self.rot_sensitivity + elif key.char == "c": + drot = rotation_matrix(angle=0.1 * self.rot_sensitivity, direction=[0.0, 0.0, 1.0])[:3, :3] + self.rotation = self.rotation.dot(drot) # rotates z + self.raw_drotation[2] += 0.1 * self.rot_sensitivity + elif key.char == "v": + drot = rotation_matrix(angle=-0.1 * self.rot_sensitivity, direction=[0.0, 0.0, 1.0])[:3, :3] + self.rotation = self.rotation.dot(drot) # rotates z + self.raw_drotation[2] -= 0.1 * self.rot_sensitivity + + except AttributeError as e: + pass + + def on_release(self, key): + """ + Key handler for key releases. + Args: + key (str): key that was pressed + """ + + try: + # controls for grasping + if key == Key.space: + self.grasp = not self.grasp # toggle gripper + + # user-commanded reset + elif key.char == "q": + self._reset_state = ResetState.DISCARD + self._enabled = False + self._reset_internal_state() + elif key.char == "j": + self._reset_state = ResetState.SAVE + self._enabled = False + self._reset_internal_state() + elif key.char == "p": + self._reset_state = ResetState.DISCARD + self._enabled = False + self._reset_internal_state() + self.terminate = True + + except AttributeError as e: + pass diff --git a/code_src/rise_code/sim_pipeline/data_collection/spacemouse_hybrid.py b/code_src/rise_code/sim_pipeline/data_collection/spacemouse_hybrid.py new file mode 100644 index 0000000000000000000000000000000000000000..bf8b1ba4b61be01e154b46450c3435d687dcd44b --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_collection/spacemouse_hybrid.py @@ -0,0 +1,443 @@ +"""Driver class for SpaceMouse controller. + +This class provides a driver support to SpaceMouse on macOS. +In particular, we assume you are using a SpaceMouse Wireless by default. + +To set up a new SpaceMouse controller: + 1. Download and install driver from https://www.3dconnexion.com/service/drivers.html + 2. Install hidapi library through pip + (make sure you run uninstall hid first if it is installed). + 3. Make sure SpaceMouse is connected before running the script + 4. (Optional) Based on the model of SpaceMouse, you might need to change the + vendor id and product id that correspond to the device. + +For Linux support, you can find open-source Linux drivers and SDKs online. + See http://spacenav.sourceforge.net/ + +""" + +import threading +import time +from collections import namedtuple +from pynput.keyboard import Controller, Key, Listener +import numpy as np + +from enum import Enum + +try: + import hid +except ModuleNotFoundError as exc: + raise ImportError( + "Unable to load module hid, required to interface with SpaceMouse. " + "Only macOS is officially supported. Install the additional " + "requirements with `pip install -r requirements-extra.txt`" + ) from exc + +import robosuite.macros as macros +from robosuite.devices import Device +from robosuite.utils.transform_utils import rotation_matrix + +AxisSpec = namedtuple("AxisSpec", ["channel", "byte1", "byte2", "scale"]) + +SPACE_MOUSE_SPEC = { + "x": AxisSpec(channel=1, byte1=1, byte2=2, scale=1), + "y": AxisSpec(channel=1, byte1=3, byte2=4, scale=-1), + "z": AxisSpec(channel=1, byte1=5, byte2=6, scale=-1), + "roll": AxisSpec(channel=1, byte1=7, byte2=8, scale=-1), + "pitch": AxisSpec(channel=1, byte1=9, byte2=10, scale=-1), + "yaw": AxisSpec(channel=1, byte1=11, byte2=12, scale=1), +} + + +def to_int16(y1, y2): + """ + Convert two 8 bit bytes to a signed 16 bit integer. + + Args: + y1 (int): 8-bit byte + y2 (int): 8-bit byte + + Returns: + int: 16-bit integer + """ + x = (y1) | (y2 << 8) + if x >= 32768: + x = -(65536 - x) + return x + + +def scale_to_control(x, axis_scale=350.0, min_v=-1.0, max_v=1.0): + """ + Normalize raw HID readings to target range. + + Args: + x (int): Raw reading from HID + axis_scale (float): (Inverted) scaling factor for mapping raw input value + min_v (float): Minimum limit after scaling + max_v (float): Maximum limit after scaling + + Returns: + float: Clipped, scaled input from HID + """ + x = x / axis_scale + x = min(max(x, min_v), max_v) + return x + + +def convert(b1, b2): + """ + Converts SpaceMouse message to commands. + + Args: + b1 (int): 8-bit byte + b2 (int): 8-bit byte + + Returns: + float: Scaled value from Spacemouse message + """ + return scale_to_control(to_int16(b1, b2)) + +class ResetState(Enum): + CONTINUE = 0 + SAVE = 1 + DISCARD = 2 + +class SpaceMouse(Device): + """ + A minimalistic driver class for SpaceMouse with HID library. + + Note: Use hid.enumerate() to view all USB human interface devices (HID). + Make sure SpaceMouse is detected before running the script. + You can look up its vendor/product id from this method. + + Args: + vendor_id (int): HID device vendor id + product_id (int): HID device product id + pos_sensitivity (float): Magnitude of input position command scaling + rot_sensitivity (float): Magnitude of scale input rotation commands scaling + """ + + def __init__( + self, + vendor_id=macros.SPACEMOUSE_VENDOR_ID, + product_id=macros.SPACEMOUSE_PRODUCT_ID, + pos_sensitivity=1.0, + rot_sensitivity=1.0, + ): + + print("Opening SpaceMouse device") + self.vendor_id = vendor_id + self.product_id = product_id + self.device = hid.device() + self.device.open(self.vendor_id, self.product_id) # SpaceMouse + + self.pos_sensitivity = pos_sensitivity + self.rot_sensitivity = rot_sensitivity + + print("Manufacturer: %s" % self.device.get_manufacturer_string()) + print("Product: %s" % self.device.get_product_string()) + + self._reset_state = ResetState.CONTINUE + self._enabled = False + self._pos_step = 0.05 + + # 6-DOF variables + self.x, self.y, self.z = 0, 0, 0 + self.roll, self.pitch, self.yaw = 0, 0, 0 + + self._display_controls() + + self.single_click_and_hold = False + + self._control = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + self._reset_state = ResetState.CONTINUE + self.rotation = np.array([[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]]) + self._enabled = False + self.raw_drotation = np.zeros(3) + self.last_drotation = np.zeros(3) + + self.hold_q = False + self.hold_value = False + self.eval_policy = False + self.execute_policy = False + self.recording_image_embedding = False + + # launch a new listener thread to listen to SpaceMouse + self.thread = threading.Thread(target=self.run) + self.thread.daemon = True + self.thread.start() + + # make a thread to listen to keyboard and register our callback functions + self.listener = Listener(on_press=self.on_press, on_release=self.on_release) + + # start listening + self.listener.start() + + + @staticmethod + def _display_controls(): + """ + Method to pretty print controls. + """ + + def print_command(char, info): + char += " " * (30 - len(char)) + print("{}\t{}".format(char, info)) + + print("") + print_command("Control", "Command") + print_command("Right button / e", "reset simulation AND SAVE") + print_command("q", "reset simulation AND DISCARD") + print_command("Left button (hold)", "close gripper") + print_command("Move mouse laterally", "move arm horizontally in x-y plane") + print_command("Move mouse vertically", "move arm vertically") + print_command("Twist mouse about z axis", "rotate arm about z axis (yaw control)") + print_command("w-a-s-d", "roll/pitch control") + print_command("p", "end data collection") + print_command("f", "Evaluate the Q function with the current action input") + print_command("g", "Evaluate the value function") + print_command("e", "Run the policy with sampling") + print_command("r", "Just run the policy and visualize marginal policy distribution") + print("") + + def _reset_internal_state(self): + """ + Resets internal state of controller, except for the reset signal. + """ + self.rotation = np.array([[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]]) + # Reset 6-DOF variables + self.x, self.y, self.z = 0, 0, 0 + self.roll, self.pitch, self.yaw = 0, 0, 0 + self.raw_drotation = np.zeros(3) # immediate roll, pitch, yaw delta values from keyboard hits + self.last_drotation = np.zeros(3) + self.pos = np.zeros(3) + self.last_pos = np.zeros(3) + # Reset control + self._control = np.zeros(6) + # Reset grasp + self.single_click_and_hold = False + self.grasp = False + self.hold_q = False + self.hold_value = False + self.eval_policy = False + self.execute_policy = False + self.recording_image_embedding = False + + def start_control(self): + """ + Method that should be called externally before controller can + start receiving commands. + """ + self._reset_internal_state() + self._reset_state = ResetState.CONTINUE + self._enabled = True + self.terminate = False + + def get_controller_state(self): + """ + Grabs the current state of the 3D mouse. + + Returns: + dict: A dictionary containing dpos, orn, unmodified orn, grasp, and reset + """ + dpos = self.control[:3] * 0.005 * self.pos_sensitivity + roll, pitch, yaw = self.control[3:] * 0.005 * self.rot_sensitivity + + raw_drotation = ( + self.raw_drotation - self.last_drotation + ) # create local variable to return, then reset internal drotation + self.last_drotation = np.array(self.raw_drotation) + + # convert RPY to an absolute orientation + drot3 = rotation_matrix(angle=yaw, direction=[0, 0, 1.0], point=None)[:3, :3] + + self.rotation = self.rotation.dot(drot3) + + return dict( + dpos=dpos, + rotation=self.rotation, + raw_drotation=np.array([raw_drotation[0], raw_drotation[1], yaw]), + grasp=self.control_gripper, + reset=self._reset_state, + ) + + def run(self): + """Listener method that keeps pulling new messages.""" + + t_last_click = -1 + + while True: + d = self.device.read(13) + if d is not None and self._enabled: + + if self.product_id == 50741 or self.product_id == 50726: + ## logic for older spacemouse model + + if d[0] == 1: ## readings from 6-DoF sensor + self.y = convert(d[1], d[2]) + self.x = convert(d[3], d[4]) + self.z = convert(d[5], d[6]) * -1.0 + + if d[0] == 2: + + self.roll = convert(d[1], d[2]) + self.pitch = convert(d[3], d[4]) + self.yaw = convert(d[5], d[6]) + + self._control = [ + self.x, + self.y, + self.z, + self.roll, + self.pitch, + self.yaw, + ] + else: + ## default logic for all other spacemouse models + + if d[0] == 1: ## readings from 6-DoF sensor + self.y = convert(d[1], d[2]) + self.x = convert(d[3], d[4]) + self.z = convert(d[5], d[6]) * -1.0 + + self.roll = convert(d[7], d[8]) + self.pitch = convert(d[9], d[10]) + self.yaw = convert(d[11], d[12]) + + self._control = [ + self.x, + self.y, + self.z, + self.roll, + self.pitch, + self.yaw, + ] + + if d[0] == 3: ## readings from the side buttons + + # press left button + if d[1] == 1: + t_click = time.time() + elapsed_time = t_click - t_last_click + t_last_click = t_click + self.single_click_and_hold = not self.single_click_and_hold + + # right button is for reset + if d[1] == 2: + self._reset_state = ResetState.SAVE + self._enabled = False + self._reset_internal_state() + + @property + def control(self): + """ + Grabs current pose of Spacemouse + + Returns: + np.array: 6-DoF control value + """ + return np.array(self._control) + + @property + def control_gripper(self): + """ + Maps internal states into gripper commands. + + Returns: + float: Whether we're using single click and hold or not + """ + if self.single_click_and_hold: + return 1.0 + return 0 + + def on_press(self, key): + """ + Key handler for key presses. + Args: + key (str): key that was pressed + """ + + try: + # controls for moving position + if key.char == "d": + drot = rotation_matrix(angle=0.1 * self.rot_sensitivity, direction=[1.0, 0.0, 0.0])[:3, :3] + self.rotation = self.rotation.dot(drot) # rotates x + self.raw_drotation[1] -= 0.1 * self.rot_sensitivity + elif key.char == "a": + drot = rotation_matrix(angle=-0.1 * self.rot_sensitivity, direction=[1.0, 0.0, 0.0])[:3, :3] + self.rotation = self.rotation.dot(drot) # rotates x + self.raw_drotation[1] += 0.1 * self.rot_sensitivity + elif key.char == "s": + drot = rotation_matrix(angle=0.1 * self.rot_sensitivity, direction=[0.0, 1.0, 0.0])[:3, :3] + self.rotation = self.rotation.dot(drot) # rotates y + self.raw_drotation[0] += 0.1 * self.rot_sensitivity + elif key.char == "w": + drot = rotation_matrix(angle=-0.1 * self.rot_sensitivity, direction=[0.0, 1.0, 0.0])[:3, :3] + self.rotation = self.rotation.dot(drot) # rotates y + self.raw_drotation[0] -= 0.1 * self.rot_sensitivity + elif key.char == "f": + self.hold_q = True + elif key.char == "g": + self.hold_value = True + elif key.char == "h": + self.execute_policy = True + elif key.char == "r": + self.eval_policy = True + elif key.char == 'z': + self.recording_image_embedding = True + + except AttributeError as e: + pass + + def on_release(self, key): + """ + Key handler for key releases. + Args: + key (str): key that was pressed + """ + + try: + # controls for grasping + if key == Key.space: + self.grasp = not self.grasp # toggle gripper + + # user-commanded reset + elif key.char == "q": + self._reset_state = ResetState.DISCARD + self._enabled = False + self._reset_internal_state() + elif key.char == "e": + self._reset_state = ResetState.SAVE + self._enabled = False + self._reset_internal_state() + + elif key.char == "e": + self._reset_state = ResetState.SAVE + self._enabled = False + self._reset_internal_state() + + elif key.char == "p": + self._reset_state = ResetState.DISCARD + self._enabled = False + self._reset_internal_state() + self.terminate = True + elif key.char == "f": + self.hold_q = False + elif key.char == "g": + self.hold_value = False + elif key.char == "h": + self.execute_policy = False + elif key.char == "r": + self.eval_policy = False + elif key.char == "z": + self.recording_image_embedding = False + + except AttributeError as e: + pass + +if __name__ == "__main__": + + space_mouse = SpaceMouse() + for i in range(100): + print(space_mouse.control, space_mouse.control_gripper) + time.sleep(0.02) diff --git a/code_src/rise_code/sim_pipeline/data_collection/teleop_utils.py b/code_src/rise_code/sim_pipeline/data_collection/teleop_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bbeafce9dbce9fc15d41111976a332aa51911126 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_collection/teleop_utils.py @@ -0,0 +1,573 @@ +from collections import deque +import h5py +import datetime +import os +import numpy as np +import robosuite as suite +import uuid +import getpass +import torch +import robomimic.utils.tensor_utils as TensorUtils +import robosuite.utils.transform_utils as T + +from scipy.spatial.transform import Rotation as R +from glob import glob +from robosuite.devices import * +from robosuite.models.robots import * +from robosuite.robots import * +from sim_pipeline.data_collection.spacemouse_hybrid import SpaceMouse as SpaceMouseHybrid +from sim_pipeline.data_collection.spacemouse_hybrid import ResetState +from sim_pipeline.data_collection.keyboard import Keyboard +from sim_pipeline.data_manager.dataset_metadata_enums import * + +def input2action(device, robot, active_arm="right", env_configuration=None): + """ + Converts an input from an active device into a valid action sequence that can be fed into an env.step() call + + If a reset is triggered from the device, immediately returns None. Else, returns the appropriate action + + Args: + device (Device): A device from which user inputs can be converted into actions. Can be either a Spacemouse or + Keyboard device class + + robot (Robot): Which robot we're controlling + + active_arm (str): Only applicable for multi-armed setups (e.g.: multi-arm environments or bimanual robots). + Allows inputs to be converted correctly if the control type (e.g.: IK) is dependent on arm choice. + Choices are {right, left} + + env_configuration (str or None): Only applicable for multi-armed environments. Allows inputs to be converted + correctly if the control type (e.g.: IK) is dependent on the environment setup. Options are: + {bimanual, single-arm-parallel, single-arm-opposed} + + Returns: + 2-tuple: + + - (None or np.array): Action interpreted from @device including any gripper action(s). None if we get a + reset signal from the device + - (None or int): 1 if desired close, -1 if desired open gripper state. None if get a reset signal from the + device + + """ + state = device.get_controller_state() + # Note: Devices output rotation with x and z flipped to account for robots starting with gripper facing down + # Also note that the outputted rotation is an absolute rotation, while outputted dpos is delta pos + # Raw delta rotations from neutral user input is captured in raw_drotation (roll, pitch, yaw) + dpos, rotation, raw_drotation, grasp, reset = ( + state["dpos"], + state["rotation"], + state["raw_drotation"], + state["grasp"], + state["reset"], + ) + + # If we're resetting, immediately return None + if isinstance(reset, ResetState) and reset == ResetState.SAVE or reset == ResetState.DISCARD: + return reset, None + elif not isinstance(reset, ResetState) and reset: + return None, None + + # Get controller reference + controller = robot.controller if not isinstance(robot, Bimanual) else robot.controller[active_arm] + gripper_dof = robot.gripper.dof if not isinstance(robot, Bimanual) else robot.gripper[active_arm].dof + + # First process the raw drotation + drotation = raw_drotation[[1, 0, 2]] + if controller.name == "IK_POSE": + # If this is panda, want to swap x and y axis + if isinstance(robot.robot_model, Panda): + drotation = drotation[[1, 0, 2]] + else: + # Flip x + drotation[0] = -drotation[0] + # Scale rotation for teleoperation (tuned for IK) + drotation *= 10 + dpos *= 5 + # relative rotation of desired from current eef orientation + # map to quat + drotation = T.mat2quat(T.euler2mat(drotation)) + + # If we're using a non-forward facing configuration, need to adjust relative position / orientation + if env_configuration == "single-arm-opposed": + # Swap x and y for pos and flip x,y signs for ori + dpos = dpos[[1, 0, 2]] + drotation[0] = -drotation[0] + drotation[1] = -drotation[1] + if active_arm == "left": + # x pos needs to be flipped + dpos[0] = -dpos[0] + else: + # y pos needs to be flipped + dpos[1] = -dpos[1] + + # Lastly, map to axis angle form + drotation = T.quat2axisangle(drotation) + + elif controller.name == "OSC_POSE": + # Flip z + drotation[2] = -drotation[2] + # Scale rotation for teleoperation (tuned for OSC) -- gains tuned for each device + drotation[0] = drotation[0] * 1.5 if isinstance(device, (Keyboard, SpaceMouseHybrid)) else drotation[0] * 50 + drotation[1] = drotation[1] * 1.5 if isinstance(device, (Keyboard, SpaceMouseHybrid)) else drotation[1] * 50 + drotation[2] = drotation[2] * 1.5 if isinstance(device, (Keyboard)) else drotation[2] * 50 + dpos = dpos * 75 if isinstance(device, (Keyboard)) else dpos * 125 + elif controller.name == "OSC_POSITION": + dpos = dpos * 75 if isinstance(device, (Keyboard)) else dpos * 125 + else: + # No other controllers currently supported + print("Error: Unsupported controller specified -- Robot must have either an IK or OSC-based controller!") + + # map 0 to -1 (open) and map 1 to 1 (closed) + grasp = 1 if grasp else -1 + + # Create action based on action space of individual robot + if controller.name == "OSC_POSITION": + action = np.concatenate([dpos, [grasp] * gripper_dof]) + else: + action = np.concatenate([dpos, drotation, [grasp] * gripper_dof]) + + # Return the action and grasp + return action, grasp + + +def collect_human_trajectory( + env, + device, + arm, + env_configuration, + print_rew=False, + eval_model=None, + lowdim_keys=None, + rgb_keys=None, + value_function=None, + q_function=None, + discriminator=False, + n_obs_steps=2, + record_image_embedding=False, + use_dino_features=False, +) -> tuple[bool, bool]: + """ + Use the device (keyboard or SpaceNav 3D mouse) to collect a demonstration. + The rollout trajectory is saved to files in npz format. + Modify the DataCollectionWrapper wrapper to add new fields or change data formats. + + Args: + env (MujocoEnv): environment to control + device (Device): to receive controls from the device + arms (str): which arm to control (eg bimanual) 'right' or 'left' + env_configuration (str): specified environment configuration + + Returns: + whether or not data collection should continue, and whether the demonstration was successful + (should be saved) + """ + + obs = env.reset() + + if use_dino_features: + if 'object' in lowdim_keys or 'object-state' in lowdim_keys: + # remove object from lowdim_keys + lowdim_keys = [k for k in lowdim_keys if k != 'object' and k != 'object-state'] + + # ID = 2 always corresponds to agentview + env.render() + + is_first = True + + task_completion_hold_count = -1 # counter to collect 10 timesteps after reaching goal + device.start_control() + last_action = None + + success = False + num_actions = 0 + + if eval_model is not None and not discriminator: + obs_stack = deque(maxlen=n_obs_steps) + # append the first obs twice to make sure the queue is full + obs_stack.append(obs) + obs_stack.append(obs) + + if record_image_embedding or use_dino_features: + from robomimic.models.obs_core import DinoV2Core + feature_model = DinoV2Core(input_shape=(3, 84, 84), backbone_name='dinov2_vits14', frozen=True, concatenate=True) + feature_model.eval() + model_device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + feature_model.to(model_device) + if use_dino_features: + if 'dino_features' not in obs: + dino_features = run_feature_extractor(obs, feature_model, lowdim_keys, rgb_keys, normalize=False) + obs['dino_features'] = dino_features + + render_positions = False + image_embedding = None + lowdim_embedding = None + embedding_toggle = False + action_queue = deque() + # Loop until we get a reset from the input or the task completes + while True: + # Set active robot + active_robot = env.robots[0] if env_configuration == "bimanual" else env.robots[arm == "left"] + + # Get the newest action + action, grasp = input2action( + device=device, robot=active_robot, active_arm=arm, env_configuration=env_configuration + ) + # If action is none, then this a reset so we should break + if action is None or (isinstance(action , ResetState) and (action == ResetState.DISCARD or action == ResetState.SAVE)): + # record one last succesful step to make sure data is saved if required + if action == ResetState.SAVE and last_action is not None: + state = env.env.sim.get_state().flatten() + env.states.append(state) + info = {} + info['actions'] = np.zeros_like(last_action) + env.action_infos.append(info) + env.successful = True + success = True + break + + if device.hold_q: + if q_function is not None: + if use_dino_features: + q = run_value_function(obs, action, q_function, lowdim_keys + ['dino_features'], [], eval_batch=False) + else: + q = run_value_function(obs, action, q_function, lowdim_keys, rgb_keys, eval_batch=False) + print('Q: ', q) + continue + elif device.hold_value: + if value_function is not None: + if use_dino_features: + v = run_value_function(obs, None, value_function, lowdim_keys + ['dino_features'], [], eval_batch=False) + else: + v = run_value_function(obs, None, value_function, lowdim_keys, rgb_keys, eval_batch=False) + print('Value: ', v) + continue + elif device.execute_policy or device.eval_policy: + if eval_model is not None and not discriminator: + stacked_obs = {k: np.stack([obs[k] for obs in obs_stack], axis=0) for k in obs_stack[0].keys()} + + if use_dino_features: + actions = run_policy(stacked_obs, eval_model, lowdim_keys + ['dino_features'], [], num_actions=32) + else: + actions = run_policy(stacked_obs, eval_model, lowdim_keys, rgb_keys, num_actions=64) + actions = actions.detach().cpu().numpy() + + act_xyz = actions[:, :, :3] # Shape (N, horizon, 3) + current_eef_pos = obs['robot0_eef_pos'][:3] # Shape (3,) + + all_positions = [] + # For each trajectory, compute the sequence of eef positions + for traj_actions in act_xyz: # traj_actions shape: (horizon, 3) + # Compute cumulative positions by adding delta actions + positions = np.zeros((len(traj_actions) + 1, 3)) + positions[0] = current_eef_pos # First position + for i in range(len(traj_actions)): + positions[i+1] = positions[i] + traj_actions[i] * 0.2 + all_positions.append(positions) + if use_dino_features: + q_vals = run_value_function(obs, actions[:, 0, :], q_function, lowdim_keys + ['dino_features'], [], eval_batch=True) + else: + q_vals = run_value_function(obs, actions[:, 0, :], q_function, lowdim_keys, rgb_keys, eval_batch=True) + + render_positions = True + + device_action = action + if device.execute_policy: + if len(action_queue) == 0: + best_idx = np.argmax(q_vals.detach().cpu().numpy()) + for action in actions[best_idx]: + action_queue.append(action) + action = action_queue.popleft() + action += device_action + + if device.recording_image_embedding: + if not embedding_toggle: + if image_embedding is None: + print('First embedding') + image_embedding = run_feature_extractor(obs, feature_model, lowdim_keys, rgb_keys) + print(image_embedding) + lowdim_embedding = get_lowdim_embedding(obs, lowdim_keys) + embedding_toggle = True + else: + print('Second embedding') + second_embedding = run_feature_extractor(obs, feature_model, lowdim_keys, rgb_keys) + second_lowdim_embedding = get_lowdim_embedding(obs, lowdim_keys) + euclidean_distance = np.linalg.norm(image_embedding - second_embedding) + lowdim_euclidean_distance = np.linalg.norm(lowdim_embedding - second_lowdim_embedding) + print('Image Embedding distance: ', euclidean_distance) + print('Lowdim distance: ', lowdim_euclidean_distance) + # # compute cosine similarity + # cosine_similarity = np.dot(image_embedding, second_embedding) / (np.linalg.norm(image_embedding) * np.linalg.norm(second_embedding)) + # print('Cosine similarity: ', cosine_similarity) + image_embedding = None + embedding_toggle = True + else: + if embedding_toggle: + embedding_toggle = False + + # Run environment step + obs, rew, _, _ = env.step(action) + if use_dino_features: + if 'dino_features' not in obs: + dino_features = run_feature_extractor(obs, feature_model, lowdim_keys, rgb_keys, normalize=False) + obs['dino_features'] = dino_features + + if eval_model is not None and not discriminator: + obs_stack.append(obs) + elif eval_model is not None and discriminator: + output = run_policy(obs, eval_model, lowdim_keys, rgb_keys) + print(output) + + last_action = action + + # print(obs['robot0_eef_pos']) + + if print_rew: + print(rew) + if render_positions: + # Convert q_values to colors using a colormap + q_values = q_vals.detach().cpu().numpy().flatten() + # Normalize q_values to [0,1] range + q_norm = (q_values - q_values.min()) / (q_values.max() - q_values.min()) + # Use blue (low) to red (high) colormap, with highest value black + colors = np.zeros((len(q_values), 4)) + colors[:, 0] = q_norm # Red channel + colors[:, 2] = 1 - q_norm # Blue channel + colors[:, 3] = 0.2 # Alpha channel + + # Set highest q-value trajectory to green + max_idx = np.argmax(q_values) + colors[max_idx] = [0, 1, 0, 0.2] # Green with same alpha + + for positions, color in zip(all_positions, colors): + # visualize only after stepping to avoid putting the trajectory into the observation + env.visualize_trajectory(points=positions, rgba=color, radius=0.005) + render_positions = False + env.render() + env.clear_all_markers() + + # Also break if we complete the task + if task_completion_hold_count == 0: + success = True + break + + if device.terminate: + env.close() + return False, False + + # state machine to check for having a success for 10 consecutive timesteps + if env._check_success(): + if task_completion_hold_count > 0: + task_completion_hold_count -= 1 # latched state, decrement count + else: + task_completion_hold_count = 10 # reset count on first success timestep + else: + task_completion_hold_count = -1 # null the counter if there's no success + + # cleanup for end of data collection episodes + env.close() + + return True, success + +def get_lowdim_embedding(obs, lowdim_keys): + lowdim_obs = [obs[k] for k in lowdim_keys] + return np.concatenate(lowdim_obs) + +def run_feature_extractor(obs, model, lowdim_keys, rgb_keys, normalize=True): + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + obs_dict = {k: obs[k] for k in lowdim_keys + rgb_keys} + features = [] + for k in sorted(rgb_keys): + if 'image' in k: + # flip H + obs_dict[k] = obs_dict[k][::-1] + obs_dict[k] = obs_dict[k].transpose(2, 0, 1) / 255.0 + ob = torch.from_numpy(obs_dict[k].copy()) + ob = ob.unsqueeze(0) + ob = ob.to(device) + ob = ob.float() + features.append(model(ob)) + + # concatenate features + features = torch.cat(features, dim=1).detach().cpu().numpy().flatten() + if normalize: + features = features / np.linalg.norm(features) + return features + +def run_value_function(obs, actions, model, lowdim_keys, rgb_keys, eval_batch=True): + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + + obs_dict = {k: obs[k] for k in lowdim_keys + rgb_keys} + + # replace 'object-state' with 'object' in obs + if 'object-state' in obs_dict: + obs_dict['object'] = obs_dict['object-state'] + del obs_dict['object-state'] + + for k in obs_dict.keys(): + if obs_dict[k].ndim == 3: + obs_dict[k] = obs_dict[k][::-1] + obs_dict[k] = obs_dict[k].transpose(2, 0, 1) + elif obs_dict[k].ndim == 4: + # image is (T, H, W, C) + # first, flip H + obs_dict[k] = obs_dict[k][:, ::-1] + # then, transpose to (T, C, H, W) + obs_dict[k] = obs_dict[k].transpose(0, 3, 1, 2) + # scale from (0, 255) to (0, 1) + obs_dict[k] = obs_dict[k].astype(float) / 255.0 + ob = TensorUtils.to_tensor(obs_dict) + ob = TensorUtils.to_batch(ob) + if eval_batch: + ob = {k: ob[k].repeat(actions.shape[0], *([1] * (len(ob[k].shape) - 1))) for k in ob} + ob = TensorUtils.to_device(ob, device) + ob = TensorUtils.to_float(ob) + + if actions is not None: + actions = TensorUtils.to_tensor(actions) + if not eval_batch: + actions = TensorUtils.to_batch(actions) + actions = TensorUtils.to_device(actions, device) + actions = TensorUtils.to_float(actions) + + if actions is not None: + predictions = model(obs_dict=ob, acts=actions) + else: + predictions = model(obs_dict=ob) + return predictions + +def run_policy(obs, model, lowdim_keys, rgb_keys, num_actions=1): + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + + obs_dict = {k: obs[k] for k in lowdim_keys + rgb_keys} + + # replace 'object-state' with 'object' in obs + if 'object-state' in obs_dict: + obs_dict['object'] = obs_dict['object-state'] + del obs_dict['object-state'] + + for k in obs_dict.keys(): + if 'image' in k: + # flip H + if obs_dict[k].ndim == 3: + obs_dict[k] = obs_dict[k][::-1] + obs_dict[k] = obs_dict[k].transpose(2, 0, 1) + elif obs_dict[k].ndim == 4: + # image is (T, H, W, C) + # first, flip H + obs_dict[k] = obs_dict[k][:, ::-1] + # then, transpose to (T, C, H, W) + obs_dict[k] = obs_dict[k].transpose(0, 3, 1, 2) + # scale from (0, 255) to (0, 1) + obs_dict[k] = obs_dict[k].astype(float) / 255.0 + ob = TensorUtils.to_tensor(obs_dict) + ob = TensorUtils.to_batch(ob) + + # repeat the observation num_actions times + ob = {k: ob[k].repeat(num_actions, *([1] * (len(ob[k].shape) - 1))) for k in ob} + + ob = TensorUtils.to_device(ob, device) + ob = TensorUtils.to_float(ob) + + predictions = model.policy.get_action(ob) + return predictions + + +def gather_demonstrations_as_hdf5(directory, out_dir, env_info, env_name, data_name): + """ + Gathers the demonstrations saved in @directory into a + single hdf5 file. + + The strucure of the hdf5 file is as follows. + + data (group) + date (attribute) - date of collection + time (attribute) - time of collection + repository_version (attribute) - repository version used during collection + env (attribute) - environment name on which demos were collected + + demo1 (group) - every demonstration has a group + model_file (attribute) - model xml string for demonstration + states (dataset) - flattened mujoco states + actions (dataset) - actions applied during demonstration + + demo2 (group) + ... + + Args: + directory (str): Path to the directory containing raw demonstrations. + out_dir (str): Path to where to store the hdf5 file. + env_info (str): JSON-encoded string containing environment information, + including controller and robot info + """ + + hdf5_path = os.path.join(out_dir, f"{data_name}.hdf5") + f = h5py.File(hdf5_path, "w") + + # store some metadata in the attributes of one group + grp = f.create_group("data") + + num_eps = 0 + + for ep_directory in os.listdir(directory): + + state_paths = os.path.join(directory, ep_directory, "state_*.npz") + states = [] + actions = [] + success = False + + for state_file in sorted(glob(state_paths)): + dic = np.load(state_file, allow_pickle=True) + + states.extend(dic["states"]) + for ai in dic["action_infos"]: + actions.append(ai["actions"]) + success = success or dic["successful"] + + if len(states) == 0: + continue + + # Add only the successful demonstration to dataset + if success: + # print("Demonstration is successful and has been saved") + # Delete the last state. This is because when the DataCollector wrapper + # recorded the states and actions, the states were recorded AFTER playing that action, + # so we end up with an extra state at the end. + del states[-1] + assert len(states) == len(actions) + + ep_data_grp = grp.create_group("demo_{}".format(num_eps)) + num_eps += 1 + + # store model xml as an attribute + xml_path = os.path.join(directory, ep_directory, "model.xml") + with open(xml_path, "r") as f: + xml_str = f.read() + ep_data_grp.attrs["model_file"] = xml_str + + # write datasets for states and actions + ep_data_grp.create_dataset("states", data=np.array(states)) + ep_data_grp.create_dataset("actions", data=np.array(actions)) + else: + pass + # print("Demonstration is unsuccessful and has NOT been saved") + + # write dataset attributes (metadata) + now = datetime.datetime.now() + grp.attrs["date"] = "{}-{}-{}".format(now.month, now.day, now.year) + grp.attrs["time"] = "{}:{}:{}".format(now.hour, now.minute, now.second) + grp.attrs["repository_version"] = suite.__version__ + grp.attrs["env"] = env_name + grp.attrs["env_info"] = env_info + grp.attrs["creator"] = getpass.getuser() + + grp.attrs['dataset_id'] = str(uuid.uuid4()) + grp.attrs['env_name'] = env_name + grp.attrs['env_type'] = EnvType.ROBOSUITE.value + grp.attrs['dataset_type'] = DatasetType.PLAY.value + grp.attrs['action_type'] = ActionType.RELATIVE.value + grp.attrs['is_real'] = False + grp.attrs['is_test'] = data_name == 'test' + + f.close() + + return hdf5_path \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/data_manager/change_image_dataset.py b/code_src/rise_code/sim_pipeline/data_manager/change_image_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..9e892b1ef6810074f268bee87ddfbeb03fb9ae2f --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_manager/change_image_dataset.py @@ -0,0 +1,66 @@ +import click +import os +import h5py +import uuid +import numpy as np + +from contextlib import nullcontext +from robomimic.scripts.split_train_val import split_train_val_from_hdf5 + +@click.command() +@click.option('--dataset', '-d', help='Datset file path') +@click.option('--output_name', '-o', help='Output file name') +def relabel_dataset_rewards(dataset, output_name): + print(f'Relabeling rewards in dataset {dataset}') + # output file in same directory as input file + output_path = os.path.join(os.path.dirname(dataset), output_name) + + with ( + h5py.File(dataset, 'r') as f, + h5py.File(output_path, 'w') as f_relabeled, + ): + data = f['data'] + out_data = f_relabeled.create_group("data") + + demo_counter = 0 + for ep_key in data: + ep = data[ep_key] + + data.copy( + source=ep, + dest=out_data, + name=f'demo_{demo_counter}' + ) + out_data_grp = out_data[f'demo_{demo_counter}'] + + # Reshape image from (episode_len, H, W, 3) to (episode_len, 3, 1, 80, 80) + image = out_data_grp['obs']['agentview_image'][:] + # First reshape to move channels dimension + image = np.transpose(image, (0, 3, 1, 2)) + # Get current dimensions + _, _, h, w = image.shape + # Center crop to 80x80 + h_start = (h - 80) // 2 + w_start = (w - 80) // 2 + image = image[:, :, h_start:h_start+80, w_start:w_start+80] + # Add singleton dimension + image = np.expand_dims(image, axis=2) + out_data_grp['obs']['agentview_image'][:] = image + demo_counter += 1 + + # copy episode attributes + for key, val in ep.attrs.items(): + out_data_grp.attrs[key] = val + + # copy dataset attributes + for key, val in data.attrs.items(): + if key == 'dataset_id': + out_data.attrs[key] = str(uuid.uuid4()) + else: + out_data.attrs[key] = val + + # recreate the train-validation split + split_train_val_from_hdf5(hdf5_path=output_path, val_ratio=0.1) + +if __name__ == "__main__": + relabel_dataset_rewards() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/data_manager/chop_dataset.py b/code_src/rise_code/sim_pipeline/data_manager/chop_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..3e05d1ed7bdf0be3c2cb5f72822e0334b455f9d5 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_manager/chop_dataset.py @@ -0,0 +1,77 @@ +import click +import os +import h5py +import uuid +import numpy as np +import random + +from robomimic.scripts.split_train_val import split_train_val_from_hdf5 + +@click.command() +@click.option('--dataset', '-d', help='Dataset file path') +@click.option('--output_name', '-o', help='Output file name') +@click.option('--proportion', '-p', type=click.FloatRange(0, 1), help='Proportion of dataset to keep', default=1.0) +@click.option('--amount', '-n', type=click.IntRange(0), help='Number of demos to keep', default=None) +@click.option('--randomize', '-r', is_flag=True, help='Randomize the selection of episodes') +def chop_dataset(dataset, output_name, proportion, amount, randomize): + print(f'Chopping dataset {dataset}') + if proportion == 0 or (amount is not None and amount == 0): + raise ValueError("No demos to keep") + # output file in same directory as input file + output_path = os.path.join(os.path.dirname(dataset), output_name) + + with ( + h5py.File(dataset, 'r') as f, + h5py.File(output_path, 'w') as f_filtered + ): + data = f['data'] + out_data = f_filtered.create_group("data") + + num_demos = len(data.keys()) + if amount is not None: + demos_to_keep = min(amount, num_demos) + else: + demos_to_keep = int(num_demos * proportion) + + demo_keys = list(data.keys()) + if randomize: + random.shuffle(demo_keys) + + new_demos = [] + new_total = 0 + demo_counter = 0 + for ep_key in demo_keys: + if demo_counter >= demos_to_keep: + break + ep = data[ep_key] + new_demos.append(ep_key) + new_total += ep['actions'].shape[0] + + data.copy( + source=ep, + dest=out_data, + name=f'demo_{demo_counter}' + ) + out_data_grp = out_data[f'demo_{demo_counter}'] + demo_counter += 1 + + # copy episode attributes + for key, val in ep.attrs.items(): + out_data_grp.attrs[key] = val + + # copy dataset attributes + for key, val in data.attrs.items(): + if key == 'total': + out_data.attrs[key] = new_total + elif key == 'dataset_id': + out_data.attrs[key] = str(uuid.uuid4()) + elif key == 'description': + out_data.attrs[key] = val + f' chopped w/ {demos_to_keep} demos' + else: + out_data.attrs[key] = val + + # recreate the train-validation split + split_train_val_from_hdf5(hdf5_path=output_path, val_ratio=0.1) + +if __name__ == "__main__": + chop_dataset() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/data_manager/combine_datasets.py b/code_src/rise_code/sim_pipeline/data_manager/combine_datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..bfd92c3dc5d4cedefce4390e34e63cbbdfaa6423 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_manager/combine_datasets.py @@ -0,0 +1,142 @@ +import h5py +import json +import numpy as np +import click +import uuid + +from sim_pipeline.configs.constants import COMBINED_DATA_DIR + +def copy_group(in_group, out_group): + for key in in_group.keys(): + item = in_group[key] + if isinstance(item, h5py.Group): + new_group = out_group.create_group(key) + for attr_key, attr_value in item.attrs.items(): + new_group.attrs[attr_key] = attr_value + copy_group(item, new_group) + else: + # is a dataset + out_dataset = out_group.create_dataset(key, data=item[:]) + for attr_key, attr_value in item.attrs.items(): + out_dataset.attrs[attr_key] = attr_value + + +def normalize(arr, stats): + min_val, max_val = stats["min"], stats["max"] + return 2 * (arr - min_val) / (max_val - min_val + 1e-7) - 1 + + +def unnormalize(arr, stats): + min_val, max_val = stats["min"], stats["max"] + return 0.5 * (arr + 1) * (max_val - min_val) + min_val + + +@click.command() +@click.option('--datasets', '-d', help='Dataset file path(s)', multiple=True) +@click.option('--output_name', '-o', help='Output file name') +def combine_datasets_command(datasets, output_name): + combine_datasets(datasets, output_name, default_stem=True) + +def combine_datasets(input_files: list[str], output_file: str, default_stem: bool = False): + # combine hdf5 datasets together. to combine attrs, all copies should be stored + # in a list with the same keys. + + if default_stem: + output_file = f'{COMBINED_DATA_DIR}/{output_file}' + + with h5py.File(output_file, 'w') as out_f: + data_group = out_f.create_group('data') + mask_group = out_f.create_group('mask') + combined_attrs = {} + episode_counter = {} + combined_masks = {} + + for input_file in input_files: + with h5py.File(input_file, 'r') as in_f: + in_data_group = in_f['data'] + old_key_to_new = {} + + for episode_key in in_data_group.keys(): + # i.e. base_key = 'demo + base_key = episode_key.split('_')[0] + if base_key not in episode_counter: + episode_counter[base_key] = 0 + else: + episode_counter[base_key] += 1 + + new_key = f'{base_key}_{episode_counter[base_key]}' + old_key_to_new[episode_key] = new_key + + episode_group = data_group.create_group(new_key) + in_episode_group = in_data_group[episode_key] + # Copy attributes + for attr_key, attr_value in in_episode_group.attrs.items(): + episode_group.attrs[attr_key] = attr_value + + copy_group(in_episode_group, episode_group) + + for attr_key, attr_value in in_data_group.attrs.items(): + if attr_key in ['derived_from', 'combined']: + continue + + if attr_key == 'description': + if attr_key not in combined_attrs: + combined_attrs[attr_key] = 'Combined: ' + combined_attrs[attr_key] += attr_value + ' | ' + combined_attrs[attr_key] = combined_attrs[attr_key].replace('\n', '') + continue + + if attr_key == 'dataset_id': + attr_key = 'constituent_dataset_id' + + if attr_key == 'env_args': + combined_attrs[attr_key] = attr_value + continue + + if attr_key in ['total', 'size']: + if attr_key not in combined_attrs: + combined_attrs[attr_key] = 0 + combined_attrs[attr_key] += attr_value + continue + + if attr_key not in combined_attrs: + combined_attrs[attr_key] = [] + try: + attr_value = json.loads(attr_value) + except: + pass + if isinstance(attr_value, list): + combined_attrs[attr_key].extend(attr_value) + else: + combined_attrs[attr_key].append(attr_value) + + if 'mask' in in_f: + in_mask_group = in_f['mask'] + for mask_key in in_mask_group.keys(): + if mask_key not in combined_masks: + combined_masks[mask_key] = [] + combined_masks[mask_key].extend([old_key_to_new[episode_key.decode('utf-8')] for episode_key in in_mask_group[mask_key]]) + + + for mask_key, mask_values in combined_masks.items(): + mask_group.create_dataset(mask_key, data=np.array(mask_values).astype('S8')) + + # Add combined attributes to the output file + for attr_key, attr_values in combined_attrs.items(): + if attr_key == 'total': + data_group.attrs[attr_key] = attr_values + continue + if isinstance(attr_values, str): + data_group.attrs[attr_key] = attr_values + continue + try: + data_group.attrs[attr_key] = json.dumps(attr_values) + except TypeError: + # is_real is numpy bool_ for some reason + data_group.attrs[attr_key] = json.dumps([bool(i) for i in attr_values]) + + data_group.attrs['combined'] = True + data_group.attrs['dataset_id'] = str(uuid.uuid4()) + +if __name__ == '__main__': + combine_datasets_command() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/data_manager/convert_robosuite.py b/code_src/rise_code/sim_pipeline/data_manager/convert_robosuite.py new file mode 100644 index 0000000000000000000000000000000000000000..d8cfecbaa4a7b94e1aa301160c508c12933f200c --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_manager/convert_robosuite.py @@ -0,0 +1,75 @@ +""" +Helper script to convert a dataset collected using robosuite into an hdf5 compatible with +this repository. Takes a dataset path corresponding to the demo.hdf5 file containing the +demonstrations. It modifies the dataset in-place. By default, the script also creates a +90-10 train-validation split. + +For more information on collecting datasets with robosuite, see the code link and documentation +link below. + +Code: https://github.com/ARISE-Initiative/robosuite/blob/offline_study/robosuite/scripts/collect_human_demonstrations.py + +Documentation: https://robosuite.ai/docs/algorithms/demonstrations.html + +Example usage: + + python convert_robosuite.py --dataset /path/to/your/demo.hdf5 +""" + +import h5py +import json +import argparse + +import robomimic.envs.env_base as EB +from robomimic.scripts.split_train_val import split_train_val_from_hdf5 + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--dataset", + type=str, + help="path to input hdf5 dataset", + ) + args = parser.parse_args() + + f = h5py.File(args.dataset, "a") # edit mode + + # store env meta + env_name = f["data"].attrs["env_name"] + env_info = json.loads(f["data"].attrs["env_info"]) + env_meta = dict( + type=EB.EnvType.ROBOSUITE_TYPE, + env_name=env_name, + env_version=f["data"].attrs["repository_version"], + env_kwargs=env_info, + ) + if "env_args" in f["data"].attrs: + del f["data"].attrs["env_args"] + f["data"].attrs["env_args"] = json.dumps(env_meta, indent=4) + + print("====== Stored env meta ======") + print(f["data"].attrs["env_args"]) + + # store metadata about number of samples + total_samples = 0 + for ep in f["data"]: + # ensure model-xml is in per-episode metadata + assert "model_file" in f["data/{}".format(ep)].attrs + + # add "num_samples" into per-episode metadata + if "num_samples" in f["data/{}".format(ep)].attrs: + del f["data/{}".format(ep)].attrs["num_samples"] + n_sample = f["data/{}/actions".format(ep)].shape[0] + f["data/{}".format(ep)].attrs["num_samples"] = n_sample + total_samples += n_sample + + # add total samples to global metadata + if "total" in f["data"].attrs: + del f["data"].attrs["total"] + f["data"].attrs["total"] = total_samples + + f.close() + + # create 90-10 train-validation split in the dataset + split_train_val_from_hdf5(hdf5_path=args.dataset, val_ratio=0.1) diff --git a/code_src/rise_code/sim_pipeline/data_manager/data_manager.py b/code_src/rise_code/sim_pipeline/data_manager/data_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..673986efbbc0f5577052d58d9fd910800c9cf7e2 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_manager/data_manager.py @@ -0,0 +1,1012 @@ +import sqlite3 +import h5py +import uuid +import json +import tabulate + +from itertools import product +from importlib.resources import files +from typing import Any +from pathlib import Path +from sim_pipeline.configs.constants import COMBINED_DATA_DIR +from sim_pipeline.data_manager.dataset_metadata_enums import * +from sim_pipeline.data_manager.combine_datasets import combine_datasets +from sim_pipeline.reward_functions import RewardFunction +from collections import namedtuple + +class DataManager: + def __init__(self, db_path): + self.db_path = db_path + self.conn = sqlite3.connect(self.db_path) + self.cursor = self.conn.cursor() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.commit() + self.close() + + def create_tables(self): + """ + Create database tables based on schema. Removes all existing tables. + """ + self.empty_tables() + + with open(files('sim_pipeline.data_manager') / 'create_tables.sql', 'r') as sql_file: + sql_script = sql_file.read() + self.cursor.executescript(sql_script) + + self.populate_initial_types() + + self.conn.commit() + + def empty_tables(self): + """ + Remove all tables from database. + """ + self.cursor.execute("PRAGMA foreign_keys = OFF;") + + self.cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';") + tables = self.cursor.fetchall() + + for table_name in tables: + self.cursor.execute(f"DROP TABLE IF EXISTS {table_name[0]};") + + try: + self.cursor.execute("DELETE FROM sqlite_sequence;") + except sqlite3.OperationalError: + pass + + self.cursor.execute("PRAGMA foreign_keys = ON;") + + def populate_initial_types(self): + """ + Initialize the tables with the type definitions of each enum. + """ + self.cursor.executemany( + 'INSERT INTO DatasetProcessedStatuses (category) VALUES (?)', + [(status.value,) for status in ProcessedStatus] + ) + + self.cursor.executemany( + 'INSERT INTO DatasetTypes (type) VALUES (?)', + [(t.value,) for t in DatasetType] + ) + + self.cursor.executemany( + 'INSERT INTO EnvTypes (type) VALUES (?)', + [(t.value,) for t in EnvType] + ) + + self.cursor.executemany( + 'INSERT INTO ActionTypes (type) VALUES (?)', + [(t.value,) for t in ActionType] + ) + self.cursor.executemany( + 'INSERT INTO RewardTypes (type) VALUES (?)', + [(t.value,) for t in RewardType] + ) + self.cursor.executemany( + 'INSERT INTO RewardTypes (type) VALUES (?)', + [(t.value,) for t in RewardFunction] + ) + + def parse_directories(self, directories: list[Path]): + combined_datasets = [] + self._parse_directories_recursive(directories, combined_datasets) + + # add combined datasets at the end, because they might depend on datasets that are not in the database yet + for path in combined_datasets: + self.add_combined_dataset(path, path.stem) + self.commit() + + def _parse_directories_recursive(self, directories: list[Path], combined_datasets: list[Path]): + for dirname in directories: + if not dirname.is_dir(): + print(f'Warning: {dirname} is not a directory') + continue + + for path in dirname.iterdir(): + if path.is_file() and path.suffix == '.hdf5': + print(f'Parsing {path}') + try: + metadata, combined = self.get_dataset_metadata(path) + except KeyError as e: + print(f'Raised error {e}') + print(f'Warning: {path} does not contain correct metadata format. Skipping...') + continue + except PermissionError: + print(f'Warning: {path} is not readable. Skipping...') + continue + if metadata is None: + continue + try: + self.insert_dataset_metadata(path, path.stem, metadata) + except ValueError: + continue + if combined: + combined_datasets.append(path) + elif path.is_dir(): + self._parse_directories_recursive([path], combined_datasets) + + def get_dataset_metadata(self, dataset_path: Path) -> tuple[dict[str, Any], bool] | tuple[None, bool]: + with h5py.File(dataset_path, 'r+') as datafile: + data = datafile['data'] + attrs = data.attrs + + combined = 'combined' in attrs and attrs['combined'] + + return self._get_dataset_metadata(datafile, dataset_path), combined + + def _get_list(self, value: list | str | Any) -> list[Any]: + if isinstance(value, list): + return value + elif isinstance(value, str): + try: + value = json.loads(value) + return value + except json.JSONDecodeError: + return [value] + return [value] + + def _get_dataset_metadata(self, datafile: h5py.File, dataset_path: Path) -> dict[str, Any] | None: + data = datafile['data'] + attrs = data.attrs + + if 'is_test' in attrs and all(self._get_list(attrs['is_test'])): + return None + + if 'dataset_id' in attrs: + dataset_id: str = attrs['dataset_id'] + else: + # 'mask' always exists for robomimic data. we use this to differentiate b/w + # robomimic and any random h5py file + if 'mask' in datafile: + self._populate_robomimic_data(datafile, dataset_path) + dataset_id: str = attrs['dataset_id'] + else: + raise ValueError('Invalid metadata, env_type not specified & could not infer robomimic.') + + env_name = self._get_list(attrs['env_name']) + + env_type = [EnvType(t) for t in self._get_list(attrs['env_type'])] + + dataset_type = [DatasetType(t) for t in self._get_list(attrs['dataset_type'])] + + size = len(data.keys()) + + for ep_name in data.keys(): + episode = data[ep_name] + # Processed = has observations & reward, ready to go + # Pre-processed = raw robomimic or robosuite teleop data, after running + # conversion script but before dataset_states_to_obs + # Raw teleop = only relevant for robosuite teleop data, before conversion + if 'obs' in episode: + processed_status = ProcessedStatus.PROCESSED + + obs_keys = [key for key in episode['obs'].keys() if key not in ['object']] + + elif 'mask' not in datafile: + processed_status = ProcessedStatus.RAW_TELEOP + obs_keys = [] + else: + processed_status = ProcessedStatus.PRE_PROCESSED + obs_keys = [] + + break + + if processed_status == ProcessedStatus.PROCESSED: + reward_type = [] + for t in self._get_list(attrs['reward_type']): + try: + reward_type.append(RewardType(t)) + except ValueError: + reward_type.append(RewardFunction(t)) + + if 'derived_from' in attrs: + derived_from = json.loads(attrs['derived_from']) + if isinstance(derived_from[0], list): + # flatten + derived_from = [item for sublist in derived_from for item in sublist] + else: + derived_from = [] + else: + reward_type = [RewardType.NO_REWARD] + derived_from = [] + + action_type = [ActionType(t) for t in self._get_list(attrs['action_type'])] + + is_real = self._get_list(attrs['is_real']) + + if 'description' in attrs: + description = attrs['description'] + else: + description = '' + + datafile.close() + + return { + 'dataset_id': dataset_id, + 'env_name': env_name, + 'env_type': env_type, + 'dataset_type': dataset_type, + 'obs_keys': obs_keys, + 'processed_status': processed_status, + 'reward_type': reward_type, + 'action_type': action_type, + 'is_real': is_real, + 'size': size, + 'derived_from': derived_from, + 'description': description, + } + + def _populate_robomimic_data(self, datafile: h5py.File, dataset_path: Path): + """ + Robomimic downloaded datasets don't have proper metadata. Populate with default inferred metadata. + """ + + data = datafile['data'] + attrs = data.attrs + env_args = json.loads(attrs['env_args']) + + attrs['dataset_id'] = str(uuid.uuid4()) + + attrs['env_name'] = env_args['env_name'] + + attrs['env_type'] = EnvType.ROBOMIMIC.value + attrs['dataset_type'] = DatasetType(dataset_path.parent.stem).value + + attrs['size'] = len(data.keys()) + + for ep_name in data.keys(): + episode = data[ep_name] + if 'obs' in episode: + processed_status = ProcessedStatus.PROCESSED + else: + processed_status = ProcessedStatus.PRE_PROCESSED + break + + if processed_status == ProcessedStatus.PROCESSED: + shaped_rew = env_args['env_kwargs']['reward_shaping'] + if shaped_rew: + reward_type = RewardType.DENSE + else: + reward_type = RewardType.SPARSE + else: + reward_type = RewardType.NO_REWARD + + attrs['reward_type'] = reward_type.value + # assume action type is relative + attrs['action_type'] = ActionType.RELATIVE.value + attrs['is_real'] = False + attrs['description'] = 'downloaded robomimic dataset' + + attrs['creator'] = 'robomimic' + + def insert_dataset_metadata(self, dataset_path: Path, name: str, metadata: dict[str, Any]): + dataset_id = metadata['dataset_id'] + + if self.fetch_id('Datasets', 'id', dataset_id, none_ok=True) is not None: + # duplicates should not happen under proper use but just in case (i.e. copying a hdf5 file) + print(f"Warning: Dataset with id {dataset_id} already exists in the database") + raise ValueError(f'Duplicate ids') + + self.insert_data('Datasets', { + 'id': dataset_id, + 'name': name, + 'path': str(dataset_path), + 'env_name': metadata['env_name'][0], + 'is_real': metadata['is_real'][0], + 'size': metadata['size'], + 'description': metadata['description'], + }) + + category_id = self.fetch_id('DatasetProcessedStatuses', 'category', metadata['processed_status'].value) + + self.insert_data('DatasetProcessedStatusesAssociations', { + 'dataset_id': dataset_id, + 'category_id': category_id, + }) + + env_type_ids = set( + self.fetch_id('EnvTypes', 'type', t.value) for t in metadata['env_type'] + ) + for env_type_id in env_type_ids: + self.insert_data('DatasetEnvType', { + 'dataset_id': dataset_id, + 'env_type_id': env_type_id + }) + + dataset_type_ids = set( + self.fetch_id('DatasetTypes', 'type', t.value) for t in metadata['dataset_type'] + ) + for dataset_type_id in dataset_type_ids: + self.insert_data('DatasetTypeAssociations', { + 'dataset_id': dataset_id, + 'dataset_type_id': dataset_type_id + }) + + action_type_ids = set( + self.fetch_id('ActionTypes', 'type', t.value) for t in metadata['action_type'] + ) + for action_type_id in action_type_ids: + self.insert_data('DatasetActionType', { + 'dataset_id': dataset_id, + 'action_type_id': action_type_id + }) + + if metadata['processed_status'] == ProcessedStatus.PROCESSED: + reward_type_ids = set( + self.fetch_id('RewardTypes', 'type', t.value) for t in metadata['reward_type'] + ) + for reward_type_id in reward_type_ids: + self.insert_data('DatasetRewardType', { + 'dataset_id': dataset_id, + 'reward_type_id': reward_type_id + }) + + for key in metadata['obs_keys']: + self.cursor.execute(''' + INSERT OR IGNORE INTO ObservationKeys (key) + VALUES (?) + ''', (key,)) + + key_id = self.fetch_id('ObservationKeys', 'key', key) + + self.insert_data('DatasetObservationKeys', { + 'dataset_id': dataset_id, + 'observation_key_id': key_id + }) + + for id in metadata['derived_from']: + self.cursor.execute(''' + INSERT INTO DerivedDatasets (dataset_id, derived_from_id) + VALUES (?, ?) + ''', (dataset_id, id)) + + def add_combined_dataset(self, dataset_path: str | Path, name: str): + """ + Add a combined dataset to the database. If any of the constituent datasets are missing, + a dummy dataset is created. + + Args: + dataset_path (str | Path): path to the combined dataset + name (str): name of the combined dataset + """ + print(f'Adding combined dataset {name}') + with h5py.File(dataset_path, 'r') as datafile: + data = datafile['data'] + attrs = data.attrs + if 'combined' not in attrs or not attrs['combined']: + return + + + constituent_dataset_ids = json.loads(attrs['constituent_dataset_id']) + for i, dataset_id in enumerate(constituent_dataset_ids): + # if the constituent dataset no longer exist, create a dummy dataset with the same metadata + if self.fetch_id('Datasets', 'id', dataset_id, none_ok=True) is None: + print(f"Warning: Dataset with id {dataset_id} not found in the database. Adding dummy") + self._add_dummy_dataset(data, dataset_id, i) + + self._insert_combined_dataset(attrs['dataset_id'], name, str(dataset_path), constituent_dataset_ids) + + def _add_dummy_dataset(self, data: h5py.Group, dataset_id: str, i: int): + """ + Called when a combined dataset is missing a constituent. Creates a dummy + dataset with the same metadata as the missing constituent. + + data - data group object for the combined dataset + dataset_id - id of the missing dataset + i - index of the constituent dataset in the combined dataset + """ + attrs = data.attrs + constituent_attrs = self._get_ith_constituent_attrs(attrs, i) + env_name = constituent_attrs['env_name'] + + self.insert_data('Datasets', { + 'id': dataset_id, + 'name': 'dummy', + 'path': 'dummy_path', + 'env_name': env_name, + 'is_real': constituent_attrs['is_real'], + 'size': 0, + 'description': '' + }) + # only processed datasets can be combined, so the constituent must be processed + category_id = self.fetch_id('DatasetProcessedStatuses', 'category', ProcessedStatus.PROCESSED.value) + env_type_id = self.fetch_id('EnvTypes', 'type', constituent_attrs['env_type']) + self.insert_data('DatasetProcessedStatusesAssociations', { + 'dataset_id': dataset_id, + 'category_id': category_id, + }) + self.insert_data('DatasetEnvType', { + 'dataset_id': dataset_id, + 'env_type_id': env_type_id + }) + dataset_type_id = self.fetch_id('DatasetTypes', 'type', constituent_attrs['dataset_type']) + self.insert_data('DatasetTypeAssociations', { + 'dataset_id': dataset_id, + 'dataset_type_id': dataset_type_id + }) + action_type_id = self.fetch_id('ActionTypes', 'type', constituent_attrs['action_type']) + self.insert_data('DatasetActionType', { + 'dataset_id': dataset_id, + 'action_type_id': action_type_id + }) + reward_type_id = self.fetch_id('RewardTypes', 'type', constituent_attrs['reward_type']) + self.insert_data('DatasetRewardType', { + 'dataset_id': dataset_id, + 'reward_type_id': reward_type_id + }) + + for ep_key in data.keys(): + episode = data[ep_key] + obs_keys = [key for key in episode['obs'].keys() if key not in ['object']] + break + for key in obs_keys: + self.cursor.execute(''' + INSERT OR IGNORE INTO ObservationKeys (key) + VALUES (?) + ''', (key,)) + key_id = self.fetch_id('ObservationKeys', 'key', key) + self.insert_data('DatasetObservationKeys', { + 'dataset_id': dataset_id, + 'observation_key_id': key_id + }) + + def _insert_combined_dataset(self, combined_id: str, name: str, dataset_path: str, constituent_ids: list[str]): + # TODO: currently we are assuming combined datasets cannot be derived from other combined datasets + # otherwise, we would have to insert into the DerivedDatasets table + + self.insert_data( + 'CombinedDatasets', + { + 'id': combined_id, + 'name': name, + 'path': dataset_path + } + ) + + for dataset_id in constituent_ids: + self.insert_data( + 'CombinedDatasetComponents', + { + 'combined_dataset_id': combined_id, + 'dataset_id': dataset_id + } + ) + + def _get_ith_constituent_attrs(self, attrs: dict[str, Any], i: int) -> dict[str, Any]: + """ + Extract metadata for the i-th constituent dataset from the attrs of a combined dataset. + """ + constituent_metadata = {} + + for attr in ['env_name', 'env_args', 'env_type', 'dataset_type', 'action_type', 'reward_type', 'is_real']: + try: + constituent_metadata[attr] = json.loads(attrs[attr])[0] + except: + constituent_metadata[attr] = json.loads(attrs[attr]) + + return constituent_metadata + + def insert_data(self, table_name, data): + columns = ', '.join(data.keys()) + values = ', '.join([f"'{v}'" for v in data.values()]) + self.cursor.execute(f"INSERT INTO {table_name} ({columns}) VALUES ({values})") + + def fetch_id(self, table_name, matching, name, none_ok=False): + try: + return self.cursor.execute(f'SELECT id FROM {table_name} WHERE {matching} = ?', (name,)).fetchone()[0] + except TypeError: + if none_ok: + return None + raise ValueError(f'{matching} = {name} not found in {table_name} table. Likely {name} was not inserted into enum table.') + + def query_datasets(self, return_all=False, combined_only: bool | None=None,**kwargs) -> list[tuple[str]]: + """ + Perform a query on the database and return matches. + + return_all - if True, return ['id', 'name', 'path', 'is_real', 'env_name', 'action_types', 'obs_keys', 'derived_from', 'constituent_ids'] + else return ['id', 'name', 'path'] + combined_only - if True, only return combined datasets. If False, only return non-combined datasets. If None, return all. + kwargs - query parameters. For example, to query by dataset id, pass id=''. Pass a list to query by multiple values, + where any dataset whose values of that field are a subset of the query, it will match. + """ + if return_all: + query_t = namedtuple('query_t', ['id', 'name', 'path', 'is_real', 'env_name', 'action_types', 'obs_keys', 'derived_from', 'constituent_ids']) + query = """ + SELECT DISTINCT d.id, d.name, d.path, d.is_real, d.env_name, + GROUP_CONCAT(DISTINCT at.type) as action_types, + GROUP_CONCAT(DISTINCT ok.key) as obs_keys, + GROUP_CONCAT(DISTINCT df.derived_from_id) as derived_from, + GROUP_CONCAT(DISTINCT cdc.dataset_id) as constituent_ids + FROM Datasets d + LEFT JOIN DatasetActionType dat ON d.id = dat.dataset_id + LEFT JOIN ActionTypes at ON dat.action_type_id = at.id + LEFT JOIN DatasetObservationKeys dok ON d.id = dok.dataset_id + LEFT JOIN ObservationKeys ok ON dok.observation_key_id = ok.id + LEFT JOIN DerivedDatasets df ON d.id = df.dataset_id + LEFT JOIN CombinedDatasetComponents cdc ON d.id = cdc.combined_dataset_id + """ + else: + query_t = namedtuple('query_t', ['id', 'name', 'path']) + query = """ + SELECT DISTINCT d.id, d.name, d.path + FROM Datasets d + """ + + if combined_only is not None: + query += """ + LEFT JOIN CombinedDatasetComponents cdc2 ON d.id = cdc2.combined_dataset_id + """ + query += "WHERE 1=1" + + params = [] + + def add_simple_condition(field, table, column): + nonlocal query, params + if field in kwargs: + values = kwargs[field] if isinstance(kwargs[field], list) else [kwargs[field]] + placeholders = ','.join(['?' for _ in values]) + query += f" AND d.id IN (SELECT id FROM {table} WHERE {column} IN ({placeholders}))" + params.extend(values) + + def add_subset_condition(field, table, type_column, id_column): + """ + the values are a subset of the query + """ + nonlocal query, params + if field in kwargs: + values = kwargs[field] if isinstance(kwargs[field], list) else [kwargs[field]] + placeholders = ','.join(['?' for _ in values]) + query += f""" + AND NOT EXISTS ( + SELECT 1 + FROM {table} + WHERE dataset_id = d.id + AND {type_column} NOT IN ({placeholders}) + ) + AND EXISTS ( + SELECT 1 + FROM {table} + WHERE dataset_id = d.id + ) + """ + params.extend(values) + + def add_exact_match_condition(field, table, column): + """ + the query is a subset of the values + """ + nonlocal query, params + if field in kwargs: + values = kwargs[field] if isinstance(kwargs[field], list) else [kwargs[field]] + placeholders = ','.join(['?' for _ in values]) + query += f""" + AND ( + SELECT COUNT(DISTINCT {column}) + FROM {table} + WHERE dataset_id = d.id + AND {column} IN ({placeholders}) + ) = {len(values)} + """ + params.extend(values) + + add_simple_condition('id', 'Datasets', 'id') + add_simple_condition('name', 'Datasets', 'name') + add_subset_condition('env_type', 'DatasetEnvType dm JOIN EnvTypes et ON dm.env_type_id = et.id', 'et.type', 'et.id') + add_subset_condition('action_type', 'DatasetActionType dat JOIN ActionTypes at ON dat.action_type_id = at.id', 'at.type', 'at.id') + add_subset_condition('reward_type', 'DatasetRewardType drt JOIN RewardTypes rt ON drt.reward_type_id = rt.id', 'rt.type', 'rt.id') + add_subset_condition('dataset_type', 'DatasetTypeAssociations dta JOIN DatasetTypes dt ON dta.dataset_type_id = dt.id', 'dt.type', 'dt.id') + + # add_subset_condition('obs_keys', 'DatasetObservationKeys dok JOIN ObservationKeys ok ON dok.observation_key_id = ok.id', 'ok.key', 'ok.id') + add_exact_match_condition('obs_keys', 'DatasetObservationKeys dok JOIN ObservationKeys ok ON dok.observation_key_id = ok.id', 'ok.key') + add_subset_condition('processed_status', 'DatasetProcessedStatusesAssociations dpsa JOIN DatasetProcessedStatuses dps ON dpsa.category_id = dps.id', 'dps.category', 'dps.id') + + # exclude any in exclude_obs_keys + if 'exclude_obs_keys' in kwargs: + exclude_obs_keys = kwargs['exclude_obs_keys'] if isinstance(kwargs['exclude_obs_keys'], list) else [kwargs['exclude_obs_keys']] + placeholders = ','.join(['?' for _ in exclude_obs_keys]) + query += f""" + AND NOT EXISTS ( + SELECT 1 + FROM DatasetObservationKeys dok + JOIN ObservationKeys ok ON dok.observation_key_id = ok.id + WHERE dok.dataset_id = d.id + AND ok.key IN ({placeholders}) + ) + """ + params.extend(exclude_obs_keys) + + if 'is_real' in kwargs: + is_real_values = kwargs['is_real'] if isinstance(kwargs['is_real'], list) else [kwargs['is_real']] + placeholders = ','.join(['?' for _ in is_real_values]) + query += f" AND d.is_real IN ({placeholders})" + params.extend([int(val) for val in is_real_values]) + + + if combined_only is not None: + query += f" AND {'EXISTS' if combined_only else 'NOT EXISTS'} (SELECT 1 FROM CombinedDatasetComponents WHERE combined_dataset_id = d.id)" + + query += " GROUP BY d.id, d.name, d.path" + + self.cursor.execute(query, params) + results = self.cursor.fetchall() + + # name tuple + results = [query_t(*result) for result in results] + return results + + def _group_matched_datasets(self, matched: list[tuple[str, list[str]]]) -> list[set[str]]: + """ + Groups together datasets that represent the same underlying data (but might be in different + forms, like different observation keys or action types) + + matched - list of tuples (dataset_id, derived_from) representing datasets that match the query + + returns a list of sets of dataset ids, where dataset ids in each set represent the same + underlying data + """ + groups: dict[str, set[str]] = {} + for dataset_id, derived_from in matched: + derived_from = set(derived_from) + # Check if this dataset or any of its predecessors are already in a group + existing_group = None + for id in {dataset_id} | derived_from: + if id in groups: + existing_group = groups[id] + break + + if existing_group is None: + # if no existing group is found, create a new one + new_group = {dataset_id} | derived_from + for id in new_group: + groups[id] = new_group + else: + # if an existing group is found, merge this dataset and its predecessors into it + existing_group.add(dataset_id) + existing_group.update(derived_from) + for id in existing_group: + groups[id] = existing_group + + # Return unique groups + return list(set(frozenset(group) for group in groups.values())) + + def _propose_dataset_combinations( + self, + matched: list[tuple[str, list[str]]], + combined_datasets: list[tuple[str, list[str]]], + is_dummy: dict[str, bool] + ) -> list[list[str]]: + """ + Returns a list of possible combinations of datasets that can be combined into a new dataset. + Avoids proposing combinations that would result in overlapping data. Also avoids dummy datasets. + + matched - list of tuples (dataset_id, derived_from) that match query, non-combined only + combined_datasets - list of (dataset_id, constituent_ids) that match query, combined only + is_dummy - dict mapping dataset_id to whether it is a dummy dataset for each dataset in matched + """ + groups = self._group_matched_datasets(matched) + + # For each group, select the dataset(s) that were in the original list + # This effectively filters out the 'derived_from' ids that might not be in the original list + matched_ids = [i[0] for i in matched] + valid_datasets_per_group = [ + set(id for id in group if id in matched_ids) + for group in groups + ] + + # remove dummy datasets + remaining_groups = [] + dummy_only_groups = [] + for group in valid_datasets_per_group: + group_no_dummy = set() + for id in group: + if not is_dummy[id]: + group_no_dummy.add(id) + if len(group_no_dummy) > 0: + remaining_groups.append(group_no_dummy) + else: + dummy_only_groups.append(group) + + def generate_combinations( + current_groups: list[tuple[str, list[str]]], + current_combined: list[tuple[str, list[str]]], + excluded_ids: set[str] + ) -> list[list[str]]: + """ + Recursively generate all possible dataset combinations. + + current_groups - groups of datasets ids (not combined) that can be combined + current_combined - combined datasets that can be combined (due to having constituents in dummy-only groups) + excluded_ids - dataset ids that have already been combined and thus should be excluded + """ + if not current_groups and not current_combined: + return [[]] + + result = [] + + for cd in current_combined: + constituent_ids = set(cd[1]) + if not constituent_ids & excluded_ids: + # exclude constituents + new_excluded = excluded_ids | constituent_ids + new_groups = [g for g in current_groups if not g & constituent_ids] + # remove potential combined datasets that share constituents with this one + new_combined = [c for c in current_combined if c[0] != cd[0] and not set(c[1]) & constituent_ids] + result.extend([[cd[0]] + combo + for combo in generate_combinations(new_groups, new_combined, new_excluded)]) + + # try adding from non-dummy groups + if current_groups and not current_combined: + group = current_groups[0] + for dataset_id in group: + if dataset_id not in excluded_ids: + result.extend([[dataset_id] + combo + for combo in generate_combinations(current_groups[1:], current_combined, excluded_ids)]) + + return result + + # Find combined datasets that could replace dummy-only groups + relevant_combined = [cd for cd in combined_datasets + if any(set(cd[1]) & group for group in dummy_only_groups)] + # include combined datasets that do not share any constituents with matched + relevant_combined.extend([cd for cd in combined_datasets if not set(cd[1]) & set(matched_ids)]) + + # Generate all possible combinations + return generate_combinations(remaining_groups, relevant_combined, set()) + + def _get_valid_combinations(self, combinations: list[list[str]]) -> list[list[str]]: + """ + Given a list of proposed dataset commbinations, return only the ones that can + be combined. I.e., no conflicting action types, same environment, etc. + + *does not check for overlapping data. this assumes the combos are returned + from _propose_dataset_combinations, which already should avoid overlapping data + + combinations - list of proposed dataset combinations. Each combination is a list + of datatset_ids + """ + + valid_combinations = [] + for combo in combinations: + datasets_in_combo = self.query_datasets(return_all=True, id=combo) + + action_types = [q.action_types for q in datasets_in_combo] + obs_keys = [q.obs_keys for q in datasets_in_combo] + env_names = [q.env_name for q in datasets_in_combo] + is_reals = [q.is_real for q in datasets_in_combo] + + to_match: list[list[str]] = [action_types, obs_keys, env_names, is_reals] + + for match_condition in to_match: + # make sure everythin in match_condition is the same + for item in match_condition: + items = set(item.split(',')) + match_condition_item = items + break + for item in match_condition: + items = set(item.split(',')) + if items ^ match_condition_item: + # not all items are the same + break + else: + # no break - match_condition passes + continue + + # break - match_condition failed + break + else: + # no break - all match_conditions passed + valid_combinations.append(combo) + + return valid_combinations + + def _check_combined_exists(self, dataset_ids: list[str], combined: list[tuple[str, list[str]]]) -> str | None: + """ + Check if a combined dataset with the provided constituents already exists. + If exists, returns the id of the matching combined dataset. Otherwise, returns None. + + dataset_ids - list of dataset ids that would be combined + combined - possible combined dataset ids that could contain the constituents + """ + for combined_id, constituents in combined: + if set(constituents) == set(dataset_ids): + return combined_id + return None + + def get_dataset(self, attempt_combination=True, **kwargs) -> str | None: + """ + Return the path of the dataset that matches the query parameters. If multiple datasets + match, try to combine them into a new dataset. If no matching datasets are found, + attempt to convert existing datasets into a matching new dataset. + + If impossible, returns None. + """ + all_single_matched = self.query_datasets(combined_only=False, return_all=True, processed_status=ProcessedStatus.PROCESSED.value, **kwargs) + all_combined_matched = self.query_datasets(combined_only=True, return_all=True, processed_status=ProcessedStatus.PROCESSED.value, **kwargs) + is_dummy = {} + single_matches = [] + single_id_to_path: dict[str, str] = {} + single_id_to_name: dict[str, str] = {} + for match in all_single_matched: + if match.derived_from is None: + derived_from = [] + else: + derived_from = match.derived_from.split(',') + single_matches.append((match.id, derived_from)) + # TODO: perhaps find a better marker for a dummy than setting name to 'dummy'? + is_dummy[match.id] = match.name == 'dummy' + single_id_to_path[match.id] = match.path + single_id_to_name[match.id] = match.name + combined_matches = [] + combined_id_to_path = {} + combined_id_to_name = {} + for match in all_combined_matched: + constituent_ids = match.constituent_ids.split(',') + combined_matches.append((match.id, constituent_ids)) + combined_id_to_path[match.id] = match.path + combined_id_to_name[match.id] = match.name + id_to_path = single_id_to_path | combined_id_to_path + id_to_name = single_id_to_name | combined_id_to_name + + proposed_combos = self._propose_dataset_combinations(single_matches, combined_matches, is_dummy) + valid_combos = self._get_valid_combinations(proposed_combos) + + if not valid_combos or all(not item for item in valid_combos): + return None + # TODO: attempt to convert + + if len(valid_combos) == 1 and len(valid_combos[0]) == 1: + return id_to_path[valid_combos[0][0]] + + if not attempt_combination: + return None + + # go thru valid combos, if any already exist, return the first one + for combo in valid_combos: + combined_id = self._check_combined_exists(combo, combined_matches) + if combined_id: + return combined_id_to_path[combined_id] + + # otherwise, try to combine the first one + # TODO: smarter combo selection, perhaps one that minimizes fractionalization of data attributes + combo = valid_combos[0] + dataset_paths = [id_to_path[dataset_id] for dataset_id in combo] + new_name = '_'.join([id_to_name[dataset_id] for dataset_id in combo]) + '_COMBINED' + combined_dir = Path(COMBINED_DATA_DIR) + new_combined_path = combined_dir / f"{new_name}.hdf5" + print(f'Combining datasets & saving to path: {new_combined_path}') + if not COMBINED_DATA_DIR.exists(): + COMBINED_DATA_DIR.mkdir() + combine_datasets(dataset_paths, str(new_combined_path)) + + # Insert the new combined dataset into the database + metadata, _ = self.get_dataset_metadata(new_combined_path) + self.insert_dataset_metadata(new_combined_path, new_name, metadata) + self.add_combined_dataset(new_combined_path, new_name) + + self.commit() + + return new_combined_path + + def visualize_table(self, table_name, limit=None): + self.cursor.execute(f"PRAGMA table_info({table_name});") + columns = [column[1] for column in self.cursor.fetchall()] + + # Get table data + if limit: + self.cursor.execute(f"SELECT * FROM {table_name} LIMIT {limit};") + else: + self.cursor.execute(f"SELECT * FROM {table_name};") + rows = self.cursor.fetchall() + + print(f"\nContents of table '{table_name}':") + print(tabulate.tabulate(rows, headers=columns, tablefmt="grid")) + print(f"Total rows: {len(rows)}") + + def visualize_query_result(self, query, params=None, maxcolwidths=25, to_csv=False): + # Execute the provided query + if params: + self.cursor.execute(query, params) + else: + self.cursor.execute(query) + rows = self.cursor.fetchall() + + # Get column headers from the cursor description + columns = [column[0] for column in self.cursor.description] + + if to_csv: + with open('all_datasets.csv', 'w') as f: + content = tabulate.tabulate(rows, headers=columns, tablefmt='csv') + with open('all_datasets.csv', 'w') as f: + f.write(content) + print(f"\nQuery result saved to all_datasets.csv") + else: + print(f"\nQuery result:") + print(tabulate.tabulate(rows, headers=columns, tablefmt="grid", maxcolwidths=maxcolwidths)) + print(f"Total rows: {len(rows)}") + + + def visualize_all(self, to_csv=False, show_id=False): + id_str = 'd.id, ' if show_id else '' + + query = f""" + SELECT DISTINCT {id_str}d.name, d.path, d.size, d.is_real, d.env_name, dt.type, dps.category, d.description, + GROUP_CONCAT(DISTINCT at.type) as action_types, + GROUP_CONCAT(DISTINCT ok.key) as obs_keys, + GROUP_CONCAT(DISTINCT rt.type) as reward_types + FROM Datasets d + LEFT JOIN DatasetActionType dat ON d.id = dat.dataset_id + LEFT JOIN ActionTypes at ON dat.action_type_id = at.id + LEFT JOIN DatasetObservationKeys dok ON d.id = dok.dataset_id + LEFT JOIN ObservationKeys ok ON dok.observation_key_id = ok.id + LEFT JOIN DatasetProcessedStatusesAssociations dpsa ON dpsa.dataset_id = d.id + LEFT JOIN DatasetProcessedStatuses dps ON dpsa.category_id = dps.id + LEFT JOIN DatasetRewardType drt ON d.id = drt.dataset_id + LEFT JOIN RewardTypes rt ON drt.reward_type_id = rt.id + LEFT JOIN DatasetTypeAssociations dta ON dta.dataset_id = d.id + LEFT JOIN DatasetTypes dt ON dta.dataset_type_id = dt.id + GROUP BY d.id, d.name, d.path + """ + maxcolwidths = [15, 35, 8, 10, 20, 8, 30, 15, 10, 20] + maxcolwidths = [50] + maxcolwidths if show_id else maxcolwidths + self.visualize_query_result(query, maxcolwidths=maxcolwidths, to_csv=to_csv) + + def check_updated(self) -> bool: + """ + Check if all datasets in the database are still present in their original paths. + + If not, should re-parse the directories to update the database. + + Note, does not check if newly added datasets exist. + """ + all_datasets = self.query_datasets() + for dataset in all_datasets: + if dataset.name == 'dummy': + continue + path = Path(dataset.path) + if not path.exists(): + return False + return True + + def commit(self): + self.conn.commit() + + def close(self): + self.conn.close() + +### +# fix bug in tabulate by monkey patching +### +def _wrap_text_to_colwidths(list_of_lists, colwidths, numparses=True): + numparses = tabulate._expand_iterable(numparses, len(list_of_lists[0]), True) + + result = [] + + for row in list_of_lists: + new_row = [] + for cell, width, numparse in zip(row, colwidths, numparses): + if tabulate._isnumber(cell) and numparse: + new_row.append(cell) + continue + + if width is not None: + wrapper = tabulate._CustomTextWrap(width=width) + # Cast based on our internal type handling + # Any future custom formatting of types (such as datetimes) + # may need to be more explicit than just `str` of the object + # casted_cell = ( + # str(cell) if _isnumber(cell) else _type(cell, numparse)(cell) + # ) + if cell is not None: + wrapped = wrapper.wrap(cell) + new_row.append("\n".join(wrapped)) + else: + new_row.append(cell) + result.append(new_row) + + return result +tabulate._wrap_text_to_colwidths = _wrap_text_to_colwidths diff --git a/code_src/rise_code/sim_pipeline/data_manager/dataset_metadata_enums.py b/code_src/rise_code/sim_pipeline/data_manager/dataset_metadata_enums.py new file mode 100644 index 0000000000000000000000000000000000000000..769a1c9e758c5b8e31978a57ad21cb75547168b9 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_manager/dataset_metadata_enums.py @@ -0,0 +1,59 @@ +from enum import Enum + +class ProcessedStatus(Enum): + RAW_TELEOP = 'raw_teleop' + PRE_PROCESSED = 'pre_processed' + PROCESSED = 'processed' + +class EnvType(Enum): + ROBOMIMIC = 'robomimic' + ROBOSUITE = 'robosuite' + REAL_FRANKA = 'real_franka' + REAL_TYCHO = 'real_tycho' + +class DatasetType(Enum): + PH = 'ph' + MH = 'mh' + RL = 'rl' + PLAY = 'play' + +class ObsType(Enum): + IMAGE = 'image' + STATE = 'low_dim' + IMAGE_ONLY = 'image_only' + + def included_keys(self): + if self == ObsType.IMAGE: + return ['agentview_image', 'robot0_eye_in_hand_image'] + elif self == ObsType.STATE: + return None + elif self == ObsType.IMAGE_ONLY: + return ['agentview_image', 'robot0_eye_in_hand_image'] + else: + return None + + def excluded_keys(self): + if self == ObsType.IMAGE: + return None + elif self == ObsType.STATE: + return ['agentview_image', 'robot0_eye_in_hand_image'] + elif self == ObsType.IMAGE_ONLY: + return None + else: + return None + + def includes_image_obs(self): + return self in [ObsType.IMAGE, ObsType.IMAGE_ONLY] + + def includes_depth_obs(self): + return False + +class ActionType(Enum): + RELATIVE = 'relative' + ABSOLUTE = 'absolute' + +class RewardType(Enum): + SPARSE = 'sparse' + DENSE = 'dense' + NO_REWARD = 'no_reward' + DENSITY_REWARD = 'density_reward' \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/data_manager/dataset_states_to_obs.py b/code_src/rise_code/sim_pipeline/data_manager/dataset_states_to_obs.py new file mode 100644 index 0000000000000000000000000000000000000000..7db0e3ee3d1f7584059931f458b9c386aa4e2b29 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_manager/dataset_states_to_obs.py @@ -0,0 +1,519 @@ +""" +Script to extract observations from low-dimensional simulation states in a robosuite dataset. + +Args: + dataset (str): path to input hdf5 dataset + + output_name (str): name of output hdf5 dataset + + n (int): if provided, stop after n trajectories are processed + + shaped (bool): if flag is set, use dense rewards + + camera_names (str or [str]): camera name(s) to use for image observations. + Leave out to not use image observations. + + camera_height (int): height of image observation. + + camera_width (int): width of image observation + + done_mode (int): how to write done signal. If 0, done is 1 whenever s' is a success state. + If 1, done is 1 at the end of each trajectory. If 2, both. + + copy_rewards (bool): if provided, copy rewards from source file instead of inferring them + + copy_dones (bool): if provided, copy dones from source file instead of inferring them + +Example usage: + + # extract low-dimensional observations + python dataset_states_to_obs.py --dataset /path/to/demo.hdf5 --output_name low_dim.hdf5 --done_mode 2 + + # extract 84x84 image observations + python dataset_states_to_obs.py --dataset /path/to/demo.hdf5 --output_name image.hdf5 \ + --done_mode 2 --camera_names agentview robot0_eye_in_hand --camera_height 84 --camera_width 84 + + # extract 84x84 image and depth observations + python dataset_states_to_obs.py --dataset /path/to/demo.hdf5 --output_name depth.hdf5 \ + --done_mode 2 --camera_names agentview robot0_eye_in_hand --camera_height 84 --camera_width 84 --depth + + # (space saving option) extract 84x84 image observations with compression and without + # extracting next obs (not needed for pure imitation learning algos) + python dataset_states_to_obs.py --dataset /path/to/demo.hdf5 --output_name image.hdf5 \ + --done_mode 2 --camera_names agentview robot0_eye_in_hand --camera_height 84 --camera_width 84 \ + --compress --exclude-next-obs + + # use dense rewards, and only annotate the end of trajectories with done signal + python dataset_states_to_obs.py --dataset /path/to/demo.hdf5 --output_name image_dense_done_1.hdf5 \ + --done_mode 1 --dense --camera_names agentview robot0_eye_in_hand --camera_height 84 --camera_width 84 +""" +import os +import json +import h5py +import uuid +import click +import numpy as np +from copy import deepcopy +from tqdm import tqdm + +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.file_utils as FileUtils +import robomimic.utils.env_utils as EnvUtils +from robomimic.envs.env_base import EnvBase + +from hydra import compose, initialize +from hydra.core.config_store import ConfigStore +from sim_pipeline.envs.make_env import make_robomimic_env + + +def extract_trajectory( + env, + initial_state, + states, + actions, + done_mode, + camera_names=None, + camera_height=84, + camera_width=84, + const_reward: float | None = None, +): + """ + Helper function to extract observations, rewards, and dones along a trajectory using + the simulator environment. + + Args: + env (instance of EnvBase): environment + initial_state (dict): initial simulation state to load + states (np.array): array of simulation states to load to extract information + actions (np.array): array of actions + done_mode (int): how to write done signal. If 0, done is 1 whenever s' is a + success state. If 1, done is 1 at the end of each trajectory. + If 2, do both. + """ + # assert isinstance(env, EnvBase) + assert states.shape[0] == actions.shape[0] + + # load the initial state + env.reset() + obs = env.reset_to(initial_state) + + # maybe add in intrinsics and extrinsics for all cameras + camera_info = None + is_robosuite_env = EnvUtils.is_robosuite_env(env=env) + if is_robosuite_env: + camera_info = get_camera_info( + env=env, + camera_names=camera_names, + camera_height=camera_height, + camera_width=camera_width, + ) + + traj = dict( + obs=[], + next_obs=[], + rewards=[], + dones=[], + actions=np.array(actions), + states=np.array(states), + initial_state_dict=initial_state, + ) + traj_len = states.shape[0] + # iteration variable @t is over "next obs" indices + for t in range(1, traj_len + 1): + # get next observation + if t == traj_len: + # play final action to get next observation for last timestep + next_obs, _, _, _ = env.step(actions[t - 1]) + else: + # reset to simulator state to get observation + next_obs = env.reset_to({"states" : states[t]}) + + # infer reward signal + # note: our tasks use reward r(s'), reward AFTER transition, so this is + # the reward for the current timestep + r = env.get_reward() + if const_reward is not None: + r = const_reward + + # infer done signal + done = False + if (done_mode == 1) or (done_mode == 2): + # done = 1 at end of trajectory + done = done or (t == traj_len) + if (done_mode == 0) or (done_mode == 2): + # done = 1 when s' is task success state + done = done or env.is_success()["task"] + done = int(done) + + # collect transition + traj["obs"].append(obs) + traj["next_obs"].append(next_obs) + traj["rewards"].append(r) + traj["dones"].append(done) + + # update for next iter + obs = deepcopy(next_obs) + + # convert list of dict to dict of list for obs dictionaries (for convenient writes to hdf5 dataset) + traj["obs"] = TensorUtils.list_of_flat_dict_to_dict_of_list(traj["obs"]) + traj["next_obs"] = TensorUtils.list_of_flat_dict_to_dict_of_list(traj["next_obs"]) + + # list to numpy array + for k in traj: + if k == "initial_state_dict": + continue + if isinstance(traj[k], dict): + for kp in traj[k]: + traj[k][kp] = np.array(traj[k][kp]) + else: + traj[k] = np.array(traj[k]) + + return traj, camera_info + + +def get_camera_info( + env, + camera_names=None, + camera_height=84, + camera_width=84, +): + """ + Helper function to get camera intrinsics and extrinsics for cameras being used for observations. + """ + + # TODO: make this function more general than just robosuite environments + assert EnvUtils.is_robosuite_env(env=env) + + if camera_names is None: + return None + + camera_info = dict() + for cam_name in camera_names: + K = env.get_camera_intrinsic_matrix(camera_name=cam_name, camera_height=camera_height, camera_width=camera_width) + R = env.get_camera_extrinsic_matrix(camera_name=cam_name) # camera pose in world frame + if "eye_in_hand" in cam_name: + # convert extrinsic matrix to be relative to robot eef control frame + assert cam_name.startswith("robot0") + eef_site_name = env.base_env.robots[0].controller.eef_name + eef_pos = np.array(env.base_env.sim.data.site_xpos[env.base_env.sim.model.site_name2id(eef_site_name)]) + eef_rot = np.array(env.base_env.sim.data.site_xmat[env.base_env.sim.model.site_name2id(eef_site_name)].reshape([3, 3])) + eef_pose = np.zeros((4, 4)) # eef pose in world frame + eef_pose[:3, :3] = eef_rot + eef_pose[:3, 3] = eef_pos + eef_pose[3, 3] = 1.0 + eef_pose_inv = np.zeros((4, 4)) + eef_pose_inv[:3, :3] = eef_pose[:3, :3].T + eef_pose_inv[:3, 3] = -eef_pose_inv[:3, :3].dot(eef_pose[:3, 3]) + eef_pose_inv[3, 3] = 1.0 + R = R.dot(eef_pose_inv) # T_E^W * T_W^C = T_E^C + camera_info[cam_name] = dict( + intrinsics=K.tolist(), + extrinsics=R.tolist(), + ) + return camera_info + + +def dataset_states_to_obs( + dataset, + output_name, + n, + shaped, + camera_names, + camera_height, + camera_width, + depth, + done_mode, + copy_rewards, + copy_dones, + exclude_next_obs, + compress, + use_custom_env, + custom_env_config, + force_robomimic_env, + const_reward +): + if depth: + assert len(camera_names) > 0, "must specify camera names if using depth" + + # create environment to use for data processing + env_meta = FileUtils.get_env_metadata_from_dataset(dataset_path=dataset) + + # some operations for playback are robosuite-specific, so determine if this environment is a robosuite env + is_robosuite_env = EnvUtils.is_robosuite_env(env_meta) + + # output file in same directory as input file + output_path = os.path.join(os.path.dirname(dataset), output_name) + + try: + # list of all demonstration episodes (sorted in increasing number order) + with ( + h5py.File(dataset, 'r') as f, + h5py.File(output_path, 'w') as f_out + ): + attrs = f['data'].attrs + demos = list(f["data"].keys()) + inds = np.argsort([int(elem[5:]) for elem in demos]) + demos = [demos[i] for i in inds] + + if use_custom_env: + with initialize(version_base=None, config_path='../configs'): + config = compose(config_name=custom_env_config) + env = make_robomimic_env( + env_config=config.env, + flatten_obs=False, + gymnasium_api=False, + )() + env.init_for_data_processing(camera_names=camera_names) + elif 'config_name' in attrs and not force_robomimic_env: + with initialize(version_base=None, config_path='../configs'): + config = compose(config_name=attrs['config_name']) + env = make_robomimic_env( + env_config=config.env, + flatten_obs=False, + gymnasium_api=False, + )() + env.init_for_data_processing(camera_names=camera_names) + else: + env = EnvUtils.create_env_for_data_processing( + env_meta=env_meta, + camera_names=camera_names, + camera_height=camera_height, + camera_width=camera_width, + reward_shaping=shaped, + use_depth_obs=depth, + ) + + if use_custom_env or ('config_name' in attrs and not force_robomimic_env): + print("==== Using custom env ====") + else: + print("==== Using environment with the following metadata ====") + print(json.dumps(env.serialize(), indent=4)) + print("") + + # maybe reduce the number of demonstrations to playback + if n is not None: + demos = demos[:n] + + data_grp = f_out.create_group("data") + print("input file: {}".format(dataset)) + print("output file: {}".format(output_path)) + + total_samples = 0 + for ind in tqdm(range(len(demos))): + ep = demos[ind] + + # prepare initial state to reload from + states = f["data/{}/states".format(ep)][()] + initial_state = dict(states=states[0]) + if is_robosuite_env: + initial_state["model"] = f["data/{}".format(ep)].attrs["model_file"] + + # extract obs, rewards, dones + actions = f["data/{}/actions".format(ep)][()] + traj, camera_info = extract_trajectory( + env=env, + initial_state=initial_state, + states=states, + actions=actions, + done_mode=done_mode, + camera_names=camera_names, + camera_height=camera_height, + camera_width=camera_width, + ) + + # maybe copy reward or done signal from source file + if copy_rewards: + traj["rewards"] = f["data/{}/rewards".format(ep)][()] + if copy_dones: + traj["dones"] = f["data/{}/dones".format(ep)][()] + + # store transitions + + # IMPORTANT: keep name of group the same as source file, to make sure that filter keys are + # consistent as well + ep_data_grp = data_grp.create_group(ep) + ep_data_grp.create_dataset("actions", data=np.array(traj["actions"])) + ep_data_grp.create_dataset("states", data=np.array(traj["states"])) + ep_data_grp.create_dataset("rewards", data=np.array(traj["rewards"])) + ep_data_grp.create_dataset("dones", data=np.array(traj["dones"])) + for k in traj["obs"]: + if compress: + ep_data_grp.create_dataset("obs/{}".format(k), data=np.array(traj["obs"][k]), compression="gzip") + else: + ep_data_grp.create_dataset("obs/{}".format(k), data=np.array(traj["obs"][k])) + if not exclude_next_obs: + if compress: + ep_data_grp.create_dataset("next_obs/{}".format(k), data=np.array(traj["next_obs"][k]), compression="gzip") + else: + ep_data_grp.create_dataset("next_obs/{}".format(k), data=np.array(traj["next_obs"][k])) + + # episode metadata + if is_robosuite_env: + ep_data_grp.attrs["model_file"] = traj["initial_state_dict"]["model"] # model xml for this episode + ep_data_grp.attrs["num_samples"] = traj["actions"].shape[0] # number of transitions in this episode + + if camera_info is not None: + assert is_robosuite_env + ep_data_grp.attrs["camera_info"] = json.dumps(camera_info, indent=4) + + total_samples += traj["actions"].shape[0] + + + # copy over all filter keys that exist in the original hdf5 + if "mask" in f: + f.copy("mask", f_out) + + # global metadata + data_grp.attrs["total"] = total_samples + # COPY ALL METADATA FROM ORIGINAL + for k in f["data"].attrs: + data_grp.attrs[k] = f["data"].attrs[k] + + env_args = env.serialize() + # placement initializer arg is a class that can't be json serialized + if "placement_initializer" in env_args['env_kwargs']: + env_args['env_kwargs']["placement_initializer"] = None + data_grp.attrs["env_args"] = json.dumps(env_args, indent=4) # environment info + if use_custom_env: + env_config = config.env + reward_function = env_config.reward_function + if reward_function is not None: + reward_type = reward_function.value + else: + reward_type = 'dense' if shaped else 'sparse' + else: + reward_type = 'dense' if shaped else 'sparse' + data_grp.attrs['reward_type'] = reward_type # reward type + if 'derived_from' in f['data'].attrs: + derived_from = json.loads(f['data'].attrs['derived_from']) + else: + derived_from = [] + data_grp.attrs['derived_from'] = json.dumps(derived_from + [f['data'].attrs['dataset_id']]) + data_grp.attrs['dataset_id'] = str(uuid.uuid4()) + print("Wrote {} trajectories to {}".format(len(demos), output_path)) + except Exception as e: + print("Error occurred during conversion. Deleting output file.") + os.remove(output_path) + raise e + +@click.command() +@click.option( + "--dataset", + type=str, + required=True, + help="path to input hdf5 dataset", +) +@click.option( + "--output_name", + type=str, + required=True, + help="name of output hdf5 dataset", +) +@click.option( + "--n", + type=int, + default=None, + help="(optional) stop after n trajectories are processed", +) +@click.option( + "--shaped", + is_flag=True, + help="(optional) use shaped rewards", +) +@click.option( + "--camera_names", + type=str, + multiple=True, + default=[], + help="(optional) camera name(s) to use for image observations. Leave out to not use image observations.", +) +@click.option( + "--camera_height", + type=int, + default=84, + help="(optional) height of image observations", +) +@click.option( + "--camera_width", + type=int, + default=84, + help="(optional) width of image observations", +) +@click.option( + "--depth", + is_flag=True, + help="(optional) use depth observations for each camera", +) +@click.option( + "--done_mode", + type=int, + default=0, + help="how to write done signal. If 0, done is 1 whenever s' is a success state.\ + If 1, done is 1 at the end of each trajectory. If 2, both.", +) +@click.option( + "--copy_rewards", + is_flag=True, + help="(optional) copy rewards from source file instead of inferring them", +) +@click.option( + "--copy_dones", + is_flag=True, + help="(optional) copy dones from source file instead of inferring them", +) +@click.option( + "--exclude_next_obs", + is_flag=True, + help="(optional) exclude next obs in dataset", +) +@click.option( + "--compress", + is_flag=True, + help="(optional) compress observations with gzip option in hdf5", +) +@click.option( + "--use_custom_env", + is_flag=True, + help="(optional) use custom RobomimicObsWrapper for data processing", +) +@click.option( + "--custom_env_config", + type=str, + default="sac_square_pushing", + help="(optional) hydra config name for custom RobomimicObsWrapper", +) +@click.option( + "--force_robomimic_env", + is_flag=True, + help="(optional) force Robomimic env for data processing", +) +@click.option( + "--const_reward", + type=float, + default=None, + help="(optional) constant reward for all transitions", +) +def main(dataset, output_name, n, shaped, camera_names, camera_height, camera_width, depth, done_mode, copy_rewards, copy_dones, exclude_next_obs, compress, use_custom_env, custom_env_config, force_robomimic_env, const_reward): + dataset_states_to_obs( + dataset, + output_name, + n, + shaped, + camera_names, + camera_height, + camera_width, + depth, + done_mode, + copy_rewards, + copy_dones, + exclude_next_obs, + compress, + use_custom_env, + custom_env_config, + force_robomimic_env, + const_reward + ) + +if __name__ == "__main__": + main() + diff --git a/code_src/rise_code/sim_pipeline/data_manager/dataset_summary.py b/code_src/rise_code/sim_pipeline/data_manager/dataset_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..3c961a7d8f35aecf08bae6950d59f0b3b9be95b6 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_manager/dataset_summary.py @@ -0,0 +1,141 @@ +import h5py +import hydra +import numpy as np +from sim_pipeline.data_manager.dataset_metadata_enums import * +from sim_pipeline.configs._data_summary.data_summary import DataSummaryConfig +from sim_pipeline.data_manager.get_dataset import get_dataset + +@hydra.main(config_path="../configs", config_name="data_summary", version_base=None) +def dataset_summary(data_summary_cfg: DataSummaryConfig): + data_cfg = data_summary_cfg.data + dataset_path = get_dataset(data_cfg) + get_dataset_summary(dataset_path) + +def get_dataset_summary(file_path: str): + entropies = [] + with h5py.File(file_path, 'r') as f: + data = f['data'] + attrs = data.attrs + + ep_keys = list(data.keys()) + + traj_lengths = [] + action_min = np.inf + action_max = -np.inf + for ep in ep_keys: + traj_lengths.append(data[ep]['actions'].shape[0]) + action_min = min(action_min, np.min(data[ep]['actions'][()])) + action_max = max(action_max, np.max(data[ep]['actions'][()])) + traj_lengths = np.array(traj_lengths) + + if 'obs' in data[ep_keys[0]]: + processed_status = ProcessedStatus.PROCESSED + elif 'mask' not in f: + processed_status = ProcessedStatus.RAW_TELEOP + else: + processed_status = ProcessedStatus.PRE_PROCESSED + + print(f'FILE: {file_path}') + + for ep in ep_keys: + if 'entropy' in data[ep]: + entropies.append(data[ep]['entropy'][()]) + + import ipdb; ipdb.set_trace() + + print('==== Dataset Metadata ====') + print(f'ID: {attrs["dataset_id"]}') + print('Processed Status:', processed_status) + print(f'env_name: {attrs["env_name"]}') + print(f'env_type: {attrs["env_type"]}') + print(f'data_type: {attrs["dataset_type"]}') + print(f'action_type: {attrs["action_type"]}') + if processed_status == ProcessedStatus.PROCESSED: + print(f'reward_type: {attrs["reward_type"]}') + print(f'is_real: {attrs["is_real"]}') + if 'combined' in attrs and attrs['combined']: + print(f'This is a combined dataset with constituents{attrs["constituent_dataset_id"]}') + if 'date' in attrs: + print(f'creation date: {attrs["date"]}') + if 'creator' in attrs: + print(f'creator: {attrs["creator"]}') + + print("==== Trajectory Summary ====") + print(f"total transitions: {np.sum(traj_lengths)}") + print(f"total trajectories: {traj_lengths.shape[0]}") + print(f"traj length mean: {np.mean(traj_lengths)}") + print(f"traj length std: {np.std(traj_lengths)}") + print(f"traj length min: {np.min(traj_lengths)}") + print(f"traj length max: {np.max(traj_lengths)}") + print(f"action min: {action_min}") + print(f"action max: {action_max}") + print("") + + # traj length processing + num_flagged = 0 + flagged = [] + for i in range(len(traj_lengths)): + if traj_lengths[i] > 1.5 * np.std(traj_lengths) + np.mean(traj_lengths): + num_flagged += 1 + print(i, traj_lengths[i]) + flagged.append(i) + print("total flagged", num_flagged) + print(flagged) + + if processed_status != ProcessedStatus.PROCESSED: + print('Dataset is not processed, and thus does not have observations') + return + + print("==== Dataset Structure ====") + for ep in ep_keys: + print(f"episode {ep} with {data[ep].attrs['num_samples']} transitions") + for k in data[ep]: + if k in ["obs", "next_obs"]: + print(f" key: {k}") + for obs_k in data[ep][k]: + shape = data[ep][k][obs_k].shape + print(f" observation key {obs_k} with shape {shape}") + elif isinstance(data[ep][k], h5py.Dataset): + key_shape = data[ep][k].shape + print(f" key: {k} with shape {key_shape}") + break + + if 'description' in data.attrs: + print('==== Dataset Description ====') + print(data.attrs['description']) + print('') + + # entropies2 = [] + # for entropy in entropies: + # entropy = np.array(entropy) + # entropy *= 1#1 / (1 + np.exp(-10*(entropy - 0.5))) + # entropies2.append(entropy) + # entropies = entropies2 + # import matplotlib.pyplot as plt + # if entropies: + # max_length = max(len(e) for e in entropies) + # avg_entropies = [] + # std_entropies = [] + # for t in range(max_length): + # valid_entropies = [e[t] for e in entropies if len(e) > t] + # if valid_entropies: + # avg_entropies.append(np.mean(valid_entropies)) + # std_entropies.append(np.std(valid_entropies)) + # else: + # avg_entropies.append(np.nan) + # std_entropies.append(np.nan) + + # plt.figure() + # plt.plot(avg_entropies, label='Average Entropy') + # plt.fill_between(range(max_length), + # np.array(avg_entropies) - np.array(std_entropies), + # np.array(avg_entropies) + np.array(std_entropies), + # color='b', alpha=0.2, label='Std Deviation') + # plt.xlabel('Timestep') + # plt.ylabel('Entropy') + # plt.title('Average Entropy Across All Demos') + # plt.legend() + # plt.savefig('average_entropy.png') + # import matplotlib.pyplot as plt + # plt.plot(entropies[6]) + # plt.savefig('entropy.png') diff --git a/code_src/rise_code/sim_pipeline/data_manager/edit_dataset_description.py b/code_src/rise_code/sim_pipeline/data_manager/edit_dataset_description.py new file mode 100644 index 0000000000000000000000000000000000000000..0a7d030a540dc12c2b6445aaaff6ec8cb93c00f8 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_manager/edit_dataset_description.py @@ -0,0 +1,31 @@ +import hydra +import h5py +import tempfile +import subprocess + +from sim_pipeline.configs._data_summary.data_summary import DataSummaryConfig +from sim_pipeline.data_manager.get_dataset import get_dataset + + + +@hydra.main(config_path="../sim_pipeline/configs", config_name="data_summary", version_base=None) +def main(data_summary_cfg: DataSummaryConfig): + data_cfg = data_summary_cfg.data + dataset_path = get_dataset(data_cfg) + + edit_dataset_description(dataset_path) + +def edit_dataset_description(dataset_path: str): + with h5py.File(dataset_path, 'r+') as f: + data = f['data'] + if 'description' not in data.attrs: + data.attrs['description'] = '' + + with tempfile.NamedTemporaryFile(suffix='.txt', mode='w+') as tmp: + tmp.write(data.attrs['description']) + tmp.flush() + + subprocess.call(['vim', '+1', '-c set filetype=txt', tmp.name]) + + with open(tmp.name, 'r') as tmp_f: + data.attrs['description'] = tmp_f.read() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/data_manager/filter_dataset.py b/code_src/rise_code/sim_pipeline/data_manager/filter_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..e7964756f0128841aacb7adc454d464ded7a96f6 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_manager/filter_dataset.py @@ -0,0 +1,77 @@ +import click +import os +import h5py +import uuid +import numpy as np + +from robomimic.scripts.split_train_val import split_train_val_from_hdf5 + +@click.command() +@click.option('--dataset', '-d', help='Datset file path') +@click.option('--output_name', '-o', help='Output file name') +def filter_dataset(dataset, output_name): + print(f'Filtering dataset {dataset}') + # output file in same directory as input file + output_path = os.path.join(os.path.dirname(dataset), output_name) + + with ( + h5py.File(dataset, 'r') as f, + h5py.File(output_path, 'w') as f_filtered + ): + data = f['data'] + out_data = f_filtered.create_group("data") + + new_demos = [] + new_total = 0 + demo_counter = 0 + for ep_key in data: + ep = data[ep_key] + # end_obj_pos = ep['obs']['object'][-1] + # filter if object xy position is within the range + # if -0.14 <= end_obj_pos[0] <= 0.0 and 0.11 <= end_obj_pos[1] <= 0.2: + obs_keys = ep['obs'].keys() + include = True + for key in obs_keys: + if key not in ['123622270810_rgb', '207322251049_rgb', 'action', 'lang_embed', 'language_instruction', 'lowdim_ee', 'lowdim_qpos']: + include = False + break + for key in ['123622270810_rgb', '207322251049_rgb']: + if key not in obs_keys: + include = False + break + + if include: + new_demos.append(ep_key) + new_total += ep['actions'].shape[0] + + data.copy( + source=ep, + dest=out_data, + name=f'demo_{demo_counter}' + ) + out_data_grp = out_data[f'demo_{demo_counter}'] + demo_counter += 1 + + out_data_grp['obs'].move('123622270810_rgb', 'eye_in_hand_image') + out_data_grp['obs'].move('207322251049_rgb', 'agentview_image') + + # copy episode attributes + for key, val in ep.attrs.items(): + out_data_grp.attrs[key] = val + + # copy dataset attributes + for key, val in data.attrs.items(): + if key == 'total': + out_data.attrs[key] = new_total + elif key == 'dataset_id': + out_data.attrs[key] = str(uuid.uuid4()) + elif key == 'description': + out_data.attrs[key] = val + ' filtered' + else: + out_data.attrs[key] = val + + # recreate the train-validation split + split_train_val_from_hdf5(hdf5_path=output_path, val_ratio=0.0) + +if __name__ == "__main__": + filter_dataset() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/data_manager/get_dataset.py b/code_src/rise_code/sim_pipeline/data_manager/get_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..109285a917c81d4b75e08ffea2ddced6a5503af9 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_manager/get_dataset.py @@ -0,0 +1,82 @@ +import os +from pathlib import Path +from omegaconf import OmegaConf +from sim_pipeline.data_manager.data_manager import DataManager +from sim_pipeline.configs.constants import DATASET_DB_PATH +from sim_pipeline.configs.data.base_data import BaseDataConfig +from sim_pipeline.data_manager.dataset_metadata_enums import ObsType + +def get_default_directories() -> list[Path]: + if 'DATASET_PATHS' not in os.environ: + print( + "Please set the DATASET_PATHS environment variable to a list of directories to search for datasets.\n" + "Delimit directories with commas.\n" + "Example: export DATASET_PATHS='/path/to/dataset1,/path/to/dataset2'\n" + ) + raise ValueError + else: + paths = os.environ['DATASET_PATHS'].split(',') + return [Path(p) for p in paths] + + +def convert_data_cfg_to_query(data_cfg: BaseDataConfig) -> dict: + data_queries = OmegaConf.to_container(data_cfg) + dq = {} + for key, value in data_queries.items(): + if key == 'name' and value != '': + value = value.split('+') + if key == 'obs_type' and value is not None: + assert isinstance(value, ObsType) + included_keys = value.included_keys() + excluded_keys = value.excluded_keys() + if included_keys: + dq['obs_keys'] = included_keys + if excluded_keys: + dq['exclude_obs_keys'] = excluded_keys + if not (value is None or value == ''): + dq[key] = value + return dq + + +def update_db_if_moved(dm: DataManager) -> None: + if not dm.check_updated(): + print('Dataset paths moved. Re-parsing directories...') + dm.create_tables() + paths = get_default_directories() + dm.parse_directories(paths) + + +def get_dataset(data_cfg: BaseDataConfig) -> str: + # rsm_rise patch: an explicit dataset_path needs no dataset-manager database + if data_cfg.dataset_path: + if Path(data_cfg.dataset_path).exists() and Path(data_cfg.dataset_path).is_file(): + return data_cfg.dataset_path + raise ValueError(f'Provided explicit dataset path, but it is invalid: {data_cfg.dataset_path}') + if not DATASET_DB_PATH.exists(): + raise ValueError(f'Dataset manager not set up. Please run `python scripts/setup_data_manager.py`') + with DataManager(DATASET_DB_PATH) as dm: + update_db_if_moved(dm) + + if data_cfg.dataset_path: + if Path(data_cfg.dataset_path).exists() and Path(data_cfg.dataset_path).is_file(): + return data_cfg.dataset_path + else: + raise ValueError(f'Provided explicit dataset path, but it is invalid: {data_cfg.dataset_path}') + + data_queries = convert_data_cfg_to_query(data_cfg) + dataset_path = dm.get_dataset(attempt_combination=not data_cfg.do_not_combine, **data_queries) + if dataset_path is None: + print( + f'No dataset found with the given query in cfg {data_cfg}\n' + f'Either no datasets match the query or the query returned multiple\n' + f'datasets that are incompatible with eachother.\n' + f'If you think the query is correct,\n', + f'please make sure your data manager is updated if you have\n' + f'recently collected data. This can be done by running \n' + f'`python scripts/setup_data_manager.py`.\n' + f'Also, when doing this, please make sure your DATASET_PATHS environment variable\n' + f'is set to the correct directories, deliminated by commas.\n' + f"Example: export DATASET_PATHS='/path/to/dataset1,/path/to/dataset2'\n" + ) + raise ValueError + return dataset_path \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/data_manager/kde.py b/code_src/rise_code/sim_pipeline/data_manager/kde.py new file mode 100644 index 0000000000000000000000000000000000000000..fbe6c221c8e29423dbc7993bf805a41d0a7402de --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_manager/kde.py @@ -0,0 +1,221 @@ +import click +import numpy as np +import matplotlib.pyplot as plt +import h5py +from sklearn.neighbors import KernelDensity +from mpl_toolkits.mplot3d import Axes3D # necessary for 3D plotting + +@click.command() +@click.option('--dataset', '-d', required=True, type=click.Path(exists=True), help='Path to the HDF5 dataset.') +@click.option('--sample_percentage', '-p', default=100.0, help='Percentage of states to sample (0-100).') +@click.option('--use-states', '-s', is_flag=True, default=True, help='Plot state distribution only. If False, plot state-action distribution instead.') +@click.option('--query-state', '-q', default=[-0.2, 0.2, 0.9], multiple=True, help='Query state for state-action distribution.') +@click.option('--state-bandwidth', '-sb', default=1.0, help='Bandwidth for state-action query, to specify neighbhorhood-ness') +@click.option('--kde-bandwidth-state', '-ks', default=0.01, help='Bandwidth for state KDE') +@click.option('--kde-bandwidth-action', '-ka', default=0.01, help='Bandwidth for action KDE') +def main(dataset, sample_percentage, use_states, query_state, state_bandwidth, kde_bandwidth_state, kde_bandwidth_action): + # ------------------------------- + # 1. Load your data + # ------------------------------- + with h5py.File(dataset, 'r') as f: + data = f['data'] + + # gather states and actions from all episodes + states_list = [] + actions_list = [] + + for ep_key in data: + ep = data[ep_key] + # Replace this with your actual dataset fields for (X, Y, Z) state data + ep_states = ep['obs']['robot0_eef_pos'][:] + # valid_indices = np.where((ep_states[:, 0] < -0.1) & (ep_states[:, 1] > 0.1))[0] + filtered_states = ep_states[:] + filtered_actions = ep['actions'][:, :3][:] + + states_list.append(filtered_states) + actions_list.append(filtered_actions) + + # combine all episodes into single arrays + states = np.concatenate(states_list, axis=0) + actions = np.concatenate(actions_list, axis=0) + + # # Sample only p% of the states if needed + if sample_percentage < 100.0: + p = sample_percentage / 100.0 + total_states = len(states) + sample_size = int(total_states * p) + indices = np.random.choice(total_states, sample_size, replace=False) + states = states[indices] + actions = actions[indices] + + if use_states: + state_distribution(states, kde_bandwidth_state) + else: + state_action_distribution(states, actions, query_state, state_bandwidth, kde_bandwidth_action) + + +def state_distribution(states, kde_bandwidth_state): + # ------------------------------- + # 2. Run KDE on the state positions + # ------------------------------- + bandwidth = kde_bandwidth_state + kde = KernelDensity(bandwidth=bandwidth, kernel='gaussian') + kde.fit(states) + + # Evaluate the density at each state position + log_density = kde.score_samples(states) # returns log density + density = np.exp(log_density) # convert to actual density values + + # ------------------------------- + # 3. Visualize the data in 3D + # ------------------------------- + fig = plt.figure(figsize=(10, 8)) + ax = fig.add_subplot(111, projection='3d') + + # Plot the state positions, coloring by density + scatter = ax.scatter(states[:, 0], states[:, 1], states[:, 2], + c=density, cmap='viridis', s=50, alpha=0.8) + cbar = plt.colorbar(scatter, ax=ax, shrink=0.5, aspect=10) + cbar.set_label('Estimated Density') + + # Label axes and add a title + ax.set_xlabel('X') + ax.set_ylabel('Y') + ax.set_zlabel('Z') + ax.set_title('3D State KDE') + + plt.show() + + # ------------------------------- + # 4. Visualize pairwise 2D slices + # ------------------------------- + state_labels = ['X', 'Y', 'Z'] + pairs = [(0, 1), (0, 2), (1, 2)] + + fig2, axs = plt.subplots(1, 3, figsize=(18, 5)) + for ax2, (i, j) in zip(axs, pairs): + s_i = states[:, i] + s_j = states[:, j] + + # Define grid limits for the current two dimensions (with a margin) + margin = 0.5 + s_i_min, s_i_max = s_i.min() - margin, s_i.max() + margin + s_j_min, s_j_max = s_j.min() - margin, s_j.max() + margin + + # Create a grid over the two dimensions + grid_i = np.linspace(s_i_min, s_i_max, 100) + grid_j = np.linspace(s_j_min, s_j_max, 100) + S_i, S_j = np.meshgrid(grid_i, grid_j) + + # For the full 3D state KDE, fix the remaining dimension to its mean + k = [dim for dim in range(3) if dim not in [i, j]][0] + mean_k = np.mean(states[:, k]) + + # Build grid points in 3D: set dimensions i and j from the grid, dimension k fixed + grid_points = np.zeros((S_i.size, 3)) + grid_points[:, i] = S_i.ravel() + grid_points[:, j] = S_j.ravel() + grid_points[:, k] = mean_k + + # Evaluate the density on the grid (in log space) + log_dens = kde.score_samples(grid_points) + dens = np.exp(log_dens).reshape(S_i.shape) + + # Plot the contour density + cont = ax2.contourf(S_i, S_j, dens, levels=30, cmap='viridis') + ax2.set_xlabel(state_labels[i]) + ax2.set_ylabel(state_labels[j]) + ax2.set_title(f'Pairwise KDE ({state_labels[i]}, {state_labels[j]})') + + fig2.colorbar(cont, ax=axs, fraction=0.03, pad=0.04, label='Density') + plt.suptitle('Pairwise 2D State KDE Slices', fontsize=16) + plt.tight_layout(rect=[0, 0, 1, 0.95]) + plt.show() + +def state_action_distribution(states, actions, query_state, state_bandwidth, kde_bandwidth_action): + # ------------------------------- + # 2. Specify query state and "nearbiness" in state space + # ------------------------------- + # The state bandwidth controls how quickly the influence of a data point decays with distance. + state_bw = state_bandwidth + + # ------------------------------- + # 3. Compute weights based on state proximity + # ------------------------------- + # Using a Gaussian kernel on the state-space distance: + diffs = states - query_state # (n_samples, 3) + dists_sq = np.sum(diffs**2, axis=1) + weights = np.exp(-dists_sq / (2 * state_bw**2)) + + # Set weights of actions with magnitude less than 0.1 to 0 + action_magnitudes = np.linalg.norm(actions, axis=1) + weights[action_magnitudes < 0.1] = 0 + + # (Optional) Normalize the weights (not strictly necessary for KDE) + if np.sum(weights) > 0: + weights /= np.sum(weights) + + # ------------------------------- + # 4. Estimate the marginal action distribution with weighted KDE + # ------------------------------- + # We’re estimating a KDE on the 3D action space. + action_bw = kde_bandwidth_action + kde_action = KernelDensity(kernel='gaussian', bandwidth=action_bw) + kde_action.fit(actions, sample_weight=weights) # Note: scikit-learn supports sample_weight in recent versions + + # ------------------------------- + # 5. Visualize the marginal action distribution (pairwise 2D slices) + # ------------------------------- + # Because our action space is 3D, we plot 2D slices for each pair of action dimensions. + action_labels = ['dx', 'dy', 'dz'] + pairs = [(0, 1), (0, 2), (1, 2)] + + fig, axs = plt.subplots(1, 3, figsize=(18, 5)) + + for ax, (i, j) in zip(axs, pairs): + # Extract the corresponding action dimensions for plotting + a_i = actions[:, i] + a_j = actions[:, j] + + # Define grid limits for the current two dimensions (with a margin) + margin = 0.5 + a_i_min, a_i_max = a_i.min() - margin, a_i.max() + margin + a_j_min, a_j_max = a_j.min() - margin, a_j.max() + margin + + # Create a grid over the two dimensions + grid_i = np.linspace(a_i_min, a_i_max, 100) + grid_j = np.linspace(a_j_min, a_j_max, 100) + A_i, A_j = np.meshgrid(grid_i, grid_j) + + # For the full 3D action KDE, we must provide a value for the third (omitted) dimension. + # A good choice is its weighted mean (in the neighborhood). + k = [dim for dim in range(3) if dim not in [i, j]][0] + weighted_mean_k = np.average(actions[:, k], weights=weights) + + # Build grid points in 3D: set dimensions i and j from the grid, and dimension k fixed. + grid_points = np.zeros((A_i.size, 3)) + grid_points[:, i] = A_i.ravel() + grid_points[:, j] = A_j.ravel() + grid_points[:, k] = weighted_mean_k + + # Evaluate the density on the grid (in log space) + log_dens = kde_action.score_samples(grid_points) + dens = np.exp(log_dens).reshape(A_i.shape) + + # Plot the contour density and overlay the actual (projected) action samples. + cont = ax.contourf(A_i, A_j, dens, levels=30, cmap='viridis') + # ax.scatter(a_i, a_j, c='red', s=10, alpha=0.5) + ax.set_xlabel(action_labels[i]) + ax.set_ylabel(action_labels[j]) + ax.set_title(f'p({action_labels[i]}, {action_labels[j]} | s ~ {query_state})') + + # Add a colorbar common to all subplots. + fig.colorbar(cont, ax=axs, fraction=0.03, pad=0.04, label='Density') + plt.suptitle('Marginal Action Distribution p(a|s) in a State Neighborhood', fontsize=16) + plt.tight_layout(rect=[0, 0, 1, 0.95]) + plt.show() + + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/data_manager/kde_test.py b/code_src/rise_code/sim_pipeline/data_manager/kde_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e06d9a2910e84f91bae48353a59b9a78a35d5947 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_manager/kde_test.py @@ -0,0 +1,236 @@ +import numpy as np +import plotly.graph_objs as go +import dash +import h5py +import click +from dash import dcc, html, Output, Input + + +@click.command() +@click.option('--dataset', '-d', required=True, type=click.Path(exists=True), help='Path to the HDF5 dataset.') +@click.option('--sample_percentage', '-p', default=100.0, help='Percentage of states to sample (0-100).') +def main(dataset, sample_percentage): + + # --------------------------- + # 1. Generate (or load) data + # --------------------------- + with h5py.File(dataset, 'r') as f: + data = f['data'] + + # gather states and actions from all episodes + states_list = [] + actions_list = [] + + for ep_key in data: + ep = data[ep_key] + # Replace this with your actual dataset fields for (X, Y, Z) state data + ep_states = ep['obs']['robot0_eef_pos'][:] + # valid_indices = np.where((ep_states[:, 0] < -0.1) & (ep_states[:, 1] > 0.1))[0] + filtered_states = ep_states[:] + filtered_actions = ep['actions'][:, :3][:] + + states_list.append(filtered_states) + actions_list.append(filtered_actions) + + # combine all episodes into single arrays + states = np.concatenate(states_list, axis=0) + actions = np.concatenate(actions_list, axis=0) + + # # Sample only p% of the states if needed + if sample_percentage < 100.0: + p = sample_percentage / 100.0 + total_states = len(states) + sample_size = int(total_states * p) + indices = np.random.choice(total_states, sample_size, replace=False) + states = states[indices] + actions = actions[indices] + + # --------------------------------------- + # 2. Function to create an ellipsoid mesh + # --------------------------------------- + def create_ellipsoid_mesh(center, radii, u_steps=12, v_steps=12): + """ + Create meshgrid coordinates for an ellipsoid. + center: 3-element array-like (center of ellipsoid) + radii: 3-element array-like (radii along x,y,z) + Returns: x, y, z mesh arrays. + """ + u = np.linspace(0, 2 * np.pi, u_steps) + v = np.linspace(0, np.pi, v_steps) + u, v = np.meshgrid(u, v) + x = radii[0] * np.cos(u) * np.sin(v) + center[0] + y = radii[1] * np.sin(u) * np.sin(v) + center[1] + z = radii[2] * np.cos(v) + center[2] + return x, y, z + + # --------------------------- + # 3. Build the Dash App Layout + # --------------------------- + app = dash.Dash(__name__) + app.layout = html.Div([ + html.H1("State–Action Distribution Visualization"), + html.Div([ + dcc.Graph( + id='state-scatter', + config={'displayModeBar': False}, + style={'height': '700px'} # Increased height + ), + html.P("Click on a state to select it for querying.") + ]), + html.Div([ + html.Label("Neighborhood Threshold (in state space)"), + dcc.Slider( + id='threshold-slider', + min=0.01, + max=1.0, + step=0.01, + value=0.05, + marks={i: f"{i:.1f}" for i in np.arange(0.1, 5.1, 0.5)} + ) + ], style={'width': '80%', 'margin': '20px auto'}), + html.Div([ + dcc.Graph( + id='action-ellipsoids', + config={'displayModeBar': False}, + style={'height': '700px'} # Increased height + ), + html.P("Marginal action distribution p(dx,dy,dz | s) as a blob of ellipsoids.") + ]) + ], style={'overflowY': 'auto', 'height': '1500px'}) # Allows scrolling + + # ----------------------------------------- + # 4. Callback: Update the 3D state scatter plot + # ----------------------------------------- + @app.callback( + Output('state-scatter', 'figure'), + [Input('state-scatter', 'clickData'), + Input('threshold-slider', 'value')] + ) + def update_state_scatter(clickData, threshold): + # Base scatter plot: all states in blue. + trace_all = go.Scatter3d( + x=states[:, 0], + y=states[:, 1], + z=states[:, 2], + mode='markers', + marker=dict(size=4, color='blue'), + name='All States' + ) + + # Create the initial figure. + fig = go.Figure(data=[trace_all], layout=go.Layout( + title="3D State Scatter (Click a state to query)", + scene=dict( + xaxis_title='X', + yaxis_title='Y', + zaxis_title='Z', + aspectmode='auto' + ), + margin=dict(l=0, r=0, b=0, t=30) + )) + + # If a state was clicked, compute and highlight the neighborhood. + if clickData is not None: + idx = clickData['points'][0]['pointNumber'] + selected_state = states[idx] + + # Compute Euclidean distances from the selected state. + distances = np.linalg.norm(states - selected_state, axis=1) + neighborhood_mask = distances <= threshold + neighborhood_states = states[neighborhood_mask] + + # Add neighborhood states in green. + trace_neighborhood = go.Scatter3d( + x=neighborhood_states[:, 0], + y=neighborhood_states[:, 1], + z=neighborhood_states[:, 2], + mode='markers', + marker=dict(size=6, color='green'), + name='Neighborhood' + ) + fig.add_trace(trace_neighborhood) + + # Highlight the selected state in red. + trace_selected = go.Scatter3d( + x=[selected_state[0]], + y=[selected_state[1]], + z=[selected_state[2]], + mode='markers', + marker=dict(size=10, color='red'), + name='Selected State' + ) + fig.add_trace(trace_selected) + + return fig + + # ----------------------------------------------------------- + # 5. Callback: Update the action distribution ellipsoids plot + # ----------------------------------------------------------- + @app.callback( + Output('action-ellipsoids', 'figure'), + [Input('state-scatter', 'clickData'), + Input('threshold-slider', 'value')] + ) + def update_action_ellipsoids(clickData, threshold): + # If no state is selected, display an empty plot with instructions. + if clickData is None: + layout = go.Layout( + title="Marginal Action Distribution p(a|s): Select a state from the above plot", + scene=dict(xaxis_title='dx', yaxis_title='dy', zaxis_title='dz'), + margin=dict(l=0, r=0, b=0, t=30) + ) + return go.Figure(layout=layout) + + # Determine the query state (selected state) and its neighborhood. + idx = clickData['points'][0]['pointNumber'] + query_state = states[idx] + dists = np.linalg.norm(states - query_state, axis=1) + # Use a hard threshold: keep only states with distance <= threshold. + neighborhood_mask = dists <= threshold + neighborhood_actions = actions[neighborhood_mask] + + # For clarity, if many actions fall in the neighborhood, sample a subset. + max_ellipsoids = 150 + if neighborhood_actions.shape[0] > max_ellipsoids: + sel_idx = np.random.choice(neighborhood_actions.shape[0], max_ellipsoids, replace=False) + sampled_actions = neighborhood_actions[sel_idx] + else: + sampled_actions = neighborhood_actions + + # Create a list of ellipsoid mesh traces. + # Here, we use a fixed radii for each ellipsoid (you can adjust as needed). + fixed_radii = [0.03, 0.03, 0.03] + ellipsoid_traces = [] + for act in sampled_actions: + x_e, y_e, z_e = create_ellipsoid_mesh(act, fixed_radii, u_steps=12, v_steps=12) + ellipsoid = go.Surface( + x=x_e, + y=y_e, + z=z_e, + opacity=0.5, + colorscale='Viridis', + showscale=False, + hoverinfo='skip' + ) + ellipsoid_traces.append(ellipsoid) + + layout = go.Layout( + title="Marginal Action Distribution p(dx,dy,dz | s)", + scene=dict( + xaxis_title='dx', + yaxis_title='dy', + zaxis_title='dz', + aspectmode='auto' + ), + margin=dict(l=0, r=0, b=0, t=30) + ) + fig = go.Figure(data=ellipsoid_traces, layout=layout) + return fig + app.run_server(debug=True) + + +# --------------------------- +# 6. Run the Dash App +# --------------------------- +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/data_manager/modify_dataset.py b/code_src/rise_code/sim_pipeline/data_manager/modify_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..525833d2c02b6683f24d494cac260f5061b4c3cb --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_manager/modify_dataset.py @@ -0,0 +1,41 @@ +import h5py +import datetime +import getpass +from sim_pipeline.data_manager.dataset_metadata_enums import * + +def fill_metadata( + dataset_file: h5py.File, + dataset_id: str | None = None, + dataset_type: DatasetType | None = None, + action_type: ActionType | None = None, + is_real: bool | None = None, + env_type: EnvType | None = None, + env_name: str | None = None, + reward_type: RewardType | None = None, + include_date: bool = False, + include_creator: bool = False, +): + grp = dataset_file['data'] + + if dataset_id is not None: + grp.attrs['dataset_id'] = dataset_id + if dataset_type is not None: + grp.attrs['dataset_type'] = dataset_type.value + if action_type is not None: + grp.attrs['action_type'] = action_type.value + if is_real is not None: + grp.attrs['is_real'] = is_real + if env_type is not None: + grp.attrs['env_type'] = env_type.value + if env_name is not None: + grp.attrs['env_name'] = env_name + if reward_type is not None: + grp.attrs['reward_type'] = reward_type.value + + if include_date: + now = datetime.datetime.now() + grp.attrs["date"] = "{}-{}-{}".format(now.month, now.day, now.year) + grp.attrs["time"] = "{}:{}:{}".format(now.hour, now.minute, now.second) + + if include_creator: + grp.attrs["creator"] = getpass.getuser() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/data_manager/normalize_actions.py b/code_src/rise_code/sim_pipeline/data_manager/normalize_actions.py new file mode 100644 index 0000000000000000000000000000000000000000..63b3c732fdf874b2448980c9d9407117ac80e5b0 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_manager/normalize_actions.py @@ -0,0 +1,84 @@ +import click +import os +import h5py +import uuid +import numpy as np +from tqdm import tqdm + +from contextlib import nullcontext +from robomimic.scripts.split_train_val import split_train_val_from_hdf5 + +@click.command() +@click.option('--dataset', '-d', help='Datset file path') +@click.option('--output_name', '-o', help='Output file name') +def normalize_dataset_actions(dataset, output_name): + print(f'Normalizing actions in dataset {dataset}') + # output file in same directory as input file + output_path = os.path.join(os.path.dirname(dataset), output_name) + + with ( + h5py.File(dataset, 'r') as f, + h5py.File(output_path, 'w') as f_normalized, + ): + data = f['data'] + out_data = f_normalized.create_group("data") + + # First pass - compute dataset-wide action statistics + print("Computing action statistics...") + action_list = [] + for ep_key in tqdm(data): + ep = data[ep_key] + actions = ep['actions'][:] + action_list.append(actions) + + all_actions = np.concatenate(action_list, axis=0) + + # Compute min and max for all dims except gripper + action_min = np.min(all_actions[:, :-1], axis=0) # shape: (n_dims-1,) + action_max = np.max(all_actions[:, :-1], axis=0) # shape: (n_dims-1,) + + # Save normalization stats + stats_grp = f_normalized.create_group("action_normalization_stats") + stats_grp.create_dataset("min", data=action_min) + stats_grp.create_dataset("max", data=action_max) + + # Second pass - normalize and save actions + print("Normalizing actions...") + demo_counter = 0 + for ep_key in tqdm(data): + ep = data[ep_key] + + data.copy( + source=ep, + dest=out_data, + name=f'demo_{demo_counter}' + ) + out_data_grp = out_data[f'demo_{demo_counter}'] + + # Get actions and normalize all dims except gripper + actions = out_data_grp['actions'][:] + # Scale to [0,1] then to [-0.5, 0.5] + actions[:, :-1] = (actions[:, :-1] - action_min) / (action_max - action_min) - 0.5 + + # Save normalized actions + del out_data_grp['actions'] + out_data_grp.create_dataset('actions', data=actions) + + demo_counter += 1 + + # copy episode attributes + for key, val in ep.attrs.items(): + out_data_grp.attrs[key] = val + + # copy dataset attributes + for key, val in data.attrs.items(): + if key == 'dataset_id': + out_data.attrs[key] = str(uuid.uuid4()) + else: + out_data.attrs[key] = val + + # recreate the train-validation split + split_train_val_from_hdf5(hdf5_path=output_path, val_ratio=0.1) + +if __name__ == "__main__": + normalize_dataset_actions() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/data_manager/playback_dataset.py b/code_src/rise_code/sim_pipeline/data_manager/playback_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..1de075a612f972e40f1f1bd4fb667ff07e93dcf2 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_manager/playback_dataset.py @@ -0,0 +1,293 @@ +""" +A script to visualize dataset trajectories by loading the simulation states +one by one or loading the first state and playing actions back open-loop. +The script can generate videos as well, by rendering simulation frames +during playback. The videos can also be generated using the image observations +in the dataset (this is useful for real-robot datasets) by using the +--use-obs argument. + +Example usage below: + + # force simulation states one by one, and render agentview and wrist view cameras to video + python playback_dataset.py --dataset /path/to/dataset.hdf5 \ + --render_image_names agentview robot0_eye_in_hand \ + --video_path /tmp/playback_dataset.mp4 + + # playback the actions in the dataset, and render agentview camera during playback to video + python playback_dataset.py --dataset /path/to/dataset.hdf5 \ + --use-actions --render_image_names agentview \ + --video_path /tmp/playback_dataset_with_actions.mp4 + + # use the observations stored in the dataset to render videos of the dataset trajectories + python playback_dataset.py --dataset /path/to/dataset.hdf5 \ + --use-obs --render_image_names agentview_image \ + --video_path /tmp/obs_trajectory.mp4 + + # visualize depth observations along with image observations + python playback_dataset.py --dataset /path/to/dataset.hdf5 \ + --use-obs --render_image_names agentview_image \ + --render_depth_names agentview_depth \ + --video_path /tmp/obs_trajectory.mp4 + + # visualize initial states in the demonstration data + python playback_dataset.py --dataset /path/to/dataset.hdf5 \ + --first --render_image_names agentview \ + --video_path /tmp/dataset_task_inits.mp4 +""" + +import os +import json +import h5py +import click +import imageio +import numpy as np + +import robomimic +import robomimic.utils.obs_utils as ObsUtils +import robomimic.utils.env_utils as EnvUtils +import robomimic.utils.file_utils as FileUtils +from robomimic.utils.vis_utils import depth_to_rgb +from robomimic.envs.env_base import EnvBase, EnvType + + +# Define default cameras to use for each env type +DEFAULT_CAMERAS = { + EnvType.ROBOSUITE_TYPE: ["agentview"], + EnvType.IG_MOMART_TYPE: ["rgb"], + EnvType.GYM_TYPE: ValueError("No camera names supported for gym type env!"), +} + + +def playback_trajectory_with_env( + env, + initial_state, + states, + actions=None, + render=False, + video_writer=None, + video_skip=5, + camera_names=None, + first=False, +): + """ + Helper function to playback a single trajectory using the simulator environment. + If @actions are not None, it will play them open-loop after loading the initial state. + Otherwise, @states are loaded one by one. + + Args: + env (instance of EnvBase): environment + initial_state (dict): initial simulation state to load + states (np.array): array of simulation states to load + actions (np.array): if provided, play actions back open-loop instead of using @states + render (bool): if True, render on-screen + video_writer (imageio writer): video writer + video_skip (int): determines rate at which environment frames are written to video + camera_names (list): determines which camera(s) are used for rendering. Pass more than + one to output a video with multiple camera views concatenated horizontally. + first (bool): if True, only use the first frame of each episode. + """ + assert isinstance(env, EnvBase) + + write_video = (video_writer is not None) + video_count = 0 + assert not (render and write_video) + + # load the initial state + env.reset() + env.reset_to(initial_state) + + traj_len = states.shape[0] + action_playback = (actions is not None) + if action_playback: + assert states.shape[0] == actions.shape[0] + + for i in range(traj_len): + if action_playback: + env.step(actions[i]) + if i < traj_len - 1: + # check whether the actions deterministically lead to the same recorded states + state_playback = env.get_state()["states"] + if not np.all(np.equal(states[i + 1], state_playback)): + err = np.linalg.norm(states[i + 1] - state_playback) + print("warning: playback diverged by {} at step {}".format(err, i)) + else: + env.reset_to({"states" : states[i]}) + + # on-screen render + if render: + env.render(mode="human", camera_name=camera_names[0]) + + # video render + if write_video: + if video_count % video_skip == 0: + video_img = [] + for cam_name in camera_names: + video_img.append(env.render(mode="rgb_array", height=512, width=512, camera_name=cam_name)) + video_img = np.concatenate(video_img, axis=1) # concatenate horizontally + video_writer.append_data(video_img) + video_count += 1 + + if first: + break + + +def playback_trajectory_with_obs( + traj_grp, + video_writer, + video_skip=5, + image_names=None, + depth_names=None, + first=False, +): + """ + This function reads all "rgb" (and possibly "depth") observations in the dataset trajectory and + writes them into a video. + + Args: + traj_grp (hdf5 file group): hdf5 group which corresponds to the dataset trajectory to playback + video_writer (imageio writer): video writer + video_skip (int): determines rate at which environment frames are written to video + image_names (list): determines which image observations are used for rendering. Pass more than + one to output a video with multiple image observations concatenated horizontally. + depth_names (list): determines which depth observations are used for rendering (if any). + first (bool): if True, only use the first frame of each episode. + """ + assert image_names is not None, "error: must specify at least one image observation to use in @image_names" + video_count = 0 + + if depth_names is not None: + # compute min and max depth value across trajectory for normalization + depth_min = { k : traj_grp["obs/{}".format(k)][:].min() for k in depth_names } + depth_max = { k : traj_grp["obs/{}".format(k)][:].max() for k in depth_names } + + traj_len = traj_grp["actions"].shape[0] + for i in range(traj_len): + if video_count % video_skip == 0: + # concatenate image obs together + im = [traj_grp["obs/{}".format(k)][i] for k in image_names] + depth = [depth_to_rgb(traj_grp["obs/{}".format(k)][i], depth_min=depth_min[k], depth_max=depth_max[k]) for k in depth_names] if depth_names is not None else [] + frame = np.concatenate(im + depth, axis=1) + video_writer.append_data(frame) + video_count += 1 + + if first: + break + + +@click.command() +@click.option('--dataset', type=str, help='Path to hdf5 dataset', required=True) +@click.option('--filter_key', type=str, default=None, help='Filter key to select subset of trajectories') +@click.option('--n', type=int, default=None, help='Stop after n trajectories') +@click.option('--use-obs', is_flag=True, help='Visualize trajectories with dataset image observations') +@click.option('--use-actions', is_flag=True, help='Use open-loop action playback') +@click.option('--render', is_flag=True, help='On-screen rendering') +@click.option('--video_path', type=str, default=None, help='Path to save video') +@click.option('--video_skip', type=int, default=5, help='Render frames to video every n steps') +@click.option('--render_image_names', type=str, multiple=True, default=None, help='Camera names/image observations for rendering') +@click.option('--render_depth_names', type=str, multiple=True, default=None, help='Depth observations for rendering') +@click.option('--first', is_flag=True, help='Use first frame of each episode') +def playback_dataset(dataset, filter_key, n, use_obs, use_actions, render, video_path, video_skip, render_image_names, render_depth_names, first): + # some arg checking + write_video = (video_path is not None) + assert not (render and write_video) # either on-screen or video but not both + + # Auto-fill camera rendering info if not specified + if not render_image_names: + # We fill in the automatic values + env_meta = FileUtils.get_env_metadata_from_dataset(dataset_path=dataset) + env_type = EnvUtils.get_env_type(env_meta=env_meta) + render_image_names = DEFAULT_CAMERAS[env_type] + + if render: + # on-screen rendering can only support one camera + assert len(render_image_names) == 1 + + if use_obs: + assert write_video, "playback with observations can only write to video" + assert not use_actions, "playback with observations is offline and does not support action playback" + + if render_depth_names: + assert use_obs, "depth observations can only be visualized from observations currently" + + # create environment only if not playing back with observations + if not use_obs: + # need to make sure ObsUtils knows which observations are images, but it doesn't matter + # for playback since observations are unused. Pass a dummy spec here. + dummy_spec = dict( + obs=dict( + low_dim=["robot0_eef_pos"], + rgb=[], + ), + ) + ObsUtils.initialize_obs_utils_with_obs_specs(obs_modality_specs=dummy_spec) + + env_meta = FileUtils.get_env_metadata_from_dataset(dataset_path=dataset) + env = EnvUtils.create_env_from_metadata(env_meta=env_meta, render=render, render_offscreen=write_video) + + # some operations for playback are robosuite-specific, so determine if this environment is a robosuite env + is_robosuite_env = EnvUtils.is_robosuite_env(env_meta) + + f = h5py.File(dataset, "r") + + # list of all demonstration episodes (sorted in increasing number order) + if filter_key is not None: + print("using filter key: {}".format(filter_key)) + demos = [elem.decode("utf-8") for elem in np.array(f["mask/{}".format(filter_key)])] + else: + demos = list(f["data"].keys()) + inds = np.argsort([int(elem[5:]) for elem in demos]) + demos = [demos[i] for i in inds] + + # maybe reduce the number of demonstrations to playback + if n is not None: + demos = demos[:n] + + # maybe dump video + video_writer = None + if write_video: + video_writer = imageio.get_writer(video_path, fps=20) + + for ind in range(len(demos)): + ep = demos[ind] + print("Playing back episode: {}".format(ep)) + + if use_obs: + playback_trajectory_with_obs( + traj_grp=f["data/{}".format(ep)], + video_writer=video_writer, + video_skip=video_skip, + image_names=render_image_names, + depth_names=render_depth_names, + first=first, + ) + continue + + # prepare initial state to reload from + states = f["data/{}/states".format(ep)][()] + initial_state = dict(states=states[0]) + if is_robosuite_env: + initial_state["model"] = f["data/{}".format(ep)].attrs["model_file"] + + # supply actions if using open-loop action playback + actions = None + if use_actions: + actions = f["data/{}/actions".format(ep)][()] + + playback_trajectory_with_env( + env=env, + initial_state=initial_state, + states=states, actions=actions, + render=render, + video_writer=video_writer, + video_skip=video_skip, + camera_names=render_image_names, + first=first, + ) + + f.close() + if write_video: + video_writer.close() + + +if __name__ == "__main__": + playback_dataset() diff --git a/code_src/rise_code/sim_pipeline/data_manager/relabel_dino_features.py b/code_src/rise_code/sim_pipeline/data_manager/relabel_dino_features.py new file mode 100644 index 0000000000000000000000000000000000000000..6474bf93758561739e491cdf625ab5d1f18fd7c9 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_manager/relabel_dino_features.py @@ -0,0 +1,92 @@ +import click +import torch +import os +import h5py +import uuid +import numpy as np + +from tqdm import tqdm +from contextlib import nullcontext +from robomimic.scripts.split_train_val import split_train_val_from_hdf5 +from robomimic.models.obs_core import DinoV2Core + +def relabel_key(ep, out_data_grp, key, feature_model, batch_size, model_device): + obs = ep[key] + obs_dict = {k: obs[k][:] for k in obs.keys() if 'image' in k} + + for k in obs_dict.keys(): + obs_dict[k] = obs_dict[k].transpose(0, 3, 2, 1) + obs_dict[k] = obs_dict[k].astype(float) / 255.0 + + ep_features = [] + for image_key in sorted(obs_dict.keys()): + all_img_features = [] + all_imgs = obs_dict[image_key] + for index in tqdm(range(0, all_imgs.shape[0], batch_size), desc='processing batch', leave=False): + img_batch = all_imgs[index:min(index+batch_size, all_imgs.shape[0])] + img_batch = torch.from_numpy(img_batch).to(model_device).float() + img_batch_features = feature_model(img_batch).detach().cpu().numpy() + all_img_features.append(img_batch_features) + all_img_features = np.concatenate(all_img_features, axis=0) + ep_features.append(all_img_features) + ep_features = np.concatenate(ep_features, axis=1) + + feature_shape = ep_features.shape[1] + out_data_grp[key].create_dataset('dino_features', shape=(ep['actions'].shape[0], feature_shape), dtype=np.float32) + out_data_grp[key]['dino_features'][:] = ep_features + for image_key in obs_dict: + del out_data_grp[key][image_key] + +@click.command() +@click.option('--dataset', '-d', help='Datset file path') +@click.option('--output_name', '-o', help='Output file name') +@click.option('--batch_size', '-b', default=4, type=int, help='Batch size for feature model') +def relabel_dino_features(dataset, output_name, batch_size): + print(f'Relabeling images with dino features in dataset {dataset}') + # output file in same directory as input file + output_path = os.path.join(os.path.dirname(dataset), output_name) + + feature_model = DinoV2Core(input_shape=(3, 84, 84), backbone_name='dinov2_vits14', concatenate=True) + model_device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + feature_model.to(model_device) + feature_model.eval() + + with ( + h5py.File(dataset, 'r') as f, + h5py.File(output_path, 'w') as f_relabeled, + ): + data = f['data'] + out_data = f_relabeled.create_group("data") + + demo_counter = 0 + for ep_key in tqdm(data, desc='processing episodes'): + ep = data[ep_key] + + data.copy( + source=ep, + dest=out_data, + name=f'demo_{demo_counter}' + ) + out_data_grp = out_data[f'demo_{demo_counter}'] + + relabel_key(ep, out_data_grp, 'obs', feature_model, batch_size, model_device) + relabel_key(ep, out_data_grp, 'next_obs', feature_model, batch_size, model_device) + + demo_counter += 1 + + # copy episode attributes + for key, val in ep.attrs.items(): + out_data_grp.attrs[key] = val + + # copy dataset attributes + for key, val in data.attrs.items(): + if key == 'dataset_id': + out_data.attrs[key] = str(uuid.uuid4()) + else: + out_data.attrs[key] = val + + # recreate the train-validation split + split_train_val_from_hdf5(hdf5_path=output_path, val_ratio=0.1) + +if __name__ == "__main__": + relabel_dino_features() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/data_manager/relabel_rewards.py b/code_src/rise_code/sim_pipeline/data_manager/relabel_rewards.py new file mode 100644 index 0000000000000000000000000000000000000000..0c29f3553c95397e11fecfa81dd073b9fbf90bf4 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_manager/relabel_rewards.py @@ -0,0 +1,71 @@ +import click +import os +import h5py +import uuid +import numpy as np + +from contextlib import nullcontext +from robomimic.scripts.split_train_val import split_train_val_from_hdf5 + +@click.command() +@click.option('--dataset', '-d', help='Datset file path') +@click.option('--output_name', '-o', help='Output file name') +@click.option('--const_reward', '-c', type=float, help='Constant reward', default=0.0) +@click.option('--copy_from_dataset', '-cf', type=str, help='Copy rewards from this dataset path', default=None) +@click.option('--monotonic_increase', '-m', is_flag=True, help='Whether to monotonically increase rewards') +def relabel_dataset_rewards(dataset, output_name, const_reward, copy_from_dataset, monotonic_increase): + print(f'Relabeling rewards in dataset {dataset}') + # output file in same directory as input file + output_path = os.path.join(os.path.dirname(dataset), output_name) + + with ( + h5py.File(dataset, 'r') as f, + h5py.File(output_path, 'w') as f_relabeled, + h5py.File(copy_from_dataset, 'r') if copy_from_dataset is not None else nullcontext() as f_copy_from, + ): + data = f['data'] + out_data = f_relabeled.create_group("data") + + demo_counter = 0 + for ep_key in data: + ep = data[ep_key] + + data.copy( + source=ep, + dest=out_data, + name=f'demo_{demo_counter}' + ) + out_data_grp = out_data[f'demo_{demo_counter}'] + if copy_from_dataset is not None: + copy_from_data = f_copy_from['data'] + copy_from_ep = copy_from_data[ep_key] + out_data_grp['rewards'][:] = copy_from_ep['rewards'][:] + else: + if 'rewards' not in out_data_grp: + out_data_grp.create_dataset('rewards', shape=(ep['actions'].shape[0],), dtype=np.float32) + + if monotonic_increase: + # Create linearly increasing rewards from 1 to 2 + num_steps = ep['actions'].shape[0] + rewards = np.linspace(1.0, 2.0, num_steps) + out_data_grp['rewards'][:] = rewards + else: + out_data_grp['rewards'][:] = np.ones_like(out_data_grp['rewards']) * const_reward + demo_counter += 1 + + # copy episode attributes + for key, val in ep.attrs.items(): + out_data_grp.attrs[key] = val + + # copy dataset attributes + for key, val in data.attrs.items(): + if key == 'dataset_id': + out_data.attrs[key] = str(uuid.uuid4()) + else: + out_data.attrs[key] = val + + # recreate the train-validation split + split_train_val_from_hdf5(hdf5_path=output_path, val_ratio=0.1) + +if __name__ == "__main__": + relabel_dataset_rewards() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/data_manager/sam_segmentation.py b/code_src/rise_code/sim_pipeline/data_manager/sam_segmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..9c9f2170a014ae23522d97db65ff01c35dde6521 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_manager/sam_segmentation.py @@ -0,0 +1,828 @@ +import h5py +import numpy as np +import cv2 +import torch +import matplotlib.pyplot as plt +from matplotlib.widgets import Button +from segment_anything import sam_model_registry, SamPredictor +from ultralytics.trackers.byte_tracker import BYTETracker +from dataclasses import dataclass +import argparse +import os +import click +import glob +import re +from pathlib import Path + +from tqdm import tqdm + +class SAMObjectSegmentationTracker: + def __init__(self, hdf5_path, sam_checkpoint, image_key='front_image', model_type="vit_h", device="cuda", + save_visualization=True, start_index=0, collect_all_inputs_first=False, + high_res_dir=None, camera_name='front_rgb'): + """ + Initialize the SAM-based object segmentation and tracking system. + + Args: + hdf5_path: Path to the HDF5 dataset + sam_checkpoint: Path to the SAM model checkpoint + model_type: SAM model type (default: vit_h) + device: Device to run the model on (default: cuda) + save_visualization: Whether to save visualization (default: True) + start_index: Index to start from (default: 0) + collect_all_inputs_first: Whether to collect all inputs first, then process all demos (default: False) + high_res_dir: Directory containing high-resolution images (default: None) + camera_name: Camera name in the high-resolution directory (default: front_rgb) + """ + self.hdf5_path = hdf5_path + self.device = device + + # Initialize SAM + sam = sam_model_registry[model_type](checkpoint=sam_checkpoint) + sam.to(device=device) + self.predictor = SamPredictor(sam) + + @dataclass + class BYTETrackerArgs: + track_low_thresh: float = 0.4 + track_high_thresh: float = 0.8 + new_track_thresh: float = 0.8 + fuse_score: bool = False + track_buffer: int = 30 + match_thresh: float = 0.8 + + # Initialize object tracker + self.tracker = BYTETracker( + args=BYTETrackerArgs(), + frame_rate=30 + ) + + self.image_key = image_key + self.save_visualization = save_visualization + self.start_index = start_index + self.collect_all_inputs_first = collect_all_inputs_first + + # High-resolution directory and camera name + self.high_res_dir = high_res_dir + self.camera_name = camera_name + + # Storage for clicked points and masks + self.points = [] + self.point_markers = [] # Store references to point markers for removal + self.point_labels = [] # Store references to point labels for removal + self.masks = {} # Resized masks for storage (or original if not high-res) + self.tracking_masks = {} # High-res masks for tracking (same as masks if not high-res) + self.current_demo = None + self.current_frame = None + self.output_dir = None + self.dataset = None + # New storage for points per demo + self.demo_points = {} + + # Cache for high-res demo paths + self.high_res_demo_paths = None + + def __enter__(self): + """Open the HDF5 file when entering the context.""" + self.dataset = h5py.File(self.hdf5_path, 'r+') + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + """Close the HDF5 file when exiting the context.""" + if self.dataset is not None: + self.dataset.close() + self.dataset = None + + def get_high_res_demo_paths(self): + """ + Get list of high-resolution demo paths in alphanumerical order. + + Returns: + List of paths to high-resolution demo directories, in alphanumerical order + """ + if self.high_res_demo_paths is not None: + return self.high_res_demo_paths + + if not self.high_res_dir: + return [] + + # Get all demo directories in alphanumerical order (demo_10 comes after demo_1 but before demo_2) + demo_dirs = sorted(glob.glob(os.path.join(self.high_res_dir, "demo_*")), + key=lambda x: [int(c) if c.isdigit() else c for c in re.findall(r'[^0-9]|[0-9]+', os.path.basename(x))]) + self.high_res_demo_paths = demo_dirs + return self.high_res_demo_paths + + def get_high_res_image_path(self, demo_idx, frame_idx): + """ + Get the path to the high-resolution image for the given demo index and frame. + + Args: + demo_idx: The demo index (0-based) from the HDF5 file + frame_idx: The frame index + + Returns: + Path to the high-resolution image + """ + if not self.high_res_dir: + return None + + # Get demo paths in alphanumerical order + demo_paths = self.get_high_res_demo_paths() + + # Check if demo index is valid + if demo_idx >= len(demo_paths): + return None + + # Get the demo directory + demo_dir = demo_paths[demo_idx] + + # Format the image file name + image_file = f"image_{frame_idx+1:04d}.jpg" + + # Construct the full path + image_path = os.path.join(demo_dir, self.camera_name, image_file) + + if os.path.exists(image_path): + return image_path + + # If the path doesn't exist, return None + return None + + def load_image(self, demo_key, frame_idx): + """ + Load the image for the given demo and frame, preferring high-resolution if available. + + Args: + demo_key: The demo key + frame_idx: The frame index + + Returns: + The loaded image and a flag indicating if it's high resolution + """ + # Get the demo index in the HDF5 file + demo_keys = list(self.dataset['data'].keys()) + + # Sort by numerical part of the demo key + def get_demo_number(key): + match = re.search(r'demo_(\d+)', key) + return int(match.group(1)) if match else 0 + + demo_idx = get_demo_number(demo_key) + + # Try to load high-resolution image first + high_res_path = self.get_high_res_image_path(demo_idx, frame_idx) + + if high_res_path and os.path.exists(high_res_path): + print(f"Loading high-resolution image from {high_res_path}") + # Load high-resolution image + image = cv2.imread(high_res_path) + image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) + return image, True + + # Fall back to HDF5 image + image = self.dataset['data'][demo_key]['obs'][self.image_key][frame_idx] + + # Ensure image is in correct format + if image.shape[-1] != 3: # Check if channels are not last dimension + image = np.transpose(image, (1, 2, 0)) + + return image, False + + def process_dataset(self, output_dir="output_masks"): + """ + Process all demos in the dataset. + + Args: + output_dir: Directory to save output masks + """ + self.output_dir = output_dir + os.makedirs(output_dir, exist_ok=True) + + # Get all demo keys and sort them + demo_keys = sorted(self.dataset['data'].keys()) + + # Filter demo keys based on start_index + filtered_demo_keys = [] + for i, demo_key in enumerate(demo_keys): + if i < self.start_index: + continue + filtered_demo_keys.append(demo_key) + + if self.collect_all_inputs_first: + # Two-phase approach: Collect all inputs first, then process all demos + print(f"Phase 1: Collecting user inputs for {len(filtered_demo_keys)} demos...") + self.collect_all_user_inputs(filtered_demo_keys) + + print(f"Phase 2: Processing all demos...") + for i, demo_key in enumerate(filtered_demo_keys): + print(f"Index: {i+self.start_index}, Processing {demo_key}...") + self.process_demo_with_points(demo_key) + else: + # Original approach: Process each demo completely before moving to the next + for i, demo_key in enumerate(filtered_demo_keys): + print(f"Index: {i+self.start_index}, Processing {demo_key}...") + self.process_demo(demo_key) + + def collect_all_user_inputs(self, demo_keys): + """ + Collect user inputs for all demos first. + + Args: + demo_keys: List of demo keys to collect inputs for + """ + for i, demo_key in enumerate(demo_keys): + print(f"Please select points for index {i + self.start_index}, {demo_key}...") + self.collect_points_for_demo(demo_key) + + def collect_points_for_demo(self, demo_key): + """ + Collect points for a single demo. + + Args: + demo_key: Key of the demo to collect points for + """ + self.current_demo = demo_key + + # Get the first frame (try high-res first) + first_frame, is_high_res = self.load_image(demo_key, 0) + self.current_frame = first_frame + + # Reset points for this demo + self.points = [] + self.point_markers = [] + self.point_labels = [] + + # Display UI for user to click on points + self.display_point_selection_ui(first_frame, is_high_res) + + # Store the points for this demo + self.demo_points[demo_key] = { + 'points': self.points.copy(), + 'is_high_res': is_high_res + } + + def process_demo_with_points(self, demo_key): + """ + Process a single demo using previously collected points. + + Args: + demo_key: Key of the demo to process + """ + self.current_demo = demo_key + demo_data = self.dataset['data'][demo_key] + self.tracker.reset() + + # Create output directory for this demo + demo_output_dir = os.path.join(self.output_dir, demo_key) + os.makedirs(demo_output_dir, exist_ok=True) + + # Get the first frame + first_frame, is_high_res = self.load_image(demo_key, 0) + self.current_frame = first_frame + + # Get HDF5 frame dimensions for later rescaling + hdf5_frame_shape = demo_data['obs'][self.image_key][0].shape + if len(hdf5_frame_shape) == 3 and hdf5_frame_shape[0] == 3: # If channels first + hdf5_height, hdf5_width = hdf5_frame_shape[1], hdf5_frame_shape[2] + else: # If channels last + hdf5_height, hdf5_width = hdf5_frame_shape[0], hdf5_frame_shape[1] + + # Reset masks + self.masks = {} + self.tracking_masks = {} + + # Retrieve stored points for this demo + stored_points = self.demo_points[demo_key] + self.points = stored_points['points'] + + # Generate masks for the first frame + self.generate_masks_for_first_frame(hdf5_height, hdf5_width, is_high_res) + + self.all_masks = [] + # Save the first frame masks + if self.save_visualization: + # Always use HDF5 image for visualization + hdf5_image = self.dataset['data'][demo_key]['obs'][self.image_key][0] + if hdf5_image.shape[-1] != 3: # Check if channels are not last dimension + hdf5_image = np.transpose(hdf5_image, (1, 2, 0)) + self.save_mask_vis(0, demo_output_dir, hdf5_image) + self.all_masks.append(self.masks) + + # Process remaining frames + num_frames = len(demo_data['obs'][self.image_key]) + for frame_idx in tqdm(range(1, num_frames), desc=f"Tracking objects in {demo_key}"): + frame, frame_is_high_res = self.load_image(demo_key, frame_idx) + self.track_objects_in_frame(frame, frame_idx, hdf5_height, hdf5_width, frame_is_high_res) + self.all_masks.append(self.masks) + if self.save_visualization: + # Always use HDF5 image for visualization + hdf5_image = self.dataset['data'][demo_key]['obs'][self.image_key][frame_idx] + if hdf5_image.shape[-1] != 3: # Check if channels are not last dimension + hdf5_image = np.transpose(hdf5_image, (1, 2, 0)) + self.save_mask_vis(frame_idx, demo_output_dir, hdf5_image) + + self.save_masks_to_dataset(demo_key, self.all_masks) + + def process_demo(self, demo_key): + """ + Process a single demo with user input. + + Args: + demo_key: Key of the demo to process + """ + self.current_demo = demo_key + demo_data = self.dataset['data'][demo_key] + self.tracker.reset() + + # Create output directory for this demo + demo_output_dir = os.path.join(self.output_dir, demo_key) + os.makedirs(demo_output_dir, exist_ok=True) + + # Get the first frame (try high-res first) + first_frame, is_high_res = self.load_image(demo_key, 0) + self.current_frame = first_frame + + # Get HDF5 frame dimensions for later rescaling + hdf5_frame_shape = demo_data['obs'][self.image_key][0].shape + if len(hdf5_frame_shape) == 3 and hdf5_frame_shape[0] == 3: # If channels first + hdf5_height, hdf5_width = hdf5_frame_shape[1], hdf5_frame_shape[2] + else: # If channels last + hdf5_height, hdf5_width = hdf5_frame_shape[0], hdf5_frame_shape[1] + + # Reset points and masks + self.points = [] + self.point_markers = [] + self.point_labels = [] + self.masks = {} + self.tracking_masks = {} + + # Display UI for user to click on points + self.display_point_selection_ui(first_frame, is_high_res) + + # Generate masks for the first frame + self.generate_masks_for_first_frame(hdf5_height, hdf5_width, is_high_res) + + self.all_masks = [] + # Save the first frame masks + if self.save_visualization: + # Always use HDF5 image for visualization + hdf5_image = self.dataset['data'][demo_key]['obs'][self.image_key][0] + if hdf5_image.shape[-1] != 3: # Check if channels are not last dimension + hdf5_image = np.transpose(hdf5_image, (1, 2, 0)) + self.save_mask_vis(0, demo_output_dir, hdf5_image) + self.all_masks.append(self.masks) + + # Process remaining frames + num_frames = len(demo_data['obs'][self.image_key]) + for frame_idx in tqdm(range(1, num_frames), desc=f"Tracking objects in {demo_key}"): + frame, frame_is_high_res = self.load_image(demo_key, frame_idx) + self.track_objects_in_frame(frame, frame_idx, hdf5_height, hdf5_width, frame_is_high_res) + self.all_masks.append(self.masks) + if self.save_visualization: + # Always use HDF5 image for visualization + hdf5_image = self.dataset['data'][demo_key]['obs'][self.image_key][frame_idx] + if hdf5_image.shape[-1] != 3: # Check if channels are not last dimension + hdf5_image = np.transpose(hdf5_image, (1, 2, 0)) + self.save_mask_vis(frame_idx, demo_output_dir, hdf5_image) + + self.save_masks_to_dataset(demo_key, self.all_masks) + + def display_point_selection_ui(self, frame, is_high_res=False): + """ + Display a UI for the user to click on points of interest in the first frame. + + Args: + frame: The first frame of the demo + is_high_res: Whether this is a high-resolution image + """ + self.fig, self.ax = plt.subplots(figsize=(10, 10)) + self.ax.imshow(frame) + resolution_info = "High Resolution" if is_high_res else "Low Resolution (from HDF5)" + self.ax.set_title(f"Click on objects of interest in {self.current_demo} [{resolution_info}]\nShift+Click to remove a point\nPress 'Done' when finished") + + # Add a button to finish selection + done_ax = plt.axes([0.85, 0.01, 0.1, 0.075]) + self.done_button = Button(done_ax, 'Done') + self.done_button.on_clicked(self.on_done) + + # Connect click event + self.click_connection = self.fig.canvas.mpl_connect('button_press_event', self.on_click) + plt.show() + + def on_click(self, event): + """ + Handle click event in the UI. + + Args: + event: MouseEvent from matplotlib + """ + if event.inaxes == self.ax: + x, y = int(event.xdata), int(event.ydata) + + # Check if shift key is pressed (for removing points) + if event.key == 'shift': + # Find the closest point to remove + if self.points: + distances = [np.sqrt((p[0] - x)**2 + (p[1] - y)**2) for p in self.points] + closest_idx = np.argmin(distances) + + # Only remove if within a reasonable distance (e.g., 20 pixels) + if distances[closest_idx] < 20: + # Remove the point + self.points.pop(closest_idx) + + # Remove the marker and label + if closest_idx < len(self.point_markers): + marker = self.point_markers.pop(closest_idx) + marker.remove() + + if closest_idx < len(self.point_labels): + label = self.point_labels.pop(closest_idx) + label.remove() + + # Redraw remaining points with updated indices + for i, marker in enumerate(self.point_markers): + marker.set_color('red') + + for i, label in enumerate(self.point_labels): + label.set_text(f"{i+1}") + + self.fig.canvas.draw() + else: + # Add a new point + self.points.append([x, y]) + + # Mark the point on the image + marker = self.ax.plot(x, y, 'ro', markersize=10)[0] + label = self.ax.text(x+5, y+5, f"{len(self.points)}", color='white', + bbox=dict(facecolor='red', alpha=0.5)) + + # Store references to the marker and label + self.point_markers.append(marker) + self.point_labels.append(label) + + self.fig.canvas.draw() + + def on_done(self, event): + """ + Handle done button press. + + Args: + event: ButtonEvent from matplotlib + """ + plt.close(self.fig) + + def save_masks_to_dataset(self, demo_key, all_masks): + """ + Save masks to the dataset. + + Args: + demo_key: Key of the demo + all_masks: List of masks to save + """ + # Check if mask group already exists, if so delete it + if 'object_masks' in self.dataset['data'][demo_key]: + del self.dataset['data'][demo_key]['object_masks'] + + # Create the mask group + mask_group = self.dataset['data'][demo_key].create_group('object_masks') + + for frame_idx, masks in enumerate(all_masks): + # Check if frame group already exists, if so delete it + frame_group_name = f'frame_{frame_idx}' + if frame_group_name in mask_group: + del mask_group[frame_group_name] + + # Create new group for this frame + frame_group = mask_group.create_group(frame_group_name) + + for mask_id, mask in masks.items(): + # Check if mask already exists, if so delete it + mask_name = f'mask_{mask_id}' + if mask_name in frame_group: + del frame_group[mask_name] + + # Save mask + frame_group.create_dataset(mask_name, data=mask) + + def resize_mask(self, mask, target_height, target_width): + """ + Resize a mask to target dimensions. + + Args: + mask: Binary mask to resize + target_height: Target height + target_width: Target width + + Returns: + Resized binary mask + """ + resized_mask = cv2.resize( + mask.astype(np.uint8), + (target_width, target_height), + interpolation=cv2.INTER_AREA + ) + return resized_mask.astype(bool) + + def generate_masks_for_first_frame(self, hdf5_height=None, hdf5_width=None, is_high_res=False): + """ + Generate masks for all clicked points in the first frame using SAM. + + Args: + hdf5_height: Height of frames in HDF5 + hdf5_width: Width of frames in HDF5 + is_high_res: Whether the current frame is high resolution + """ + if not self.points: + print("No points selected. Please select at least one point.") + return + + # Set the image in the predictor + self.predictor.set_image(self.current_frame) + + # Generate masks for each point + for i, point in enumerate(self.points): + input_point = np.array([point]) + input_label = np.array([1]) # 1 indicates foreground + + # Generate mask + masks, scores, logits = self.predictor.predict( + point_coords=input_point, + point_labels=input_label, + multimask_output=True + ) + + # Select the mask with the highest score + best_mask_idx = np.argmax(scores) + mask = masks[best_mask_idx] + + # Store the original mask for tracking + self.tracking_masks[i+1] = mask.copy() + + # If using high-res images, resize the mask to match HDF5 dimensions for storage + if is_high_res and hdf5_height is not None and hdf5_width is not None: + mask = self.resize_mask(mask, hdf5_height, hdf5_width) + + # Store the mask with an ID (resized or original for storage) + self.masks[i+1] = mask # ID starts from 1 + + print(f"Generated mask for point {i+1} with confidence {scores[best_mask_idx]:.4f}") + + def track_objects_in_frame(self, frame, frame_idx, hdf5_height=None, hdf5_width=None, is_high_res=False): + """ + Track objects from previous frame to current frame. + + Args: + frame: Current frame + frame_idx: Index of the current frame + hdf5_height: Height of frames in HDF5 + hdf5_width: Width of frames in HDF5 + is_high_res: Whether the current frame is high resolution + """ + if not self.masks: + print("No masks to track. Please generate masks for the first frame first.") + return + + # Set the image in the predictor + self.predictor.set_image(frame) + + # Convert masks to detections for tracking + # For BYTETracker, we need to format detections as results object with xywh, conf, and cls + bboxes = [] + scores = [] + cls = [] + mask_ids = [] + + # Use tracking_masks for computing bounding boxes if high-res, otherwise use masks + tracking_masks = self.tracking_masks if is_high_res else self.masks + + for mask_id, mask in tracking_masks.items(): + # Find contours of the mask + contours, _ = cv2.findContours( + mask.astype(np.uint8), + cv2.RETR_EXTERNAL, + cv2.CHAIN_APPROX_SIMPLE + ) + + if contours: + # Get the largest contour + largest_contour = max(contours, key=cv2.contourArea) + x, y, w, h = cv2.boundingRect(largest_contour) + + # Store in xywh format (center_x, center_y, width, height) + cx = x + w/2 + cy = y + h/2 + bboxes.append([cx, cy, w, h]) + + # Calculate confidence (placeholder, can be improved) + scores.append(0.9) + + # Store class (all objects are the same class in this case) + cls.append(0) + + # Store mask_id for reference + mask_ids.append(mask_id) + + if bboxes: + # Create a Results-like object for BYTETracker + class Results: + pass + + results = Results() + results.xywh = np.array(bboxes) + results.conf = np.array(scores) + results.cls = np.array(cls) + + # Track objects + tracks = self.tracker.update(results, frame) + + # Update masks based on tracking results + new_masks = {} # For storage (resized if high-res) + new_tracking_masks = {} # For tracking (original high-res) + + # Create a mapping from track_id to original mask_id + # This is necessary because BYTETracker may assign different track_ids + track_to_mask_map = {} + + # We need to match the tracks back to our original mask_ids + # Use IOU matching to find the best correspondences + for i, track in enumerate(tracks): + if len(track) >= 4: # Make sure we have at least x, y, w, h + # Extract the bbox from the track result + t_left, t_top, t_right, t_bottom = track[:4] + + # This track's box as [left, top, right, bottom] + track_box = [t_left, t_top, t_right, t_bottom] + + # Find the best matching mask_id based on IOU + best_iou = 0 + best_mask_id = None + + for j, mask_id in enumerate(mask_ids): + # Original box + x, y, w, h = bboxes[j] + left, top = x - w/2, y - h/2 + right, bottom = x + w/2, y + h/2 + + # Calculate IOU + x_left = max(left, track_box[0]) + y_top = max(top, track_box[1]) + x_right = min(right, track_box[2]) + y_bottom = min(bottom, track_box[3]) + + if x_right < x_left or y_bottom < y_top: + continue + + intersection = (x_right - x_left) * (y_bottom - y_top) + box1_area = (right - left) * (bottom - top) + box2_area = (track_box[2] - track_box[0]) * (track_box[3] - track_box[1]) + union = box1_area + box2_area - intersection + + iou = intersection / union if union > 0 else 0 + + if iou > best_iou: + best_iou = iou + best_mask_id = mask_id + + if best_mask_id is not None and best_iou > 0.3: # IOU threshold + track_to_mask_map[i] = best_mask_id + + # Now generate new masks based on the tracks + for i, track in enumerate(tracks): + if i in track_to_mask_map: + mask_id = track_to_mask_map[i] + + # Get the previous mask's area (from tracking masks) + prev_mask = tracking_masks[mask_id] + prev_area = np.sum(prev_mask) + + # Extract bbox from track result + box = track[:4] # [left, top, right, bottom] + + # Calculate a point in the center of the box + center_x = (box[0] + box[2]) / 2 + center_y = (box[1] + box[3]) / 2 + + # Generate a new mask + input_point = np.array([[center_x, center_y]]) + input_label = np.array([1]) + + masks, scores, logits = self.predictor.predict( + point_coords=input_point, + point_labels=input_label, + multimask_output=True, + box=np.array([box[0], box[1], box[2], box[3]]) # Provide box constraint + ) + + # Find the mask that's closest in area to the previous mask + best_mask_idx = 0 + best_area_diff = float('inf') + + for idx, mask in enumerate(masks): + current_area = np.sum(mask) + area_diff = abs(current_area - prev_area) / prev_area # Relative difference + + if area_diff < best_area_diff: + best_area_diff = area_diff + best_mask_idx = idx + + # Only use the new mask if it's not too different in size + new_mask = masks[best_mask_idx] + new_area = np.sum(new_mask) + area_ratio = new_area / prev_area + + # Always keep the high-res mask for tracking + new_tracking_mask = new_mask.copy() + + # If using high-res images, resize the mask to match HDF5 dimensions for storage + if is_high_res and hdf5_height is not None and hdf5_width is not None: + new_mask = self.resize_mask(new_mask, hdf5_height, hdf5_width) + # Recalculate area ratio for the storage decision, using original areas + storage_area = np.sum(new_mask) + storage_area_ratio = storage_area / np.sum(self.masks[mask_id]) + else: + storage_area_ratio = area_ratio + + # Allow the mask to be between 0.5x and 2x the previous size + if 0.5 <= area_ratio <= 2.0: + new_tracking_masks[mask_id] = new_tracking_mask + new_masks[mask_id] = new_mask + else: + # If the new mask is too different, keep the previous masks + new_tracking_masks[mask_id] = tracking_masks[mask_id] + new_masks[mask_id] = self.masks[mask_id] + + # Update masks + self.tracking_masks = new_tracking_masks + self.masks = new_masks + + def save_mask_vis(self, frame_idx, output_dir, orig_image, mask_alpha=0.5): + """ + Save masks for the current frame. + + Args: + frame_idx: Index of the current frame + output_dir: Directory to save masks + orig_image: Original image (from HDF5) + mask_alpha: Alpha value for mask transparency + """ + # Save a visualization of all masks + if self.masks: + first_mask = next(iter(self.masks.values())) + + colored_mask = np.zeros((*first_mask.shape, 4), dtype=np.float32) + + # Generate unique colors for each mask ID + num_masks = len(self.masks) + # Use a colormap to generate distinct colors + cmap = plt.get_cmap('hsv', num_masks + 1) + + for i, (mask_id, mask) in enumerate(self.masks.items()): + # Get a unique color from the colormap + color = cmap(i) + # Set alpha value + mask_color = (color[0], color[1], color[2], mask_alpha) + colored_mask[mask] = mask_color + + # Save combined mask + combined_path = os.path.join(output_dir, f"combined_mask_{frame_idx:04d}.png") + plt.figure(figsize=(10, 10)) + plt.imshow(orig_image) + plt.imshow(colored_mask) + plt.title(f"Segmentation Masks - Frame {frame_idx}") + plt.savefig(combined_path) + plt.close() + + +def main(): + @click.command() + @click.option("--dataset", required=True, help="Path to HDF5 dataset") + @click.option("--sam-checkpoint", required=True, help="Path to SAM checkpoint") + @click.option("--model-type", default="vit_b", help="SAM model type") + @click.option("--device", default="cuda", help="Device to run on") + @click.option("--save-visualization", default=True, help="Save visualization") + @click.option("--output-dir", default="output_masks", help="Output directory for vis") + @click.option("--image-key", default="front_image", help="Image key") + @click.option("--start-index", default=0, help="Start index") + @click.option("--collect-all-inputs-first", '-c',is_flag=True, help="Collect all user inputs first, then process all demos") + @click.option("--high-res-dir", help="Directory containing high-resolution images") + @click.option("--camera-name", default="front_rgb", help="Camera name in high-resolution directory") + def run(dataset, sam_checkpoint, model_type, device, output_dir, save_visualization, image_key, start_index, collect_all_inputs_first, high_res_dir, camera_name): + with SAMObjectSegmentationTracker( + hdf5_path=dataset, + sam_checkpoint=sam_checkpoint, + image_key=image_key, + model_type=model_type, + device=device, + save_visualization=save_visualization, + start_index=start_index, + collect_all_inputs_first=collect_all_inputs_first, + high_res_dir=high_res_dir, + camera_name=camera_name + ) as tracker: + tracker.process_dataset(output_dir) + + run() + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/data_manager/truncate_dataset.py b/code_src/rise_code/sim_pipeline/data_manager/truncate_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..576d93cd9b4becbc18cfb193f954d51139ac7257 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/data_manager/truncate_dataset.py @@ -0,0 +1,84 @@ +import click +import os +import h5py +import uuid +import numpy as np +from tqdm import tqdm + +from robomimic.scripts.split_train_val import split_train_val_from_hdf5 + +@click.command() +@click.option('--dataset', '-d', help='Dataset file path') +@click.option('--output_name', '-o', help='Output file name') +@click.option('--proportion', '-p', type=click.FloatRange(0, 1), help='Proportion of dataset to keep', default=1.0) +@click.option('--amount', '-n', type=click.IntRange(0), help='Number of steps to remove from the start of each demo', default=None) +def truncate_dataset(dataset, output_name, proportion, amount): + print(f'Truncating dataset {dataset}') + if proportion == 0: + raise ValueError("No demos to keep") + # output file in same directory as input file + output_path = os.path.join(os.path.dirname(dataset), output_name) + + with ( + h5py.File(dataset, 'r') as f, + h5py.File(output_path, 'w') as f_filtered + ): + data = f['data'] + out_data = f_filtered.create_group("data") + + num_demos = len(data.keys()) + demos_to_keep = int(num_demos * proportion) + new_demos = [] + new_total = 0 + demo_counter = 0 + + for ep_key in tqdm(data, desc="Processing demos", total=demos_to_keep): + if demo_counter >= demos_to_keep: + break + ep = data[ep_key] + new_demos.append(ep_key) + + # Determine the number of steps to keep + num_steps = ep['actions'].shape[0] + steps_to_keep = max(0, num_steps - (amount if amount is not None else 0)) + start_index = amount if amount is not None else 0 + new_total += steps_to_keep + + # Create a new group for the truncated demo + out_data_grp = out_data.create_group(f'demo_{demo_counter}') + + # Copy truncated data + for key in ep.keys(): + if isinstance(ep[key], h5py.Dataset): + out_data_grp.create_dataset( + key, + data=ep[key][start_index:num_steps] + ) + else: + ep.copy(key, out_data_grp) + + # Copy and update episode attributes + for key, val in ep.attrs.items(): + if key == 'num_samples': + out_data_grp.attrs[key] = steps_to_keep + else: + out_data_grp.attrs[key] = val + + demo_counter += 1 + + # Copy dataset attributes + for key, val in data.attrs.items(): + if key == 'total': + out_data.attrs[key] = new_total + elif key == 'dataset_id': + out_data.attrs[key] = str(uuid.uuid4()) + elif key == 'description': + out_data.attrs[key] = val + f' truncated w/ {demos_to_keep} demos' + else: + out_data.attrs[key] = val + + # Recreate the train-validation split + split_train_val_from_hdf5(hdf5_path=output_path, val_ratio=0.1) + +if __name__ == "__main__": + truncate_dataset() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/envs/__init__.py b/code_src/rise_code/sim_pipeline/envs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code_src/rise_code/sim_pipeline/envs/initialization_wrapper.py b/code_src/rise_code/sim_pipeline/envs/initialization_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..0506789ecccf9d25963f0ed2bdb3e455cb9e54bc --- /dev/null +++ b/code_src/rise_code/sim_pipeline/envs/initialization_wrapper.py @@ -0,0 +1,76 @@ +import numpy as np +from copy import deepcopy +from robosuite.robots.single_arm import SingleArm +from robosuite.environments.robot_env import RobotEnv + +class InitializationWrapper: + def __init__(self, env: RobotEnv, init_ee_range, seed=None): + assert isinstance(env, RobotEnv) + + self.env = env + self.init_ee_range: list[list[float]] = init_ee_range + + if seed is None: + seed = np.random.randint(0, 1000) + np.random.seed(seed) + + def __getattr__(self, name): + return getattr(self.env, name) + + def reset(self): + self.env.reset() + + ### initialization: move to random ee position within range + + # randomly sample target ee pos + target_ee_pos = np.array([np.random.uniform(self.init_ee_range[0][0], self.init_ee_range[0][1]), + np.random.uniform(self.init_ee_range[1][0], self.init_ee_range[1][1]), + np.random.uniform(self.init_ee_range[2][0], self.init_ee_range[2][1])]) + + curr_action_dim = self.env.action_dim + self.env._action_dim = 4 + + # switch to absolute ee pos controller + + # TODO support multiple robots + robots: list[SingleArm] = self.env.robots + for robot in robots: + curr_controller = robot.controller + + robot._load_controller() + abs_controller = robot.controller + abs_controller.use_delta = False + abs_controller.use_ori = False + abs_controller.control_dim = 3 + abs_controller.input_max = abs_controller.input_max[:abs_controller.control_dim] + abs_controller.input_min = abs_controller.input_min[:abs_controller.control_dim] + abs_controller.output_max = abs_controller.output_max[:abs_controller.control_dim] + abs_controller.output_min = abs_controller.output_min[:abs_controller.control_dim] + + robot.controller.reset_goal() + + # obtained from running robosuite + starting_z = 1.011049 + + # to ensure robot does not collide with objects, execute xy movement before z movement + xy_goal = target_ee_pos[:2] + + # TODO automatically determine when done + num_steps = 25 + for i in range(num_steps): + action = np.r_[xy_goal, starting_z, 0.0] + obs, reward, done, info = self.env.step(action) + # print(obs['robot0_eef_pos'], action) # # randomly sample target ee pos + + action = np.r_[target_ee_pos, 0.0] + obs, reward, done, info = self.env.step(action) + # print(obs['robot0_eef_pos'], action) + + # reset controller + robot.controller = curr_controller + robot.controller.reset_goal() + self.env._action_dim = curr_action_dim + + self.env.timestep = 0 + + return self.env._get_observations(force_update=True) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/envs/make_env.py b/code_src/rise_code/sim_pipeline/envs/make_env.py new file mode 100644 index 0000000000000000000000000000000000000000..962f872c2845f515a2ac66cc2c75a81614d5ff90 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/envs/make_env.py @@ -0,0 +1,316 @@ +from functools import partial +from omegaconf import OmegaConf +from stable_baselines3.common.vec_env import DummyVecEnv, SubprocVecEnv + +from diffusion_policy.gym_util.async_vector_env import AsyncVectorEnv +from diffusion_policy.gym_util.sync_vector_env import SyncVectorEnv + +from sim_pipeline.reward_wrapper import RewardWrapper as FrankaRewardWrapper +from sim_pipeline.configs.env.base import BaseEnvConfig +from sim_pipeline.configs.env.robomimic_base import RobomimicEnvConfig +from sim_pipeline.configs.env.franka_base import EnvConfigFranka +from sim_pipeline.configs.robot.base_franka import RobotConfigFranka +from sim_pipeline.configs.constants import EnvType, RobomimicEnvType +from sim_pipeline.data_manager.dataset_metadata_enums import ObsType +from sim_pipeline.envs.reward_wrapper import RewardWrapper + +def make_vec_env( + env_config: BaseEnvConfig, + num_workers=1, + seed=0, + device_id=0, + debug=False, + flatten_obs=True, + gymnasium_api=True, + use_gym_vec_env=False, + mp_context: str | None = None, + obs_modality_specs=None, +): + if debug: + vec_env = SyncVectorEnv if use_gym_vec_env else DummyVecEnv + num_workers = 1 + else: + vec_env = AsyncVectorEnv if use_gym_vec_env else SubprocVecEnv + if env_config.env_type == EnvType.POINT_MAZE: + return vec_env([make_maze_env(env_config, seed) for _ in range(num_workers)]) + elif env_config.env_type == EnvType.FRANKA: + from weird_franka.robot.sim.vec_env.vec_wrapper import SubVecEnv + + env_fns = [ + partial( + make_franka_env, + env_config.robot_config, + env_config, + seed=seed + i, + device_id=device_id + ) + for i in range(num_workers) + ] + return SubVecEnv(env_fns) + elif env_config.env_type == EnvType.ROBOMIMIC: + if vec_env == AsyncVectorEnv: + return vec_env([ + make_robomimic_env( + env_config, + seed + i, + device_id, + flatten_obs=flatten_obs, + gymnasium_api=gymnasium_api, + obs_modality_specs=obs_modality_specs, + ) for i in range(num_workers) + ], + context=mp_context + ) + return vec_env([ + make_robomimic_env( + env_config, + seed + i, + device_id, + flatten_obs=flatten_obs, + gymnasium_api=gymnasium_api, + obs_modality_specs=obs_modality_specs, + ) for i in range(num_workers) + ]) + +def make_env( + env_config: BaseEnvConfig, + seed=0, + device_id=0, + flatten_obs=True, + gymnasium_api=True, +): + if env_config.env_type == EnvType.POINT_MAZE: + return make_maze_env(env_config, seed)() + elif env_config.env_type == EnvType.FRANKA: + return make_franka_env(env_config.robot_config, env_config, seed, device_id) + elif env_config.env_type == EnvType.ROBOMIMIC: + if env_config.data_collection: + return make_robosuite_env(env_config, seed, device_id)() + return make_robomimic_env(env_config, seed, device_id, flatten_obs=flatten_obs, gymnasium_api=gymnasium_api)() + +def make_robomimic_env( + env_config: RobomimicEnvConfig, + seed=0, + device_id=0, + flatten_obs=True, + gymnasium_api=True, + obs_modality_specs=None, +): + from sim_pipeline.envs.robosuite_wrapper import RobomimicObsWrapper + from sim_pipeline.envs.initialization_wrapper import InitializationWrapper + + obs_type: ObsType = env_config.obs_type + use_image_obs = obs_type.includes_image_obs() + use_depth_obs = obs_type.includes_depth_obs() + + env_kwargs = { + 'has_offscreen_renderer': env_config.render_offscreen, + 'use_object_obs': True, + 'use_camera_obs': use_image_obs, + 'controller_configs': {'type': 'OSC_POSE', 'input_max': 1, 'input_min': -1, 'output_max': [0.05, 0.05, 0.05, 0.5, 0.5, 0.5], 'output_min': [-0.05, -0.05, -0.05, -0.5, -0.5, -0.5], 'kp': 150, 'damping': 1, 'impedance_mode': 'fixed', 'kp_limits': [0, 300], 'damping_limits': [0, 10], 'position_limits': None, 'orientation_limits': None, 'uncouple_pos_ori': True, 'control_delta': True, 'interpolation': None, 'ramp_ratio': 0.2}, + 'robots': ['Panda'], + 'camera_heights': 84, + 'camera_widths': 84, + 'reward_shaping': True, + 'render_gpu_device_id': device_id, + 'horizon': env_config.horizon, + 'camera_names': OmegaConf.to_container(env_config.camera_names), + } + + # rsm_rise 23:35 UTC (stream A): RR_EVAL_HARD_RESET=0 asks robosuite to reuse ONE MjSim and ONE offscreen + # render context for the whole run instead of destroying and re-creating them on every reset + # (robosuite/environments/base.py:247, `if self.hard_reset and not self.deterministic_reset`). That churn is + # the prime suspect for the DEGENERATE eval mode documented in status/A_env_stage0.md (23:10): ~20-30 % of + # eval processes abort inside mjr_readPixels at the FIRST render AFTER the FIRST reset, i.e. on the first + # re-created context, and then do exactly one episode per process forever. Object/robot randomisation does + # NOT depend on hard_reset -- _reset_internal() re-samples the placement initializer and applies it with + # set_joint_qpos either way -- so the initial-state distribution is unchanged. DEFAULT IS UNCHANGED (True); + # only set this for the A/B, never silently for a table row. + import os as _os + if _os.environ.get('RR_EVAL_HARD_RESET') == '0': + env_kwargs['hard_reset'] = False + print('[rsm_rise] env: hard_reset=False (RR_EVAL_HARD_RESET=0) -- one sim + one render context reused') + + if env_config.custom_obj_init: + env_kwargs['placement_initializer'] = _get_init_randomizers(env_config) + env_kwargs['initialization_noise'] = None + + def _init(): + env = RobomimicObsWrapper( + env_name=env_config.env_name.value, + render=env_config.render, + render_offscreen=env_config.render_offscreen, + use_image_obs=use_image_obs, + use_depth_obs=use_depth_obs, + flatten_obs=flatten_obs, + env_config=env_config, + gymnasium_api=gymnasium_api, + obs_modality_specs=obs_modality_specs, + seed=seed, + **env_kwargs, + ) + + if env_config.custom_ee_init: + robosuite = env.env + init_wrapped_env = InitializationWrapper(robosuite, env_config.init_ee_range, seed=seed) + env.env = init_wrapped_env + + if env_config.reward_function is not None: + env = RewardWrapper( + env, + env_config.reward_function.get_function(), + success_func=env_config.success_function.get_function(), + gymnasium_api=gymnasium_api + ) + + return env + return _init + +def make_robosuite_env( + env_config: RobomimicEnvConfig, + seed=0, + device_id=0 +): + import robosuite as suite + from robosuite import load_controller_config + from sim_pipeline.envs.initialization_wrapper import InitializationWrapper + + controller_config = load_controller_config(default_controller='OSC_POSE') + # Create argument configuration + config = { + "env_name": env_config.env_name.value, + "robots": ['Panda'], + "controller_configs": controller_config, + } + + if env_config.custom_obj_init: + config['placement_initializer'] = _get_init_randomizers(env_config) + config['initialization_noise'] = None + + camera_names = OmegaConf.to_container(env_config.camera_names) + + def _init(): + # Create environment + env = suite.make( + **config, + has_renderer=env_config.render, + has_offscreen_renderer=env_config.render_offscreen, + render_camera='agentview', + ignore_done=env_config.ignore_done, + use_camera_obs=env_config.render_offscreen, + reward_shaping=True, + control_freq=20, + camera_names=camera_names, + camera_heights=84, + camera_widths=84, + ) + if env_config.custom_ee_init: + env = InitializationWrapper(env, env_config.init_ee_range, seed=seed) + + if env_config.reward_function is not None: + env = RewardWrapper( + env, + env_config.reward_function.get_function(), + success_func=env_config.success_function.get_function(), + gymnasium_api=False + ) + + return env + return _init + + +def _get_init_randomizers(env_config: RobomimicEnvConfig): + from robosuite.utils.placement_samplers import UniformRandomSampler, SequentialCompositeSampler + + placement_initializer = SequentialCompositeSampler(name='ObjectSampler') + obj_names = env_config.env_name.get_object_names() + + + if env_config.env_name in [RobomimicEnvType.NUT_ASSEMBLY_SQUARE, RobomimicEnvType.NUT_ASSEMBLY_ROUND, RobomimicEnvType.TOOL_HANG]: + ensure_valid_placement = False + else: + ensure_valid_placement = True + + # NOTE: Change the rotation_axis to z (to be flat), tip, short_base, or long_base to initialize peg differently + for obj_name in obj_names: + + if env_config.env_name == RobomimicEnvType.TOOL_HANG and obj_name == 'frameObject': + rotation_axis = 'y' + else: + rotation_axis = 'z' + # rsm_rise: optional per-object overrides from the env config + _axes = getattr(env_config, 'init_obj_rotation_axis', None) or {} + if obj_name in _axes: + rotation_axis = str(_axes[obj_name]) + + if env_config.env_name == RobomimicEnvType.TOOL_HANG: + z_offset = 0.001 + else: + z_offset = 0.02 + _zoff = getattr(env_config, 'init_obj_z_offset', None) or {} + if obj_name in _zoff: + z_offset = float(_zoff[obj_name]) + + try: + init_range = env_config.init_obj_range[obj_name] + except KeyError: + init_range = env_config.env_name.get_default_obj_init_ranges()[obj_name] + try: + rotation_range = init_range[2] + except IndexError: + rotation_range = None + sampler = UniformRandomSampler( + name=f'{obj_name}Sampler', + x_range=init_range[0], + y_range=init_range[1], + ensure_object_boundary_in_range=False, + rotation=rotation_range, + rotation_axis=rotation_axis, + # to avoid overlapping with the round nut (which doesn't exist here) + ensure_valid_placement=ensure_valid_placement, + reference_pos=env_config.env_name.get_surface_ref_pos(), + z_offset=z_offset + ) + + placement_initializer.append_sampler(sampler) + + return placement_initializer + +def make_franka_env( + robot_config: RobotConfigFranka = None, + env_config: EnvConfigFranka = None, + seed=0, + device_id=0 +): + from weird_franka.robot.robot_env import RobotEnv + from weird_franka.robot.sim.mujoco.obj_wrapper import ObjWrapper + + robot_config.model_name = robot_config.model_name.replace( + "base", env_config.obj_id + ) + env = RobotEnv(**robot_config, device_id=device_id) + env = ObjWrapper(env, **env_config) + env = FrankaRewardWrapper(env, **env_config) + + env.seed(seed) + + return env + +def make_maze_env( + env_config: EnvConfigFranka, + seed=0 +): + from .point_maze.point_maze import PointMazeEnv + from .point_maze.ood_maze_envs import MazeType + # print(f'Creating environment for {maze_id} maze ...') + def _init(): + env = PointMazeEnv( + maze_map=MazeType(env_config.maze_id).to_map(), + render_mode=env_config.render_mode, + continuing_task=False, + max_episode_steps=env_config.max_ep_steps, + reward_type=env_config.reward_type + ) + env.reset(seed=seed) + return env + return _init \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/envs/reward_wrapper.py b/code_src/rise_code/sim_pipeline/envs/reward_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..386cf6528b4a5b80c2a09f0f4147e288a7696305 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/envs/reward_wrapper.py @@ -0,0 +1,45 @@ +from typing import Any +import gymnasium as gym + +class RewardWrapper(gym.Env): + def __init__(self, env, reward_func=None, success_func=None, gymnasium_api=True): + self.env = env + self.reward_func = reward_func if reward_func else self.default_reward + self.success_func = success_func if success_func else self.default_success + self.gymnasium_api = gymnasium_api + + def __getattribute__(self, name: str) -> Any: + """ + Ignores subclass methods. Needed to avoid SB3's requirement of needing to inherit from gym.Env + """ + instance_dict = object.__getattribute__(self, '__dict__') + if name in RewardWrapper.__dict__ or name in instance_dict: + return object.__getattribute__(self, name) + + env = object.__getattribute__(self, 'env') + return getattr(env, name) + + def step(self, action): + step_results = self.env.step(action) + try: + obs, reward, done, info = step_results + truncated = False + except ValueError: + obs, reward, done, truncated, info = step_results + if self.gymnasium_api: + return obs, self.reward_func(obs, action, self.env), done, truncated, info + return obs, self.reward_func(obs, action, self.env), done, info + + def get_success(self): + obs = self.env.get_observation() + return self.success_func(obs, self.env) + + def get_reward(self): + obs = self.env.get_observation() + return self.reward_func(obs, None, self.env) + + def default_reward(self, obs, act, env): + return 0.0 + + def default_success(self, obs, env): + return self.env.get_success() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/envs/robosuite_wrapper.py b/code_src/rise_code/sim_pipeline/envs/robosuite_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..185af6bf2d45f498840b4074520f50fe8de4e34e --- /dev/null +++ b/code_src/rise_code/sim_pipeline/envs/robosuite_wrapper.py @@ -0,0 +1,128 @@ +import gymnasium as gym +# needed b/c diffusion policy uses orig gym +import gym as og_gym +import numpy as np +import robomimic.utils.obs_utils as ObsUtils + +from sim_pipeline.configs.env.robomimic_base import RobomimicEnvConfig +from sim_pipeline.utils.obs_dict_tools import flatten_obs_dict +from robomimic.envs.env_robosuite import EnvRobosuite + +class RobomimicObsWrapper(EnvRobosuite, gym.Env): + def __init__(self, *args, env_config=None, flatten_obs=True, gymnasium_api=True, obs_modality_specs=None, seed=None, **kwargs): + super().__init__(*args, **kwargs) + + self.env_config: RobomimicEnvConfig = env_config + if seed: + np.random.seed(seed) + + self.flatten_obs = flatten_obs + self.gymnasium_api = gymnasium_api + + # we store this value in the class rather than robomimic's global var + # due to multiprocessing + self.obs_modality_specs = obs_modality_specs + if self.obs_modality_specs is not None: + ObsUtils.initialize_obs_utils_with_obs_specs(self.obs_modality_specs) + + if self.env.has_offscreen_renderer and not self.env.has_renderer: + self.render_mode = 'rgb_array' + elif self.env.has_renderer: + self.render_mode = 'human' + + # this is auto set as True in robomimic + self.env.ignore_done = env_config.ignore_done + + #TODO hardcoded action dim, can pull from bc dataset perhaps + if self.flatten_obs: + self.action_space = gym.spaces.Box(low=-1, high=1, shape=(7,), dtype=np.float32) + obs = self.get_observation() + self.observation_space = gym.spaces.Box(low=-np.inf, high=np.inf, shape=obs.shape, dtype=np.float32) + elif self.obs_modality_specs is not None: + observation_space = og_gym.spaces.Dict() + obs = self.get_observation() + for key, value in obs.items(): + if key.endswith('image'): + low = 0.0 + high = 1.0 + else: + low = -1.0 + high = 1.0 + observation_space[key] = og_gym.spaces.Box(low=low, high=high, shape=value.shape, dtype=np.float32) + self.observation_space = observation_space + self.action_space = og_gym.spaces.Box(low=-1, high=1, shape=(7,), dtype=np.float32) + + @staticmethod + def init_for_data_processing(camera_names): + image_modalities = [f'{cn}_image' for cn in camera_names] + + obs_modality_specs = { + "obs": { + "low_dim": [], # technically unused, so we don't have to specify all of them + "rgb": image_modalities, + } + } + ObsUtils.initialize_obs_utils_with_obs_specs(obs_modality_specs) + + @staticmethod + def get_specs_from_obs_keys(lowdim_keys: list[str], rgb_keys: list[str], depth_keys: list[str]): + obs_modality_specs = { + "obs": { + "low_dim": lowdim_keys, + "rgb": rgb_keys, + "depth": depth_keys, + } + } + return obs_modality_specs + + def __getattr__(self, name): + return getattr(self.env, name) + + def get_observation(self, di=None) -> np.ndarray: + if not self.flatten_obs: + return super().get_observation(di) + + obs_dict = self.env._get_observations(force_update=True) + + pf = self.get_prefix() + + return flatten_obs_dict(obs_dict, pf, self.env_config) + + def get_prefix(self): + # only supports one robot for now + for robot in self.env.robots: + return robot.robot_model.naming_prefix + + def get_success(self): + return self.env._check_success() + + def is_done(self): + # need to override EnvRobosuite, which auto sets done to False + return self.env.done + + def get_camera_sizes(self): + return self.env.camera_heights, self.env.camera_widths + + def render(self, mode=None, height=None, width=None, camera_name="agentview"): + if mode is None: + mode = self.render_mode + + if height is None: + height = self.env.camera_heights[0] + if width is None: + width = self.env.camera_widths[0] + + return super().render(mode=mode, height=height, width=width, camera_name=camera_name) + + def step(self, action, *args, **kwargs): + obs, rew, done, info = super().step(action, *args, **kwargs) + + if self.gymnasium_api: + return obs, rew, done, False, info + return obs, rew, done, info + + def reset(self, seed=None): + obs = super().reset() + if self.gymnasium_api: + return obs, None + return obs \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/eval/diffusion_env_runner.py b/code_src/rise_code/sim_pipeline/eval/diffusion_env_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..54f9e97041eab11252e01655531e3bbabd77aa29 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/diffusion_env_runner.py @@ -0,0 +1,37 @@ +import math +import numpy as np + +from sim_pipeline.configs.exp._eval.diffusion_eval import DiffusionEvalExpConfig +from sim_pipeline.eval.eval import setup_eval +from sim_pipeline.eval.rollout import rollout +from sim_pipeline.eval.rollout_stats import RolloutStats + +class DiffusionEnvRunner: + def __init__(self, config: DiffusionEvalExpConfig, n_envs: int, n_train: int, n_test: int): + self.config = config + self.n_envs = n_envs + self.n_inits = n_train + n_test + self.env, self.policy, self.render_mode, video_writers = setup_eval(config) + + def run(self, policy): + n_chunks = math.ceil(self.n_inits / self.n_envs) + rollout_stats = RolloutStats() + + for chunk_idx in range(n_chunks): + rollout( + policy=policy, + eval_envs=self.env, + rollout_stats=rollout_stats, + logger=None, + total_steps=self.config.rollout_horizon, + render_mode=self.render_mode, + log_video=False, + video_writers=None, + render_dims=None, + return_trajectory=False, + end_on_success=False, + ) + + rollout_stats.compute_statistics() + + return rollout_stats.get_avg_stats() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/eval/eval.py b/code_src/rise_code/sim_pipeline/eval/eval.py new file mode 100644 index 0000000000000000000000000000000000000000..65000a58274b5475557d8bfd4bad825595bc81b3 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/eval.py @@ -0,0 +1,1375 @@ +import os +import socket +import numpy as np +import hydra +import torch +import cv2 +import h5py +import uuid +import json +import dill + +import robomimic.utils.file_utils as FileUtils +from omegaconf import open_dict, OmegaConf +from contextlib import nullcontext +from pathlib import Path +from hydra.core.hydra_config import HydraConfig +from hydra import compose + +from gym.vector.vector_env import VectorEnv +from stable_baselines3.common.vec_env import VecEnv + +import robomimic.utils.obs_utils as ObsUtils + +from sim_pipeline.eval.rollout_env import PossibleVecEnv +from sim_pipeline.eval.rollout_policies import * +from sim_pipeline.eval.rollout import rollout +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.configs.constants import PolicyType, CombinedPolicyType, ImitationAlgorithm, ROLLOUT_DATA_DIR +from sim_pipeline.envs.robosuite_wrapper import RobomimicObsWrapper +from sim_pipeline.envs.make_env import make_env, make_vec_env +from sim_pipeline.eval.rollout_stats import RolloutStats +from sim_pipeline.utils.rollout_utils import add_trajectory_to_dataset, merge_obs_specs +from sim_pipeline.utils.train_utils import get_latest_sb_policy, get_latest_robomimic_policy, get_latest_diffusion_policy, get_latest_ogbench_policy +from sim_pipeline.utils.experiment import setup_experiment +from sim_pipeline.utils.video_writer import video_writer_manager +from sim_pipeline.utils.diffusion_utils import get_policy_class, get_workspace +from sim_pipeline.data_manager.modify_dataset import fill_metadata +from sim_pipeline.data_manager.dataset_metadata_enums import * +from sim_pipeline.data_manager.edit_dataset_description import edit_dataset_description +from sim_pipeline.model_manager.get_model import get_model +from sim_pipeline.data_manager.get_dataset import get_dataset + +def get_env(policy_type: PolicyType, config: EvaluationConfig, obs_modality_specs=None, n_envs_override: int = None) -> RobomimicObsWrapper | VecEnv | VectorEnv: + if n_envs_override is not None: + n_envs = n_envs_override + else: + n_envs = config.exp.num_workers + if policy_type == PolicyType.ROBOMIMIC: + if n_envs > 1: + env: VectorEnv = make_vec_env( + env_config=config.env, + num_workers=n_envs, + seed=config.exp.eval_seed, + device_id=config.exp.device_id, + flatten_obs=False, + use_gym_vec_env=True, + gymnasium_api=False, + ) + else: + env: RobomimicObsWrapper = make_env( + env_config=config.env, + seed=config.exp.eval_seed, + device_id=config.exp.device_id, + flatten_obs=False, + ) + elif policy_type == PolicyType.STABLE_BASELINES: + if n_envs > 1: + env: VecEnv = make_vec_env( + env_config=config.env, + num_workers=n_envs, + seed=config.exp.eval_seed, + device_id=config.exp.device_id, + flatten_obs=True, + use_gym_vec_env=False, + mp_context='forkserver', + obs_modality_specs=obs_modality_specs, + gymnasium_api=False, + ) + else: + env: RobomimicObsWrapper = make_env( + env_config=config.env, + seed=config.exp.eval_seed, + device_id=config.exp.device_id, + flatten_obs=True, + ) + elif policy_type == PolicyType.DIFFUSION or policy_type == PolicyType.COMPOSITE or policy_type == PolicyType.OGBENCH: + if n_envs > 1: + env: VectorEnv = make_vec_env( + env_config=config.env, + num_workers=n_envs, + seed=config.exp.eval_seed, + device_id=config.exp.device_id, + flatten_obs=False, + use_gym_vec_env=True, + mp_context='forkserver', + obs_modality_specs=obs_modality_specs, + gymnasium_api=False, + ) + else: + env: RobomimicObsWrapper = make_env( + env_config=config.env, + seed=config.exp.eval_seed, + device_id=config.exp.device_id, + flatten_obs=False, + ) + elif policy_type == PolicyType.PD: + if n_envs > 1: + env: VectorEnv = make_vec_env( + env_config=config.env, + num_workers=n_envs, + seed=config.exp.eval_seed, + device_id=config.exp.device_id, + flatten_obs=False, + use_gym_vec_env=True, + mp_context='forkserver', + obs_modality_specs=obs_modality_specs, + gymnasium_api=False, + ) + else: + env: RobomimicObsWrapper = make_env( + env_config=config.env, + seed=config.exp.eval_seed, + device_id=config.exp.device_id, + flatten_obs=False, + ) + else: + raise NotImplementedError + return env + + +def get_policy_dir(policy_type: PolicyType, config: EvaluationConfig) -> Path | None: + if config.exp.use_model_manager and not policy_type in [PolicyType.PD, PolicyType.COMPOSITE, PolicyType.STABLE_BASELINES, PolicyType.OGBENCH]: + identifier = config.exp.date_string + if identifier: + model_path = get_model(config.name, identifier) + else: + model_path = get_model(config.name) + return Path(model_path) + + if config.exp.model_path: + return Path(config.exp.model_path) + + log_path = config.exp.logdir + match policy_type: + case PolicyType.STABLE_BASELINES: + logdir = Path(log_path) / f'{config.name}' / f'{config.exp.seed}' + case PolicyType.ROBOMIMIC | PolicyType.DISCRIMINATOR: + logdir: Path = Path(log_path) / f'{config.name}' / config.exp.date_string + case PolicyType.DIFFUSION: + logdir: Path = Path(log_path) / f'{config.name}' / config.exp.date_string + case PolicyType.OGBENCH: + logdir: Path = Path(log_path) / f'{config.name}' + case PolicyType.PD: + logdir = None + case PolicyType.COMPOSITE: + logdir: Path = Path(log_path) / config.name + if not logdir.exists(): + logdir.mkdir() + case _: + raise NotImplementedError + return logdir + + +def load_policy(policy_type: PolicyType, config: EvaluationConfig, policy_dir: Path, env, device: torch.device): + match policy_type: + case PolicyType.STABLE_BASELINES: + algo = config.training.algo.get_algo() + ckpt_path = get_latest_sb_policy(policy_dir / 'policy' / '_step_') + model = algo.load(ckpt_path, device=device, env=env) + + return model + case PolicyType.ROBOMIMIC | PolicyType.DISCRIMINATOR: + if policy_dir.suffix == '.pth' and policy_dir.is_file(): # rsm_rise: a checkpoint file directly + ckpt_path = policy_dir + else: + ckpt_path = get_latest_robomimic_policy(policy_dir / 'models') + + policy, ckpt_dict = FileUtils.policy_from_checkpoint(ckpt_path=ckpt_path, device=device, verbose=True, + discriminator=policy_type == PolicyType.DISCRIMINATOR) + # rsm_rise (stream D): the eval config's planner keys (training.plan_* / rsm_*) override the + # checkpoint's algo config -> best-of-N over the diffusion sampler with the RSM scorer. + algo = getattr(policy, 'policy', None) + if hasattr(algo, 'configure_planner'): + from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion import planner_kwargs + kw = planner_kwargs(config.training) + if kw: + algo.configure_planner(**kw) + print(f"[rsm_rise] planner configured: plan_n={kw.get('plan_n')} rule={kw.get('plan_rule')} " + f"backend={kw.get('rsm_backend')} mode={kw.get('plan_mode')} depth={kw.get('plan_depth')} " + f"beta={kw.get('plan_beta')} rsm_ckpt={kw.get('rsm_ckpt')!r}") + + # rsm_rise gen_q#274 (stream NEW_BASELINES): Diffusion Forcing run AS A PLANNER. + # Driven by ENV VARS, not by a config key, deliberately: the training-config schema is + # being edited concurrently by the gen_q#273 stream and an additive env-var hook cannot + # collide with it. Default off -- with RR_DF_CKPT unset this block is a no-op and every + # existing cell takes byte-identical code paths. + # DF is not a scorer backend: it proposes its OWN actions (see code/df_rise/df_policy.py), + # so it REPLACES get_action rather than ranking the proposer's candidates, and its + # candidate count is reported separately and never compared silently against a + # 128-candidate value column. + import os as _os + if _os.environ.get("RR_DF_CKPT"): + import sys as _sys + _sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/code/df_rise") + # $ROOT/env does not ship rotary_embedding_torch, which upstream's + # models/diffusion.py imports unconditionally via unet3d. Vendored pure-python copy + # (code/df_rise/_deps/PROVENANCE.txt); appended INSIDE this block so a non-DF cell is + # untouched, and APPENDED (not inserted) so it can never shadow an env package. + _sys.path.append("/proj/dmfexp/zwhong/rsm_rise/code/df_rise/_deps") + # gen_q#274, measured LSF 1881480 13:35Z: a cell that leaves `training.plan_n` unset + # gets RobomimicSamplingRolloutPolicy (eval.py:493-501, chosen for IDQL when plan_n is + # None). That class duplicates the observation 128x, calls get_action on the batch and + # then picks the best candidate WITH THE RISE CRITIC (:94-111). A DF cell run that way + # would be "DF proposes, the RISE value function selects" while the caption said DF + # selects its own -- the exact silent substitution #274 forbids. Setting plan_n (any + # value; 1 keeps the RSM planner itself off) selects the PLAIN RobomimicRolloutPolicy, + # whose predict() calls get_action once and executes the returned chunk. Refuse + # rather than measure the wrong thing. + _pn_df = config.training.get("plan_n", None) if hasattr(config.training, "get") else None + if _pn_df is None: + raise RuntimeError( + "RR_DF_CKPT is set but training.plan_n is unset, so this cell would run " + "RobomimicSamplingRolloutPolicy: DF's actions would be RANKED BY THE RISE " + "CRITIC instead of by DF's own guidance, and the row would not be a DF row. " + "Pass training.plan_n=1 (the RSM planner stays off; this only selects the " + "plain rollout policy).") + import df_policy as _dfp + _df = _dfp.install( + policy, + ckpt=_os.environ["RR_DF_CKPT"], + feat_stats=_os.environ["RR_DF_FEAT_STATS"], + horizon_frames=int(_os.environ.get("RR_DF_HORIZON", "20")), + guidance_scale=float(_os.environ.get("RR_DF_GUIDANCE", "1.0")), + gamma=float(_os.environ.get("RR_DF_GAMMA", "0.95")), + n_plans=int(_os.environ.get("RR_DF_NPLANS", "128")), + execute_frames=int(_os.environ.get("RR_DF_EXECUTE", "8")), + device=str(device), + seed=int(_os.environ.get("RR_DF_SEED", "0")), + diag_path=_os.environ.get("RR_DF_DIAG", ""), + # RR_DF_SELECT=random -> the random-of-N control on IDENTICAL candidates. + select=_os.environ.get("RR_DF_SELECT", "argmax"), + ) + print(f"[gen_q#274] Diffusion Forcing PLANNER installed: ckpt={_os.environ['RR_DF_CKPT']} " + f"H={_df.H} guidance={_df.guidance_scale} gamma={_df.gamma} " + f"n_plans={_df.n_plans} execute={_df.execute_frames} select={_df.select} " + f"train_step={_df.step}") + + # rsm_rise gen_q#274 (stream NEW_BASELINES): TD-MPC2, BOTH reported configurations. + # Same env-var discipline as the DF block above and for the same reason (gen_q#273 is + # editing the training-config schema concurrently). Default off -- with RR_TD_CKPT + # unset this block is a no-op and every existing cell takes byte-identical code paths. + # RR_TD_MODE=score -> configuration (a), the SHARED-CANDIDATE column. The proposer, + # the candidate set (plan_n, unchanged), the selection rule and the harness are all + # untouched; only the function that ranks the 128 candidates is swapped, by + # pre-populating the planner's scorer cache. This is close to DINO-WM plus a value + # head and the cell JSON's describe() says exactly that. + # RR_TD_MODE=plan -> configuration (b), TD-MPC2's own MPPI/CEM planner seeded by the + # RISE actor as policy prior. It PROPOSES its own actions, so like DF it replaces + # get_action, and its sample count / horizon / iterations are disclosed in the cell + # JSON. Its budget is NOT 128 candidates and must never be printed as if it were. + if _os.environ.get("RR_TD_CKPT"): + import sys as _sys + _sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/code/tdmpc2_rise") + _td_mode = _os.environ.get("RR_TD_MODE", "score") + _algo = getattr(policy, "policy", None) + if _td_mode == "score": + import td_scorer as _tds + if _algo is None or not hasattr(_algo, "_get_scorer"): + raise RuntimeError("RR_TD_MODE=score needs a policy with the RSM planner " + "(rsm_planner.PlannerMixin); got %r" % type(_algo)) + # gen_q#274 run 5: pre-populating `_planner_scorer` only has an effect if the + # planner actually RANKS candidates. `PlannerMixin.planning_enabled` is + # `plan_n is not None and plan_n > 1` (rsm_planner.py:267-269) and + # `plan_get_action` short-circuits to a single unranked sample when N <= 1 + # (:341-345). So a cell whose config left plan_n unset would run the PLAIN RISE + # policy, print the banner below, write a TD-MPC2-labelled cell JSON and never + # once call TD-MPC2. That is the silent no-op #274 forbids -- refuse instead. + _pn = _algo.planner_cfg().get("plan_n") + if not _algo.planning_enabled: + raise RuntimeError( + "RR_TD_MODE=score requires the cell's own planner to be ON " + f"(training.plan_n > 1); got plan_n={_pn!r}, so plan_get_action would " + "return an unranked sample and the TD-MPC2 scorer would never be " + "called. Set plan_n (128 for the shared-candidate column).") + _sc = _tds.make_td_scorer( + _os.environ["RR_TD_CKPT"], _os.environ["RR_TD_FEAT_STATS"], + device=str(device), + mode=_os.environ.get("RR_TD_PLAN_MODE", "d1"), + depth=int(_os.environ.get("RR_TD_DEPTH", "1")), + n_particles=int(_os.environ.get("RR_TD_PARTICLES", "1")), + chunk=int(_os.environ.get("RR_TD_CHUNK", "8")), + adim=int(_os.environ.get("RR_TD_ADIM", "7")), + score_kind=_os.environ.get("RR_TD_SCORE", "prob")) + # gen_q#274 blocker item 3 (owner, 2026-09-23 19:45Z): RR_TD_DUAL_DWM= + # additionally scores THE SAME 128 candidates at THE SAME anchor with the published + # DINO-WM read-out and writes the rank correlation to RR_TD_DUAL_OUT. The cell's own + # selection is untouched -- the wrapper returns TD-MPC2's scores -- but it costs the + # second read-out's forward passes per decision, so a dual run is a DIAGNOSTIC and its + # payload writes it to td274smoke/, never into a published column. + if _os.environ.get("RR_TD_DUAL_DWM"): + import dual_scorer as _dual + _sec = _dual.build_dwm_secondary( + _os.environ["RR_TD_DUAL_DWM"], _os.environ["RR_TD_FEAT_STATS"], + hop_ckpt=_os.environ.get("RR_TD_DUAL_HOP") or None, device=str(device), + depth=int(_os.environ.get("RR_TD_DUAL_DEPTH", "4")), + beta=float(_os.environ.get("RR_TD_DUAL_BETA", "0.95")), + gamma=float(_os.environ.get("RR_TD_DUAL_GAMMA", "0.99")), + n_particles=int(_os.environ.get("RR_TD_DUAL_PARTICLES", "16")), + flow_steps=int(_os.environ.get("RR_TD_DUAL_FLOW", "8"))) + # gen_q#274 run 38 -- RR_TD_DUAL_SWAP=1 exchanges WHICH read-out drives the + # selection. Nothing about either estimator changes: both are built exactly + # as above, from the same checkpoints with the same knobs, and DualScorer + # still returns the PRIMARY's scores and records the other's ranks. Only the + # argument order is swapped. + # + # WHY IT IS THE INSTRUMENT THAT LOCALISES THE DEFECT. status/nb/td_dwm_rho.txt + # carries its own caveat: every anchor in the un-swapped run lies on cfg(a)'s + # OWN trajectory, and that trajectory fails, so agreement there is agreement + # about states cfg(a) already lost. With DINO-WM driving, the anchors are the + # states the PUBLISHED column actually visits, and two things are read at once: + # (i) the matched-anchor rank correlation the un-swapped table says is missing; + # (ii) a WITHIN-HARNESS reproduction -- this cell's success rate should come + # out near DINO-WM's published 31.6 / 21.1. If it does, the eval + # harness and the candidate pool are exonerated and the defect is + # cfg(a)'s ordering; if it does not, the published comparison has a + # confound and NO cfg(a) number may be set beside a DINO-WM number + # until it is found. Either outcome is a result. + # + # LABELLING. A swapped run is NOT a TD-MPC2 score: DINO-WM chooses every + # action. Its payload sets RR_TD_SMOKE=1 and a -DUALSWAP suffix, so it lands + # in td274smoke/ under a name no table reads and can never be pooled into the + # cfg(a) column. + _swap = _os.environ.get("RR_TD_DUAL_SWAP", "0") == "1" + if _swap: + _sc = _dual.DualScorer( + _sec, _sc, _os.environ.get("RR_TD_DUAL_OUT", ""), + "dinowm_published", "tdmpc2_cfg_a", + meta={"td_ckpt": _os.environ["RR_TD_CKPT"], + "dwm_ckpt": _os.environ["RR_TD_DUAL_DWM"], + "swapped": True, + "acting_readout": "dinowm_published", + "cell": _os.environ.get("RR_TD_DUAL_CELL", "")}) + print("[gen_q#274] DUAL READ-OUT SWAPPED: DINO-WM SELECTS, TD-MPC2 cfg(a) " + "observes the same candidates at DINO-WM's own anchors -> " + f"{_os.environ.get('RR_TD_DUAL_OUT','')} " + "(this cell's success rate is DINO-WM's, NOT TD-MPC2's)") + else: + _sc = _dual.DualScorer( + _sc, _sec, _os.environ.get("RR_TD_DUAL_OUT", ""), + "tdmpc2_cfg_a", "dinowm_published", + meta={"td_ckpt": _os.environ["RR_TD_CKPT"], + "dwm_ckpt": _os.environ["RR_TD_DUAL_DWM"], + "swapped": False, + "acting_readout": "tdmpc2_cfg_a", + "cell": _os.environ.get("RR_TD_DUAL_CELL", "")}) + print("[gen_q#274] DUAL READ-OUT on: TD-MPC2 selects, DINO-WM observes the same " + f"candidates -> {_os.environ.get('RR_TD_DUAL_OUT','')}") + # the planner's own cache slot: `_get_scorer` returns this instead of building an + # RSMScorer, and `plan_get_action` is otherwise untouched. + _algo._planner_scorer = _sc + print(f"[gen_q#274] TD-MPC2 SCORER installed (configuration (a), shared candidates): " + f"plan_n={_pn} (the SAME candidate set the RSM/DINO-WM columns rank) " + f"ckpt={_os.environ['RR_TD_CKPT']} gamma={_sc.gamma} " + f"H={1.0/(1.0-_sc.gamma):.1f} chunk={_sc.chunk} " + f"train_step={_sc.backend.step} -- n_particles/flow_steps/beta have no " + f"TD-MPC2 counterpart (td_backend.py N1-N3)") + elif _td_mode == "plan": + import td_policy as _tdp + _tdpol = _tdp.install( + policy, + ckpt=_os.environ["RR_TD_CKPT"], + feat_stats=_os.environ["RR_TD_FEAT_STATS"], + plan_horizon=int(_os.environ.get("RR_TD_HP", "3")), + num_samples=int(_os.environ.get("RR_TD_SAMPLES", "512")), + num_elites=int(_os.environ.get("RR_TD_ELITES", "64")), + iterations=int(_os.environ.get("RR_TD_ITERS", "6")), + num_pi_trajs=int(_os.environ.get("RR_TD_PI_TRAJS", "24")), + temperature=float(_os.environ.get("RR_TD_TEMP", "0.5")), + select=_os.environ.get("RR_TD_SELECT", "mean"), + execute_frames=int(_os.environ.get("RR_TD_EXECUTE", "3")), + device=str(device), + seed=int(_os.environ.get("RR_TD_SEED", "0")), + prior_src=_os.environ.get("RR_TD_PRIOR", "rise_actor"), + diag_path=_os.environ.get("RR_TD_DIAG", "")) + _d = _tdpol.planner + # run 31: the banner must name the prior that ACTUALLY ran. cfg(b) as gen_q#274 + # defines it is "rise_actor"; "tdmpc2" is upstream's own published prior and + # "none" is pure CEM, both used only where our actor's 8-frame executed chunk + # cannot cover the planner horizon. Reading a tdmpc2/none cell as cfg(b) would + # credit our actor with a row it never touched. + _ps = _tdpol.prior_src + _lbl = {"rise_actor": "MPPI/CEM with the RISE actor as policy prior", + "tdmpc2": "MPPI/CEM with TD-MPC2's OWN published prior (model.pi) -- NOT " + "the RISE actor; run because the actor's executed chunk is 8 " + "frames and cannot cover this horizon", + "none": "MPPI/CEM with NO policy prior (pure CEM) -- the prior ablation"}[_ps] + print(f"[gen_q#274] TD-MPC2 PLANNER installed (configuration (b), {_lbl}): " + f"prior_src={_ps} ckpt={_os.environ['RR_TD_CKPT']} " + f"Hp={_d.Hp} samples={_d.num_samples} elites={_d.num_elites} " + f"iters={_d.iterations} pi_trajs={_d.num_pi_trajs} " + f"execute={_tdpol.execute_frames} gamma={_d.gamma} " + f"H_terminal_q={1.0/(1.0-_d.gamma):.1f} " + f"rollouts_per_plan={_d.num_samples*_d.iterations} train_step={_tdpol.step}") + else: + raise RuntimeError(f"RR_TD_MODE={_td_mode!r} is not score|plan") + + return policy + case PolicyType.DIFFUSION: + ckpt_path = get_latest_diffusion_policy(policy_dir / 'checkpoints') + payload = torch.load(open(ckpt_path, 'rb'), pickle_module=dill) + diffusion_cfg = payload['cfg'] + + lowdim_keys = config.training.low_dim_keys + rgb_keys = config.training.rgb_keys + depth_keys = config.training.depth_keys + + # adapt old diffusion library configs + with open_dict(diffusion_cfg): + diffusion_cfg.debug = False + + workspace_cls = get_workspace(rgb_keys, lowdim_keys, depth_keys) + workspace = workspace_cls(diffusion_cfg, output_dir=policy_dir) + workspace.load_payload(payload) + + policy = workspace.model + if diffusion_cfg.training.use_ema: + policy = workspace.ema_model + policy.to(device) + policy.eval() + case PolicyType.OGBENCH: + from impls.utils.flax_utils import restore_agent + from diffusion_policy.dataset.robomimic_replay_image_dataset import RobomimicReplayImageDataset + from diffusion_policy.dataset.robomimic_replay_lowdim_dataset import RobomimicReplayLowdimDataset + from torch.utils.data import DataLoader + + dataset_path = get_dataset(config.data) + + if config.training.rgb_keys: + with h5py.File(dataset_path, 'r') as f: + data = f['data'] + ep_keys = list(data.keys()) + ep = data[ep_keys[0]] + action_shape = ep['actions'].shape[1:] + obs_shapes = {} + for key in config.training.low_dim_keys: + if key not in ep['obs'].keys(): + raise ValueError(f"Key {key} not found in dataset") + obs_shapes[key] = {'shape': ep['obs'][key].shape[1:]} + for key in config.training.rgb_keys: + if key not in ep['obs'].keys(): + raise ValueError(f"Key {key} not found in dataset") + # switch to channels first + obs_shapes[key] = ep['obs'][key].shape[1:] + obs_shapes[key] = { + 'shape': (obs_shapes[key][2], obs_shapes[key][0], obs_shapes[key][1]), + 'type': 'rgb', + } + + shape_meta = { + 'obs': obs_shapes, + 'action': { + 'shape': action_shape, + } + } + + dataset = RobomimicReplayImageDataset( + shape_meta=shape_meta, + dataset_path=dataset_path, + horizon=1, + pad_before=0, + pad_after=0, + n_obs_steps=1, + abs_action=False, + use_cache=True, + seed=config.exp.seed, + val_ratio=0.0, + extra_info=True, + sample_goals=True, + p_currgoal=config.training.p_currgoal, + squeeze=True, + ) + else: + dataset = RobomimicReplayLowdimDataset( + obs_keys=config.training.low_dim_keys, + dataset_path=dataset_path, + horizon=1, + pad_before=0, + pad_after=0, + abs_action=False, + seed=config.exp.seed, + val_ratio=0.0, + extra_info=True, + sample_goals=True, + p_currgoal=config.training.p_currgoal, + squeeze=True, + ) + + train_dataloader = DataLoader( + dataset, + batch_size=config.training.batch_size, + num_workers=0, + shuffle=True, + generator=torch.Generator(device=device), + ) + + example_batch = next(iter(train_dataloader)) + example_batch_np = { + 'observations': example_batch['obs'].numpy(), + 'actions': example_batch['action'].numpy(), + } + agent_class = config.training.algo.get_agent() + agent = agent_class.create( + seed=config.exp.seed, + ex_observations=example_batch_np['observations'], + ex_actions=example_batch_np['actions'], + config=OmegaConf.to_container(config.training), + ) + latest_epoch = get_latest_ogbench_policy(policy_dir / 'checkpoints', find_epoch=True) + policy = restore_agent(agent, str(policy_dir / 'checkpoints'), latest_epoch) + case PolicyType.PD: + policy = None + case _: + raise NotImplementedError + return policy + + +def create_combined_policy( + policies, + combined_policy_type: CombinedPolicyType, + n_envs: int, +): + match combined_policy_type: + case CombinedPolicyType.HEURISTIC_RESET: + policy = HeuristicResetPolicy( + policies=policies, + n_envs=n_envs + ) + case CombinedPolicyType.HEURISTIC_RESET_SPLIT: + policy = HeuristicResetSplitPolicy( + policies=policies, + n_envs=n_envs + ) + case _: + raise NotImplementedError + return policy + + +def create_rollout_policy( + policy, + policy_type: PolicyType, + config: EvaluationConfig, + n_obs_steps: int | None = None, + action_chunking: bool = False, + obs_keys: list[str] | None = None, + lowdim: bool = False, + manual_lookahead: bool = False, + opex: bool = False, + discriminator = None, + expert_policy = None, + ) -> RolloutPolicy: + match policy_type: + case PolicyType.STABLE_BASELINES: + return StableBaselinesRolloutPolicy( + policy, + ) + case PolicyType.ROBOMIMIC: + if opex: + return RobomimicOpexRolloutPolicy( + policy, + action_chunking=action_chunking, + n_obs_steps=n_obs_steps, + is_diffusion=config.training.algo.is_diffusion() + ) + if manual_lookahead: + return ManualLookaheadRolloutPolicy( + policy, + action_chunking=action_chunking, + n_obs_steps=n_obs_steps, + is_diffusion=config.training.algo.is_diffusion() + ) + # rsm_rise gen_q#289 (worker WM_NATIVE) -- the APPENDIX row. Placed BEFORE the plan_n + # branch on purpose: this route has no proposer and no actor at all (CEM over the full + # open-loop action sequence, the published DINO-WM / LeWM planner), so it must never fall + # through into the shared-candidate path even if a cell also carries a stale plan_n. + # Nothing below this branch is reachable from it and nothing in rsm_planner/rsm_scorer is + # modified by it; the arm key starts with 'CEM' so it cannot pool with a shared arm. + if str(config.exp.get('policy_mode', 'idql')) == 'wm_cem': + # imported HERE, not in rollout_policies/__init__: the module pulls in rsm_scorer + # (and through it rsm_libero), and an eager package-level import would put that on + # the import path of every eval cell in the project, sibling streams included. + from sim_pipeline.eval.rollout_policies.wm_native_cem_rollout_policy import ( + WMNativeCEMRolloutPolicy) + spec = str(config.exp.get('wm_cem_json', '') or '') + if not spec: + raise ValueError("exp.policy_mode='wm_cem' needs exp.wm_cem_json " + "(a JSON string, or a path to a .json, with at least " + "{family, ckpt, feat_stats})") + if os.path.exists(spec): + with open(spec) as f: + cem_cfg = json.load(f) + else: + cem_cfg = json.loads(spec) + if int(config.exp.num_workers) != 1: + raise ValueError("policy_mode='wm_cem' is single-env (the CEM state is " + f"per-episode); got exp.num_workers={config.exp.num_workers}") + cem_cfg.setdefault('seed', int(config.exp.eval_seed)) + return WMNativeCEMRolloutPolicy( + policy, + cfg=cem_cfg, + n_obs_steps=n_obs_steps, + is_diffusion=config.training.algo.is_diffusion(), + ) + plan_n = config.training.get('plan_n', None) if hasattr(config.training, 'get') else None + if plan_n is not None: + # rsm_rise (stream D): the planner lives in the algo's get_action; plain rollout policy + return RobomimicRolloutPolicy( + policy, + action_chunking=action_chunking, + n_obs_steps=n_obs_steps, + is_diffusion=config.training.algo.is_diffusion() + ) + if config.training.algo == ImitationAlgorithm.IDQL and config.exp.get('policy_mode', 'idql') != 'bc': + return RobomimicSamplingRolloutPolicy( + policy, + action_chunking=action_chunking, + n_obs_steps=n_obs_steps, + is_diffusion=config.training.algo.is_diffusion(), + discriminator=discriminator, + expert_policy=expert_policy, + ) + return RobomimicRolloutPolicy( + policy, + action_chunking=action_chunking, + n_obs_steps=n_obs_steps, + is_diffusion=config.training.algo.is_diffusion() + ) + case PolicyType.DIFFUSION: + return DiffusionRolloutPolicy( + policy, + action_chunking=action_chunking, + n_obs_steps=n_obs_steps, + obs_keys=obs_keys, + lowdim=lowdim + ) + case PolicyType.OGBENCH: + return OGBenchRolloutPolicy( + policy, + action_chunking=action_chunking, + n_obs_steps=n_obs_steps, + obs_keys=obs_keys, + lowdim=lowdim, + ) + case PolicyType.PD: + return PDRolloutPolicy( + policy=None, + target_pos=config.exp.target_pos, + ) + case _: + raise NotImplementedError + + +def get_policy_info(policy_type: PolicyType, config: EvaluationConfig) -> tuple: + action_chunking = True if policy_type in [PolicyType.DIFFUSION] else False + n_obs_steps = config.training.obs_horizon if policy_type in [PolicyType.DIFFUSION] else None + all_obs_keys = None + only_lowdim = False + obs_modality_specs = None + if policy_type == PolicyType.DIFFUSION or policy_type == PolicyType.OGBENCH: + lowdim_keys = OmegaConf.to_container(config.training.low_dim_keys) + rgb_keys = OmegaConf.to_container(config.training.rgb_keys) + depth_keys = OmegaConf.to_container(config.training.depth_keys) + all_obs_keys = [] + for key in lowdim_keys + rgb_keys + depth_keys: + if key in all_obs_keys: + raise ValueError(f"Duplicate obs key {key}") + all_obs_keys.append(key) + only_lowdim = lowdim_keys and not rgb_keys and not depth_keys + obs_modality_specs = RobomimicObsWrapper.get_specs_from_obs_keys(lowdim_keys, rgb_keys, depth_keys) + elif policy_type == PolicyType.ROBOMIMIC: + if config.training.algo in [ImitationAlgorithm.IQL_DIFFUSION, ImitationAlgorithm.IDQL, ImitationAlgorithm.IDQL_QSM]: + action_chunking = True + n_obs_steps = config.training.observation_horizon + elif policy_type == PolicyType.PD: + obs_modality_specs = {} + return action_chunking, n_obs_steps, all_obs_keys, only_lowdim, obs_modality_specs + + +def get_policy(policy_type: PolicyType, config: EvaluationConfig, device: torch.device, discriminator=None, expert_policy=None) -> tuple[RolloutPolicy, dict | None]: + if policy_type == PolicyType.COMPOSITE: + all_policies = [] + all_obs_modality_specs = [] + for policy_cfg_str in config.exp.policy_configs: + policy_cfg: EvaluationConfig = compose(policy_cfg_str) + rollout_policy, obs_modality_specs = get_policy(policy_cfg.exp.policy_type, policy_cfg, device) + if obs_modality_specs is not None: + all_obs_modality_specs.append(obs_modality_specs) + all_policies.append(rollout_policy) + + obs_modality_specs = merge_obs_specs(all_obs_modality_specs) + + rollout_policy = create_combined_policy( + policies=all_policies, + combined_policy_type=config.exp.combined_policy_type, + n_envs=config.exp.num_workers, + ) + + return rollout_policy, obs_modality_specs + + # rsm_rise gen_q#264 -- IFQL AS PUBLISHED (column (a) of the flagship's IFQL pair). IFQL is not a + # robomimic algo and is trained in JAX, so it is loaded from its exported torch bundle + # (exp.eval_ckpt, written by code/ifql/train_ifql.py) rather than through policy_from_checkpoint. + # Because nothing initialises ObsUtils on this path, the obs specs are built here and returned, which + # is what makes setup_eval call initialize_obs_utils_with_obs_specs before the env is created -- the + # env's observation dict must be the processed one (images float CHW in [0, 1]) that the frozen-DINO + # state expects. Column (b) does not come through here at all: it is the ordinary robomimic path + # with training.rsm_backend=ifql. + if bool(config.exp.get('ifql_policy', False)): + from sim_pipeline.eval.rollout_policies.ifql_rollout_policy import IFQLRolloutPolicy + from robomimic.algo.rsm_scorer import CAMS, PROPRIO_KEYS + ckpt = str(config.exp.get('eval_ckpt', '') or '') + if not ckpt: + raise ValueError('exp.ifql_policy=True needs exp.eval_ckpt = the ifql_bundle.pt') + specs = RobomimicObsWrapper.get_specs_from_obs_keys(list(PROPRIO_KEYS), list(CAMS), []) + rollout_policy = IFQLRolloutPolicy( + ckpt=ckpt, + feat_stats=str(config.exp.get('ifql_feat_stats', '') or ''), + device=device, + num_samples=int(config.exp.get('ifql_num_samples', 128)), + eval_seed=int(config.exp.eval_seed), + ) + print(f'[rsm_rise] IFQL policy (as published): ckpt={ckpt} ' + f'N={config.exp.get("ifql_num_samples", 128)} eval_seed={config.exp.eval_seed}') + return rollout_policy, specs + + policy_dir = get_policy_dir(config.exp.policy_type, config) + action_chunking, n_obs_steps, all_obs_keys, lowdim, obs_modality_specs = get_policy_info(config.exp.policy_type, config) + + if policy_type == PolicyType.STABLE_BASELINES: + # we need env in order to load sb policy + temp_env = get_env(config.exp.policy_type, config, obs_modality_specs, n_envs_override=1) + else: + temp_env = None + + policy = load_policy( + policy_type=config.exp.policy_type, + config=config, + policy_dir=policy_dir, + env=temp_env, + device=device + ) + if policy_type == PolicyType.DISCRIMINATOR: + return policy, None + + if config.exp.use_discriminator: + assert discriminator is not None, "Discriminator policy not found" + + rollout_policy = create_rollout_policy( + policy, + policy_type=config.exp.policy_type, + config=config, + obs_keys=all_obs_keys, + lowdim=lowdim, + action_chunking=action_chunking, + n_obs_steps=n_obs_steps, + manual_lookahead=config.exp.manual_lookahead, + opex=config.exp.opex, + discriminator=discriminator, + expert_policy=expert_policy, + ) + + return rollout_policy, obs_modality_specs + + +def setup_eval(config: EvaluationConfig): + device = setup_experiment(config.exp, eval=True) + + log_video = config.exp.log_video + render = config.env.render + + policy_dir = get_policy_dir(config.exp.policy_type, config) + + if config.exp.use_discriminator: + import copy + discriminator_config = copy.deepcopy(config) + discriminator_config.exp.policy_type = PolicyType.DISCRIMINATOR + discriminator_config.name = config.exp.discriminator_name + discriminator, _ = get_policy(PolicyType.DISCRIMINATOR, discriminator_config, device) + + expert_config = copy.deepcopy(config) + expert_config.exp.policy_type = PolicyType.DIFFUSION + expert_config.exp.use_discriminator = False + expert_config.exp.discriminator_name = None + expert_policy, _ = get_policy(PolicyType.DIFFUSION, expert_config, device) + else: + discriminator = None + + policy, obs_modality_specs = get_policy(config.exp.policy_type, config, device, discriminator=discriminator) + + if obs_modality_specs is not None: + ObsUtils.initialize_obs_utils_with_obs_specs(obs_modality_specs) + env = get_env(config.exp.policy_type, config, obs_modality_specs) + env = PossibleVecEnv(env) + + # human render takes precedence over video recording + if log_video and not render: + video_dir: Path = policy_dir / 'videos_eval' + + if not video_dir.exists(): + video_dir.mkdir() + + default_size = tuple((s[0] if not env.is_vec_env else s[0][0]) for s in env.get_camera_sizes()) + size = default_size if config.exp.video_dims is None else config.exp.video_dims + fps = 20 + video_writers = [] + for i in range(config.exp.num_workers): + video_writer = cv2.VideoWriter(str(video_dir / f'rollout_video_{i}.mp4'), cv2.VideoWriter_fourcc(*'mp4v'), fps, size) + video_writers.append(video_writer) + + render_mode = 'rgb_array' + elif render: + render_mode = 'human' + video_writers = None + else: + render_mode = None + video_writers = None + + return env, policy, render_mode, video_writers + + +def _plan_summary(plan_log): + """Per-episode summary of the planner's per-step logs (rsm_planner.RSMPlannerMixin.pop_plan_log).""" + if not plan_log: + return None + if isinstance(plan_log, dict): + return plan_log # rsm_rise: a summary restored from a .partial on resume -- pass it through + import numpy as _np + def _flat(key): + return [float(v) for st in plan_log for v in (st[key] if isinstance(st[key], list) else [st[key]])] + chosen, smax, smean, sstd = _flat('score_chosen'), _flat('score_max'), _flat('score_mean'), _flat('score_std') + return { + 'steps': len(plan_log), 'n': plan_log[0]['n'], 'rule': plan_log[0]['rule'], + 'score_chosen_mean': float(_np.mean(chosen)), 'score_max_mean': float(_np.mean(smax)), + 'score_mean_mean': float(_np.mean(smean)), 'score_std_mean': float(_np.mean(sstd)), + 'gap_chosen_minus_mean': float(_np.mean(_np.array(chosen) - _np.array(smean))), + 'ties_at_max_mean': float(_np.mean(_flat('ties_at_max'))) if 'ties_at_max' in plan_log[0] else None, + 'frac_saturated_mean': float(_np.mean(_flat('frac_saturated'))) if 'frac_saturated' in plan_log[0] else None, + # rsm_rise (stream E): both read-outs of the RSM scorer, whichever one ranks (plan_score) + 'score_kind': plan_log[0].get('score_kind'), + 'prob_chosen_mean': float(_np.mean(_flat('prob_chosen'))) if 'prob_chosen' in plan_log[0] else None, + 'prob_max_mean': float(_np.mean(_flat('prob_max'))) if 'prob_max' in plan_log[0] else None, + # ties of the PROBABILITY array itself (gen_q#266), which `ties_at_max_mean` does not give when + # another read-out ranks -- this is what makes the prob-vs-prob_log tie claim a within-cell one. + 'prob_ties_at_max_mean': float(_np.mean(_flat('prob_ties_at_max'))) if 'prob_ties_at_max' in plan_log[0] else None, + 'prob_ties_at_max_exact_mean': float(_np.mean(_flat('prob_ties_at_max_exact'))) if 'prob_ties_at_max_exact' in plan_log[0] else None, + 'prob_distinct_mean': float(_np.mean(_flat('prob_distinct'))) if 'prob_distinct' in plan_log[0] else None, + 'logit_chosen_mean': float(_np.mean(_flat('logit_chosen'))) if 'logit_chosen' in plan_log[0] else None, + 'logit_max_mean': float(_np.mean(_flat('logit_max'))) if 'logit_max' in plan_log[0] else None, + 'logit_mean_mean': float(_np.mean(_flat('logit_mean'))) if 'logit_mean' in plan_log[0] else None, + 'logit_std_mean': float(_np.mean(_flat('logit_std'))) if 'logit_std' in plan_log[0] else None, + 'logit_ties_at_max_mean': float(_np.mean(_flat('logit_ties_at_max'))) if 'logit_ties_at_max' in plan_log[0] else None, + # log-complement read-out (gen_q#266, plan_score=prob_log): `prob` folded in log space. The tie + # count is the health number for it -- the claim is that it orders all N where prob ties ~half of + # them, and `prob_log_ties_at_max_mean` next to `ties_at_max_mean` makes that checkable from this + # JSON with no re-scoring. + 'prob_log_chosen_mean': float(_np.mean(_flat('prob_log_chosen'))) if 'prob_log_chosen' in plan_log[0] else None, + 'prob_log_max_mean': float(_np.mean(_flat('prob_log_max'))) if 'prob_log_max' in plan_log[0] else None, + 'prob_log_mean_mean': float(_np.mean(_flat('prob_log_mean'))) if 'prob_log_mean' in plan_log[0] else None, + 'prob_log_std_mean': float(_np.mean(_flat('prob_log_std'))) if 'prob_log_std' in plan_log[0] else None, + 'prob_log_ties_at_max_mean': float(_np.mean(_flat('prob_log_ties_at_max'))) if 'prob_log_ties_at_max' in plan_log[0] else None, + # tolerance-free versions: prob_log spans 40+ orders of magnitude, so an absolute 1e-6 tie + # tolerance is meaningless in the hopeless (all-logits-very-negative) regime. These are what the + # "orders all N" claim must be read off. + 'prob_log_ties_at_max_exact_mean': float(_np.mean(_flat('prob_log_ties_at_max_exact'))) if 'prob_log_ties_at_max_exact' in plan_log[0] else None, + 'prob_log_distinct_mean': float(_np.mean(_flat('prob_log_distinct'))) if 'prob_log_distinct' in plan_log[0] else None, + # conformal read-out (plan_score=conformal_lcb): the per-particle lower quantile that ranks + 'lcb_quantile': plan_log[0].get('lcb_quantile'), + 'lcb_chosen_mean': float(_np.mean(_flat('lcb_chosen'))) if 'lcb_chosen' in plan_log[0] else None, + 'lcb_max_mean': float(_np.mean(_flat('lcb_max'))) if 'lcb_max' in plan_log[0] else None, + 'lcb_mean_mean': float(_np.mean(_flat('lcb_mean'))) if 'lcb_mean' in plan_log[0] else None, + 'lcb_ties_at_max_mean': float(_np.mean(_flat('lcb_ties_at_max'))) if 'lcb_ties_at_max' in plan_log[0] else None, + 't_sample_s': float(sum(st['t_sample'] for st in plan_log)), + 't_score_s': float(sum(st['t_score'] for st in plan_log)), + 'idx': [int(v) for st in plan_log for v in st['idx']], + } + + +# ---- rsm_rise (orchestrator 15:51): episode-level resume ----------------------------------------------------- +# A preempted eval cell used to restart at episode 0, so on `preemptable` a long cell could never finish. +# eval.py writes ".partial" after EVERY episode and eval_cell.sh keeps the furthest attempt as +# ".partial_best"; on start we reload whichever of the two got furthest and continue from the next +# episode index. Resume is refused unless the run is the SAME cell (seed / horizon / policy / planner config), +# so a partial can never be blended into a different recipe. +_RESUME_N = 0 # episodes restored from a partial in this process (recorded in the results JSON) +# NOTE: exp.model_path is the per-attempt mktemp symlink dir of eval_cell.sh, so it is NOT an identity key; +# the checkpoint is compared through exp.eval_ckpt (the real model_epoch_*.pth), which eval_cell.sh passes. +_RESUME_KEYS = ('eval_seed', 'rollout_horizon', 'end_on_success', 'policy_mode', 'success_criterion', 'cell', + 'reset_states_file', 'eval_ckpt') + + +def _resume_fingerprint(config: EvaluationConfig): + fp = { + 'eval_seed': int(config.exp.eval_seed), + 'rollout_horizon': int(config.exp.rollout_horizon), + 'end_on_success': bool(config.exp.get('end_on_success', False)), + 'policy_mode': str(config.exp.get('policy_mode', 'idql')), + 'success_criterion': {'mug': os.environ.get('RSM_RISE_MUG_SUCCESS', 'stock') or 'stock', 'thread': os.environ.get('RSM_RISE_THREAD_SUCCESS', 'stock') or 'stock', 'piece_dz_tol': os.environ.get('RSM_RISE_PIECE_DZ_TOL', '') or None}, # rsm_rise: which env success rule this cell used (#267: 'thread' defaults to stock) + 'cell': str(config.exp.get('eval_cell', '') or ''), + 'eval_ckpt': str(config.exp.get('eval_ckpt', '') or ''), + 'reset_states_file': getattr(config.env, 'reset_states_file', None), + } + try: + from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion import planner_kwargs + fp['planner_overrides'] = {k: (v if isinstance(v, (int, float, str, bool)) or v is None else str(v)) + for k, v in planner_kwargs(config.training).items()} + except Exception: + fp['planner_overrides'] = None + return fp + + +def _rng_state_dump(): + """Serialize the GLOBAL numpy RNG state (robosuite's placement samplers draw from np.random).""" + try: + st = np.random.get_state() + return {'name': str(st[0]), 'keys': [int(x) for x in st[1]], 'pos': int(st[2]), + 'has_gauss': int(st[3]), 'cached_gaussian': float(st[4])} + except Exception as ex: + print(f'[rsm_rise] resume: cannot snapshot the numpy RNG state ({ex!r})') + return None + + +def _rng_state_load(d): + """Restore a state written by _rng_state_dump. True on success.""" + try: + if not isinstance(d, dict) or d.get('name') != 'MT19937' or len(d.get('keys') or []) != 624: + return False + np.random.set_state((d['name'], np.array(d['keys'], dtype=np.uint32), int(d['pos']), + int(d['has_gauss']), float(d['cached_gaussian']))) + return True + except Exception as ex: + print(f'[rsm_rise] resume: cannot restore the numpy RNG state ({ex!r})') + return False + + +def _df_planner(policy): + """The installed DF planner (code/df_rise/df_policy.py `install`), or None for every other cell. + + rsm_rise FINDING AJ (stream DF_MAKEITWORK, 2026-09-24): the DF planner keeps state that the + episode-level resume must carry -- the plan sampler's torch.Generator and the health + accumulators -- exactly as it already carries the env's numpy MT19937 state. df_policy.install + registers itself on the algo, which is where `planner_describe` / `pop_plan_log` are read from. + Returns None (so every non-DF cell is untouched) when no DF planner is installed. + """ + inner = getattr(getattr(policy, 'policy', None), 'policy', None) + # rsm_rise FINDING AK (gen_q#274 run 49-main, 2026-09-24): configuration (b) of #274 installs + # TD-MPC2's MPPI/CEM planner the same way df_policy.install does, and it owns the SAME two kinds + # of resume state (a per-cell torch.Generator for the MPPI noise, and the per-plan health records + # diagnostics() averages). Reaching only `_rr_df_planner` left every cfg(b) cell on the old, + # non-reproducing behaviour: four landed cells published 38%-96% health coverage beside an + # all-episodes success rate (status/nb/resume_audit.json). Both handles expose the same + # state_dump()/state_load() contract, so nothing else in this file changes. A cell is never + # both, and DF keeps precedence if a future cell somehow were. + for attr in ('_rr_df_planner', '_rr_td_planner'): + p = getattr(inner, attr, None) + if p is not None: + return p + return None + + +def _df_state_dump(dfp): + """dfp.state_dump(), but a failure degrades the RESUME rather than killing the running cell.""" + if dfp is None: + return None + try: + return dfp.state_dump() + except Exception as ex: + print(f'[rsm_rise] resume: cannot snapshot the DF planner state ({ex!r}) -- this partial will ' + f'resume with the OLD (non-reproducing) behaviour') + return None + + +def _resume_load(config: EvaluationConfig): + """(n_done, episodes, np_rng_state, planner_state) of the furthest COMPATIBLE partial of this cell. + + `planner_state` is the DF planner's state_dump() as of the same episode boundary, or None for a + non-DF cell and for any partial written before FINDING AJ landed. + """ + import os + path = config.exp.get('results_json', None) + if not path or not bool(config.exp.get('resume_partial', True)): + return 0, [], None, None + fp = _resume_fingerprint(config) + best = (0, [], None, None, None) + for cand in (str(path) + '.partial', str(path) + '.partial_best'): + if not os.path.exists(cand): + continue + try: + with open(cand) as f: + d = json.load(f) + except Exception as ex: + print(f'[rsm_rise] resume: cannot read {cand} ({ex!r}) -- ignored') + continue + # a key missing from the partial = written before that key existed -> not a mismatch, just unverifiable + # rsm_rise #267: `success_criterion` is a DICT that gains sub-keys over time (mug 2026-09-21, + # thread 2026-09-21), so it is compared SUB-KEY-WISE over the sub-keys the partial actually has. + # Comparing the whole dict would declare every partial written before a new sub-key existed "a + # different cell" and silently throw away its finished episodes. + bad = [] + for k in _RESUME_KEYS: + if k not in d: + continue + if k == 'success_criterion' and isinstance(d.get(k), dict) and isinstance(fp[k], dict): + if any(d[k].get(sk) != fp[k].get(sk) for sk in d[k]): + bad.append(k) + continue + if d.get(k) != fp[k]: + bad.append(k) + missing = [k for k in _RESUME_KEYS if k not in d] + if missing: + print(f'[rsm_rise] resume: {cand} predates {",".join(missing)} -- identity taken from its path') + if fp['planner_overrides'] is not None and d.get('planner_overrides') != fp['planner_overrides']: + bad.append('planner_overrides') + if bad: + print(f'[rsm_rise] resume: {cand} is a DIFFERENT cell ({",".join(bad)} differ) -- ignored') + continue + eps = d.get('episodes') or [] + n = min(int(d.get('num_episodes', 0)), len(eps)) + if n > best[0]: + best = (n, eps[:n], cand, d.get('np_rng_state'), d.get('df_planner_state')) + if best[0]: + print(f'[rsm_rise] resume: {best[2]} has {best[0]} finished episodes -> continuing at episode {best[0]}') + return best[0], best[1], best[3], best[4] + + +def _resume_restore(rollout_stats: RolloutStats, episodes): + """Replay finished episodes into a fresh RolloutStats (+ their wall times and planner summaries).""" + ep_times, ep_plans = [], [] + for e in episodes: + rollout_stats.all_reward.append(float(e.get('return', 0.0))) + rollout_stats.all_successes.append(1.0 if e.get('success') else 0.0) + rollout_stats.all_final_successes.append(1.0 if e.get('final_success') else 0.0) + rollout_stats.all_lengths.append(int(e.get('length', 0))) + rollout_stats.all_first_success.append(int(e.get('first_success_step', -1))) + rollout_stats.num_episodes += 1 + ep_times.append(float(e.get('wall_time_s', 0.0))) + ep_plans.append(e.get('plan') or []) + rollout_stats.compute_statistics() + return ep_times, ep_plans + + +def _write_results_json(config: EvaluationConfig, rollout_stats: RolloutStats, policy=None, ep_times=None, + ep_plans=None, t_start=None, partial=False, np_rng_state=None, + df_planner_state=None): + # rsm_rise: per-episode results for the planning grid (stream A) + planner config / timing (stream D) + import os, time as _time + n = rollout_stats.num_episodes + episodes = [ + { + 'episode': i, + 'success': bool(rollout_stats.all_successes[i] > 0.5), + 'final_success': bool(rollout_stats.all_final_successes[i] > 0.5), + 'return': float(rollout_stats.all_reward[i]), + 'length': int(rollout_stats.all_lengths[i]), + 'first_success_step': int(rollout_stats.all_first_success[i]), + } + for i in range(n) + ] + out = { + 'num_episodes': n, + 'success_rate': float(np.mean([e['success'] for e in episodes])) if n else None, + 'final_success_rate': float(np.mean([e['final_success'] for e in episodes])) if n else None, + 'mean_length': float(np.mean([e['length'] for e in episodes])) if n else None, + 'mean_return': float(np.mean([e['return'] for e in episodes])) if n else None, + 'model_path': str(config.exp.model_path), + 'env': OmegaConf.to_container(config.env, resolve=True, enum_to_str=True), + 'rollout_horizon': int(config.exp.rollout_horizon), + 'end_on_success': bool(config.exp.get('end_on_success', False)), + 'policy_mode': str(config.exp.get('policy_mode', 'idql')), + 'success_criterion': {'mug': os.environ.get('RSM_RISE_MUG_SUCCESS', 'stock') or 'stock', 'thread': os.environ.get('RSM_RISE_THREAD_SUCCESS', 'stock') or 'stock', 'piece_dz_tol': os.environ.get('RSM_RISE_PIECE_DZ_TOL', '') or None}, # rsm_rise: which env success rule this cell used (#267: 'thread' defaults to stock) + 'eval_seed': int(config.exp.eval_seed), + 'eval_ckpt': str(config.exp.get('eval_ckpt', '') or ''), + 'reset_states_file': getattr(config.env, 'reset_states_file', None), + 'episodes': episodes, + } + # ---- stream D: planner config, per-episode planner summary, timing, Wilson CI ------------------ + if ep_times is not None: + for i, e in enumerate(episodes[:len(ep_times)]): + e['wall_time_s'] = float(ep_times[i]) + if ep_plans is not None: + for i, e in enumerate(episodes[:len(ep_plans)]): + e['plan'] = _plan_summary(ep_plans[i]) + algo = getattr(getattr(policy, 'policy', None), 'policy', None) + if hasattr(algo, 'planner_describe'): + try: + out['planner'] = algo.planner_describe() + except Exception as ex: + out['planner'] = {'error': repr(ex)} + try: + from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion import planner_kwargs + out['planner_overrides'] = {k: (v if isinstance(v, (int, float, str, bool)) or v is None else str(v)) + for k, v in planner_kwargs(config.training).items()} + except Exception: + pass + # rsm_rise gen_q#289 (WM_NATIVE) -- PROVENANCE, and it was wrong before this block existed. + # On the native-CEM route there is no robomimic planner: `algo` above is the loaded policy, whose + # planner_describe() reports the SHARED planner's DEFAULTS (plan_mode=fold, rsm_backend=mlp, + # plan_n=None) -- a planner this cell never ran and never built. Measured on the first smoke + # cells: every CEM JSON claimed `rsm_backend: mlp, plan_mode: fold`. Anyone reading the archive + # later would have attributed a CEM result to the shared read-out. + # The native planner lives on the ROLLOUT POLICY (it has no algo), so it is read from there. + # Gated on policy_mode == 'wm_cem', which nothing but this route sets, so every other cell's JSON + # is byte-identical. `planner_overrides` is deliberately left alone: it is the training config's + # kwargs (all defaults here, and unread), and it is part of the resume identity key at :1020. + if str(config.exp.get('policy_mode', 'idql')) == 'wm_cem': + try: + out['planner'] = policy.planner_describe() + except Exception as ex: + out['planner'] = {'error': repr(ex)} + out['cell'] = str(config.exp.get('eval_cell', '') or '') + out['task'] = str(config.exp.get('eval_task', '') or config.exp.get('task', '') or '') + out['algo_name'] = getattr(algo, 'algo_name', None) if algo is not None else None + out['num_rollouts_requested'] = int(config.exp.num_rollouts) + out['partial'] = bool(partial) + out['resumed_from_episode'] = int(_RESUME_N) + if np_rng_state is not None: + out['np_rng_state'] = np_rng_state + # rsm_rise FINDING AJ: the DF planner's sampler state + health accumulators, so a preempted cell + # resumes the SAME noise stream (see _df_planner / df_policy.state_dump). PARTIAL FILES ONLY -- + # it is resume scaffolding, not a result, and the published cell JSON stays byte-for-byte the + # shape every landed cell and every table loader already reads. + if partial and df_planner_state is not None: + out['df_planner_state'] = df_planner_state + if n: + p_hat = out['success_rate']; z = 1.96 + den = 1 + z * z / n + centre = (p_hat + z * z / (2 * n)) / den + half = z * np.sqrt(p_hat * (1 - p_hat) / n + z * z / (4 * n * n)) / den + out['success_ci95'] = [float(centre - half), float(centre + half)] + if t_start is not None: + out['wall_time_s'] = float(_time.time() - t_start) + out['wall_time_per_episode_s'] = float(out['wall_time_s'] / max(n, 1)) + plans = [e.get('plan') for e in episodes if e.get('plan')] + if plans: + out['planner_time'] = { + 'steps_total': int(sum(p['steps'] for p in plans)), + 't_sample_s': float(sum(p['t_sample_s'] for p in plans)), + 't_score_s': float(sum(p['t_score_s'] for p in plans)), + 'score_chosen_mean': float(np.mean([p['score_chosen_mean'] for p in plans])), + 'score_max_mean': float(np.mean([p['score_max_mean'] for p in plans])), + 'score_mean_mean': float(np.mean([p['score_mean_mean'] for p in plans])), + 'gap_chosen_minus_mean': float(np.mean([p['gap_chosen_minus_mean'] for p in plans])), + 'ties_at_max_mean': float(np.mean([p['ties_at_max_mean'] for p in plans if p.get('ties_at_max_mean') is not None] or [np.nan])), + 'frac_saturated_mean': float(np.mean([p['frac_saturated_mean'] for p in plans if p.get('frac_saturated_mean') is not None] or [np.nan])), + # gen_q#266: the log-space read-out's tie count, rolled up to the cell so the table can print + # it beside the score without opening the per-episode plans. + 'prob_log_ties_at_max_mean': float(np.mean([p['prob_log_ties_at_max_mean'] for p in plans if p.get('prob_log_ties_at_max_mean') is not None] or [np.nan])), + 'prob_log_std_mean': float(np.mean([p['prob_log_std_mean'] for p in plans if p.get('prob_log_std_mean') is not None] or [np.nan])), + 'prob_ties_at_max_mean': float(np.mean([p['prob_ties_at_max_mean'] for p in plans if p.get('prob_ties_at_max_mean') is not None] or [np.nan])), + 'prob_log_ties_at_max_exact_mean': float(np.mean([p['prob_log_ties_at_max_exact_mean'] for p in plans if p.get('prob_log_ties_at_max_exact_mean') is not None] or [np.nan])), + 'prob_log_distinct_mean': float(np.mean([p['prob_log_distinct_mean'] for p in plans if p.get('prob_log_distinct_mean') is not None] or [np.nan])), + 'prob_ties_at_max_exact_mean': float(np.mean([p['prob_ties_at_max_exact_mean'] for p in plans if p.get('prob_ties_at_max_exact_mean') is not None] or [np.nan])), + 'prob_distinct_mean': float(np.mean([p['prob_distinct_mean'] for p in plans if p.get('prob_distinct_mean') is not None] or [np.nan])), + } + path = str(config.exp.results_json) + os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) + target = path + '.partial' if partial else path + # PER-PROCESS TMP (GAMMA_FAIR run 20, 2026-09-24, measured). `os.replace` makes the PUBLISH atomic, but + # a single shared `.tmp` is not: if two evaluators are on the same cell at once -- which happens + # whenever a drain queue carries the same payload at two indices (measured on q_gf11_tdflow_foldgamma, + # idx 99 and 113 were one file, both running) -- they open, truncate and write that ONE tmp + # concurrently, and whichever calls replace second can publish a truncated or interleaved JSON as the + # cell's result. A pid+host-unique tmp makes the pair last-writer-wins over two independently VALID + # files instead, which is the worst a duplicate should ever cost. Single-writer behaviour is unchanged. + tmp = f"{target}.tmp.{socket.gethostname()}.{os.getpid()}" + try: + with open(tmp, 'w') as f: + json.dump(out, f, indent=2) + os.replace(tmp, target) + finally: + if os.path.exists(tmp): + try: + os.remove(tmp) # write failed partway: never leave a stray tmp behind + except OSError: + pass + if not partial: + for stale in (path + '.partial', path + '.partial_best'): + try: + os.remove(stale) + except OSError: + pass + print(f'[rsm_rise] wrote {path}: success_rate={out["success_rate"]} over {n} episodes') + + +@hydra.main(version_base=None, config_path='../configs', config_name="eval_robomimic") +def eval(config: EvaluationConfig): + config.env.horizon = config.exp.rollout_horizon + env, policy, render_mode, video_writers = setup_eval(config) + + save_dataset = config.exp.save_to_dataset + rollout_stats = RolloutStats() + # rsm_rise: episode-level resume -- reload the furthest compatible partial of THIS cell and continue + global _RESUME_N + _RESUME_N, _resume_eps, _resume_rng, _resume_dfp = _resume_load(config) + _resume_times, _resume_plans = _resume_restore(rollout_stats, _resume_eps) + + if save_dataset: + dataset_name = f'{config.exp.dataset_name}.hdf5' + if not ROLLOUT_DATA_DIR.exists(): + ROLLOUT_DATA_DIR.mkdir() + dataset_path = ROLLOUT_DATA_DIR / dataset_name + total_samples = 0 + demo_num = 0 + + if config.exp.reset_to_data: + ref_dataset_path = get_dataset(config.data) + else: + ref_dataset_path = None + # rsm_rise: fixed initial-state pool (env.reset_states_file), one state per episode drawn with the eval seed + _reset_pool = None + if getattr(config.env, 'reset_states_file', None): + with open(config.env.reset_states_file) as _f: + _reset_pool = [np.array(e['state0'], dtype=np.float64) for e in json.load(_f)['episodes']] + _reset_rng = np.random.RandomState(int(config.exp.eval_seed)) + _reset_idx = [int(_reset_rng.randint(len(_reset_pool))) for _ in range(int(config.exp.num_rollouts))] + print(f"[rsm_rise] resetting every episode to one of {len(_reset_pool)} pooled initial states from {config.env.reset_states_file}") + + try: + with ( + video_writer_manager(video_writers) as video_writers, + (h5py.File(dataset_path, 'w') if save_dataset else nullcontext()) as dataset_file, + (h5py.File(ref_dataset_path, 'r') if ref_dataset_path is not None else nullcontext()) as ref_dataset_file + ): + if save_dataset: + data_grp = dataset_file.create_group('data') + + import time as _time + # rsm_rise: wall time and planner log per episode (pre-filled by an episode-level resume) + _ep_times, _ep_plans = list(_resume_times), list(_resume_plans) + _t_eval0 = _time.time() + # rsm_rise FINDING AJ (stream DF_MAKEITWORK, 2026-09-24) -- the DF planner half of the + # resume. The env half above restores the numpy MT19937 state exactly; the DF plan + # sampler's torch.Generator was NOT carried, so a resumed cell ran the right initial + # states with the wrong noise (measured: threading idmk8 As0-s0 resumed at 44 scored + # 0/6 on its tail against 3/6 fresh, and published 300 plans of health instead of + # 2500). Carrying it makes a resumed cell reproduce a fresh one; a FRESH run never + # reaches state_load, so every landed cell's numbers are untouched. + _dfp = _df_planner(policy) + if _RESUME_N and _dfp is not None: + if _resume_dfp is None: + print(f'[rsm_rise] resume: WARNING -- cell ' + f'{str(config.exp.get("eval_cell", "") or config.exp.results_json)!r} is a ' + f'PLANNER cell (DF or TD-MPC2) resuming at episode {_RESUME_N} from a partial that carries NO ' + f'df_planner_state (written before FINDING AJ landed). Falling back to the OLD ' + f'behaviour: the plan sampler restarts from its seed, so this cell will NOT ' + f'reproduce a fresh run and its planner health covers only episodes ' + f'{_RESUME_N}.. -- discard it and re-run fresh.') + elif _dfp.state_load(_resume_dfp): + print(f'[rsm_rise] resume: restored the DF plan sampler + planner health of episode ' + f'{_RESUME_N} ({len(_dfp._diag)} plans carried forward)') + else: + print(f'[rsm_rise] resume: WARNING -- cell ' + f'{str(config.exp.get("eval_cell", "") or config.exp.results_json)!r} carries a ' + f'df_planner_state that could NOT be restored; falling back to the OLD behaviour ' + f'(the plan sampler restarts from its seed). Discard this cell and re-run fresh.') + if _RESUME_N and _reset_pool is None and _rng_state_load(_resume_rng): + # rsm_rise 23:20 UTC: the partial carries the exact global-numpy RNG state as of the reset of + # episode _RESUME_N, so the resumed tail gets the SAME initial states a fresh run would have + # given it without replaying _RESUME_N env.reset() calls (~1 s each -> up to 100 s per attempt + # on a crashy cell, which is what made the 100-rollout TEST evals of a degenerate job miss the + # deadline). Strictly more faithful than the replay: the replay only matched a fresh run if + # nothing inside a rollout drew from np.random. + print(f'[rsm_rise] resume: restored the numpy RNG state of episode {_RESUME_N} ' + f'(no reset replay needed)') + elif _RESUME_N and _reset_pool is None: + # No fixed init-state pool: episode i's initial state is the i-th draw of the env RNG (seeded with + # eval_seed at creation). Burn _RESUME_N resets so the resumed episodes get the SAME initial states + # a fresh run would have given them -- otherwise the resumed tail would repeat the init states of + # the finished head and the estimate would be built on duplicated inits. + _t_warm = _time.time() + for _ in range(_RESUME_N): + env.reset() + print(f'[rsm_rise] resume: advanced the env RNG by {_RESUME_N} resets ' + f'in {_time.time() - _t_warm:.1f}s') + for i in range(_RESUME_N, config.exp.num_rollouts): + _t_ep0 = _time.time() + if ref_dataset_file is not None: + ind = 9 + + eef_pos = ref_dataset_file['data'][f'demo_{ind}']['obs']['robot0_eef_pos'] + # find first index where z < 0.5 + try: + idx = np.where(eef_pos[:, 2] < 0.835)[0][0] + except IndexError: + idx = 0 + + reset_state = ref_dataset_file['data'][f'demo_{ind}']['states'][idx] + elif _reset_pool is not None: + reset_state = _reset_pool[_reset_idx[i]] + else: + reset_state = None + + traj = rollout( + policy=policy, + eval_envs=env, + rollout_stats=rollout_stats, + reset_state=reset_state, + logger=None, + total_steps=config.exp.rollout_horizon, + render_mode=render_mode, + log_video=config.exp.log_video, + video_writers=video_writers, + render_dims=config.exp.video_dims, + video_skip=config.exp.video_skip, + return_trajectory=save_dataset, + end_on_success=bool(config.exp.get('end_on_success', False)), + ) + if save_dataset: + # save traj + demo_num, added_samples = add_trajectory_to_dataset( + demo_num, + traj, + dataset_file + ) + total_samples += added_samples + + rollout_stats.compute_statistics() + _ep_times.append(_time.time() - _t_ep0) + _algo = getattr(getattr(policy, 'policy', None), 'policy', None) + _ep_plans.append(_algo.pop_plan_log() if hasattr(_algo, 'pop_plan_log') else []) + if config.exp.get('results_json', None): + # snapshot taken here = the RNG state the NEXT episode's env.reset() will consume, + # and (FINDING AJ) the DF plan sampler + planner health as of the same boundary + _write_results_json(config, rollout_stats, policy=policy, ep_times=_ep_times, + ep_plans=_ep_plans, t_start=_t_eval0, partial=True, + np_rng_state=_rng_state_dump(), + df_planner_state=_df_state_dump(_dfp)) + + if config.exp.verbose: + rollout_stats.print_stats(i, total=config.exp.num_rollouts) + + if save_dataset: + data_grp.attrs['total'] = total_samples + + hydra_config = HydraConfig.get() + config_name = hydra_config.job.config_name + data_grp.attrs['config_name'] = config_name + + env_args = env.serialize() + if "placement_initializer" in env_args['env_kwargs']: + env_args['env_kwargs']["placement_initializer"] = None + data_grp.attrs['env_args'] = json.dumps(env_args, indent=4) + + fill_metadata( + dataset_file, + dataset_id=str(uuid.uuid4()), + dataset_type=DatasetType.RL, + action_type=ActionType.RELATIVE, + env_type=EnvType.ROBOMIMIC, + env_name=config.env.env_name.value, + is_real=False, + include_date=True, + include_creator=True, + ) + + print(f"Dataset saved to {dataset_path}") + print(f"Total samples added to dataset: {total_samples}") + if save_dataset: + edit_dataset_description(dataset_path) + if config.exp.get('results_json', None): + _write_results_json(config, rollout_stats, policy=policy, ep_times=_ep_times, + ep_plans=_ep_plans, t_start=_t_eval0, partial=False) + except Exception as e: + # remove partially completed dataset if it was created + if save_dataset: + dataset_path.unlink() + raise e diff --git a/code_src/rise_code/sim_pipeline/eval/eval_on_dataset.py b/code_src/rise_code/sim_pipeline/eval/eval_on_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..2ff25a30c2d851b6a148f52f4f485e6cf8941dee --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/eval_on_dataset.py @@ -0,0 +1,67 @@ +import numpy as np +import h5py +import torch +import click + +import robomimic.utils.file_utils as FileUtils +import robomimic.utils.tensor_utils as TensorUtils + + +def eval_on_dataset( + data_path: str, + policy, + device: torch.device, +): + with h5py.File(data_path, 'r') as f: + data = f['data'] + for ep_key in data: + if ep_key != 'demo_1': + continue + ep = data[ep_key] + obs = ep['obs'] + # Create batch of observations for entire episode + obs_dict = {k: obs[k][:] for k in obs.keys() if k in ['front_image', 'wrist_image', 'states']} + # Prepare observation history with a length of 2 + obs_history = {k: np.zeros((len(obs['front_image']), 2) + obs_dict[k].shape[1:]) for k in obs_dict.keys()} + for t in range(len(obs['front_image'])): + # Collect the current and previous observations + for k in obs_dict.keys(): + if t == 0: + # If it's the first timestep, duplicate the observation + obs_history[k][t, 0] = obs_dict[k][t] + obs_history[k][t, 1] = obs_dict[k][t] + else: + obs_history[k][t, 0] = obs_dict[k][t-1] + obs_history[k][t, 1] = obs_dict[k][t] + + # Reshape image keys to (C, H, W) and scale + for k in obs_history.keys(): + if 'image' in k: + obs_history[k] = obs_history[k].transpose(0, 1, 4, 2, 3) + obs_history[k] = obs_history[k].astype(float) / 255.0 + + ob = TensorUtils.to_tensor(obs_history) + ob = TensorUtils.to_device(ob, device) + ob = TensorUtils.to_float(ob) + # Get predictions for all states at once + predictions = policy.policy.get_action(ob) + + import ipdb; ipdb.set_trace() + + print(predictions) + +def load_policy(policy_path: str, device: torch.device): + policy, ckpt_dict = FileUtils.policy_from_checkpoint(ckpt_path=policy_path, device=device, verbose=True) + return policy + +@click.command() +@click.option('--dataset', '-d', help='Datset file path') +@click.option('--policy_path', '-p', help='Policy path') +def run(dataset, policy_path): + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + policy = load_policy(policy_path, device) + + eval_on_dataset(dataset, policy, device) + +if __name__ == '__main__': + run() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/eval/iql_diagnostic.py b/code_src/rise_code/sim_pipeline/eval/iql_diagnostic.py new file mode 100644 index 0000000000000000000000000000000000000000..f829e9b9eb6694dfcfaae21f6ba4270184fa79bf --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/iql_diagnostic.py @@ -0,0 +1,118 @@ +import hydra + +import torch +import numpy as np +import robomimic.utils.file_utils as FileUtils +import robomimic.utils.train_utils as TrainUtils +import matplotlib.pyplot as plt +from matplotlib.colors import Normalize + +from torch.utils.data import DataLoader + +from omegaconf import OmegaConf +from robomimic.algo.iql import IQL + +from sim_pipeline.configs.constants import PolicyType +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.data_manager.get_dataset import get_dataset +from sim_pipeline.eval.eval import get_policy +from sim_pipeline.training.train_robomimic import get_robomimic_config +from sim_pipeline.eval.rollout_policies.rollout_policy import RolloutPolicy +from sim_pipeline.utils.experiment import setup_experiment + +@hydra.main(version_base=None, config_path='../configs', config_name="eval_robomimic") +def plot_advantages(config: EvaluationConfig): + device = setup_experiment(config.exp, True) + if config.exp.policy_type != PolicyType.ROBOMIMIC: + raise ValueError("This script is only for Robomimic policies") + rollout_policy: RolloutPolicy + rollout_policy, _ = get_policy(config, config, device) + policy: IQL = rollout_policy.policy.policy + + dataset_path = get_dataset(config.data) + robomimic_config = get_robomimic_config(config, dataset_path) + + shape_meta = FileUtils.get_shape_metadata_from_dataset( + dataset_path=dataset_path, + all_obs_keys=robomimic_config.all_obs_keys, + ) + + trainset, validset = TrainUtils.load_data_for_training( + robomimic_config, obs_keys=shape_meta["all_obs_keys"]) + train_sampler = trainset.get_dataset_sampler() + + data_loader = DataLoader( + dataset=trainset, + sampler=train_sampler, + batch_size=100, + shuffle=(train_sampler is None), + generator=torch.Generator(device=device), + num_workers=robomimic_config.train.num_data_workers, + drop_last=True + ) + + all_pos = [] + all_next_pos = [] + all_adv = [] + + count = 0 + for batch in data_loader: + input_batch = policy.process_batch_for_training(batch) + input_batch = policy.postprocess_batch_for_training(input_batch, obs_normalization_stats=None) + + obs = input_batch['obs'] + next_obs = input_batch['next_obs'] + + _, _, critic_info = policy._compute_critic_loss(input_batch) + + q_pred = critic_info['vf/q_pred'] + v_pred = critic_info['vf/v_pred'] + + # adv = v_pred + adv = q_pred - v_pred + adv_weights = policy._get_adv_weights(adv) + + # To - 1 + object_pos = obs['object'][:, 1, :2] + next_object_pos = next_obs['object'][:, 1, :2] + + all_pos.append(object_pos.detach().cpu().numpy()) + all_next_pos.append(next_object_pos.detach().cpu().numpy()) + all_adv.append(q_pred.detach().cpu().numpy()) + count += 1 + if count > 250: + break + all_pos = np.concatenate(all_pos, axis=0) + all_next_pos = np.concatenate(all_next_pos, axis=0) + all_adv = np.concatenate(all_adv, axis=0) + + # filtered = all_adv < 0.8 + # all_pos = all_pos[filtered] + # all_next_pos = all_next_pos[filtered] + # all_adv = all_adv[filtered] + + # Compute reasonable min and max values for the colorbar + val_min = np.percentile(all_adv, 5) # 5th percentile + val_max = np.percentile(all_adv, 95) # 95th percentile + norm = Normalize(vmin=val_min, vmax=val_max) + + goal = (-0.1125, 0.1675) + + vectors = all_next_pos - all_pos + fig, ax = plt.subplots() + quiver = ax.quiver(all_pos[:, 0], all_pos[:, 1], vectors[:, 0], vectors[:, 1], all_adv, norm=norm, angles='xy') + cbar = plt.colorbar(quiver) + # cbar.set_label('adv') + + ax.scatter(x=goal[0], y=goal[1], c='r', marker='o', s=50) + + # Adjust colorbar ticks to show min, max, and clipped ranges + cbar.ax.set_yticklabels([f'<{val_min:.2f}', f'{val_min:.2f}', + f'{(val_min+val_max)/2:.2f}', f'{val_max:.2f}', + f'>{val_max:.2f}']) + plt.show() + # plt.savefig('advantages.svg') + + +if __name__ == "__main__": + plot_advantages() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/eval/label_entropy.py b/code_src/rise_code/sim_pipeline/eval/label_entropy.py new file mode 100644 index 0000000000000000000000000000000000000000..bf62d508c7e256ce7fb8db6713c26ed305a88307 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/label_entropy.py @@ -0,0 +1,196 @@ +import hydra +import numpy as np +import h5py + +from tqdm import tqdm +from omegaconf import open_dict +from scipy.spatial import cKDTree +from scipy.special import digamma + +import robomimic.utils.file_utils as FileUtils +import robomimic.utils.obs_utils as ObsUtils +import robomimic.utils.tensor_utils as TensorUtils + +from sim_pipeline.data_manager.get_dataset import get_dataset +from sim_pipeline.eval.eval import get_policy +from sim_pipeline.eval.rollout_policies.robomimic_sampling_rollout_policy import RobomimicSamplingRolloutPolicy +from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig +from sim_pipeline.utils.experiment import setup_experiment +from sim_pipeline.configs.constants import PolicyType + + +def entropy(samples: np.ndarray, k: int = 5) -> float: + """ + Estimate entropy of the distribution given i.i.d. samples using k-nearest neighbors. + Adapted from RobomimicSamplingRolloutPolicy. + """ + if len(samples.shape) != 2: + raise ValueError(f"Expected samples to have shape (N, D), got {samples.shape}") + N, D = samples.shape + tree = cKDTree(samples) + # Find distances to kth nearest neighbor for each point + distances, _ = tree.query(samples, k=k + 1) # k+1 because the first neighbor is the point itself + knn_distances = distances[:, k] # Distances to the kth nearest neighbor + + # Calculate KNN-based entropy estimate + H = -digamma(k) + digamma(N) + D * np.mean(np.log(knn_distances)) + return float(H) + + +def compute_entropy_for_single_obs( + rollout_policy: RobomimicSamplingRolloutPolicy, + obs_dict: dict, + num_samples: int = 16, + multiplier: int = 4, + k_for_entropy: int = 5, +) -> float: + """ + Given a single (unbatched) observation dictionary (each key -> shape (...)), + replicate it multiple times, sample actions from the policy, + and compute the entropy of all sampled actions. + """ + + prepared_obs = {} + for k, v in obs_dict.items(): + v = v[None, None, ...] + prepared_obs[k] = v + # Stack the same observation H times along time dimension (dim=1) + # Each key is currently shape (1, 1, D1, D2, ...) + H = rollout_policy.n_obs_steps + if H is not None and H > 1: + for k, v in prepared_obs.items(): + # Repeat the same observation H times along dim 1 + prepared_obs[k] = v.repeat(H, axis=1) + + # Use the rollout_policy's own internal method for normalizing / shaping + ob = rollout_policy._robomimic_prepare_observations(prepared_obs) + + # replicate each key num_samples times along the batch dimension + # so shape (1, T, feat_dim) -> (num_samples, T, feat_dim) + ob = {k: ob[k].repeat(num_samples, 1, 1) for k in ob} + + # sample multiple sets of actions + all_actions = [] + for _ in range(multiplier): + # This calls Robomimic's model to get an action for each of the num_samples copies + # shape of actions: (num_samples, 1, action_dim) + actions = rollout_policy.policy.policy.get_action(obs_dict=ob, goal_dict=None) + # remove time dimension + actions = actions[:, 0, :] + all_actions.append(actions.detach().cpu().numpy()) + + actions_np = np.concatenate(all_actions, axis=0) # shape: (num_samples*multiplier, action_dim) + return entropy(actions_np, k=k_for_entropy) + +@hydra.main(version_base=None, config_path="../configs", config_name="eval_robomimic_iql_diffusion") +def annotate_entropy(config: EvaluationConfig): + """ + Example script that: + 1) Loads a Robomimic policy (e.g., IQL, IDQL) using sim_pipeline's utilities. + 2) Loads a Robomimic-format dataset. + 3) For each demonstration and each timestep, computes an action-entropy value by + sampling policy actions multiple times from that state. + 4) Stores the entropy values in a new 'entropy' field in the dataset. + 5) Normalizes entropy values across the entire dataset to range [0,1]. + + Make sure your config has the correct dataset, environment, and policy checkpoint info. + """ + # Ensure we are on the correct device + device = setup_experiment(config.exp, eval=True) + + # Load the policy (for IQL/IDQL). + # This returns a generic RolloutPolicy, which we can cast to RobomimicSamplingRolloutPolicy if needed. + rollout_policy, _ = get_policy(config.exp.policy_type, config, device=device) + + if not isinstance(rollout_policy, RobomimicSamplingRolloutPolicy): + # If we are using IDQL or a variant, the easiest way to replicate the multi-sample logic + # is to use the RobomimicSamplingRolloutPolicy class. Otherwise you can adapt as needed. + print( + "WARNING: The loaded policy is not a RobomimicSamplingRolloutPolicy. " + "This script is tailored to sample multiple actions from IDQL or similar. " + "Proceeding might require code adaptation." + ) + + # Fetch the dataset path from the config + dataset_path = get_dataset(config.data) + + # Initialize any normalizations needed by robomimic + # For IDQL, if your checkpoint has normalization stats, they are typically loaded + # automatically by the policy. If you need explicit calls, do them here: + # ObsUtils.initialize_obs_utils_with_obs_specs(specs) # if needed + + # First pass: compute entropies and collect statistics + all_entropies = [] + with h5py.File(dataset_path, "r+") as hf: + data_grp = hf["data"] + demos = list(data_grp.keys()) + + # Create progress bar for demos + demo_pbar = tqdm(demos, desc="Computing entropies") + for demo_name in demo_pbar: + demo_grp = data_grp[demo_name] + + # Create or overwrite a dataset for entropy + T = demo_grp["actions"].shape[0] + if "entropy" in demo_grp: + demo_pbar.write(f"Overwriting existing entropy data in {demo_name}...") + del demo_grp["entropy"] + ent_dset = demo_grp.create_dataset("entropy", shape=(T,), dtype=np.float32) + + # We'll assume lowdim keys under demo_grp['obs']. Each key -> shape (T, ) + obs_keys = list(demo_grp["obs"].keys()) + + # Create progress bar for timesteps + ts_pbar = tqdm(range(T), desc=f"Processing timesteps for {demo_name}", leave=False) + demo_entropies = [] + for t in ts_pbar: + # Build an obs_dict suitable for the policy + obs_dict = {} + for k in obs_keys: + obs_dict[k] = demo_grp["obs"][k][t] + + # Compute entropy for this timestep + state_entropy = compute_entropy_for_single_obs( + rollout_policy=rollout_policy, + obs_dict=obs_dict, + num_samples=16, # number of repeats + multiplier=4, # how many times to sample + k_for_entropy=5, # K in KNN + ) + demo_entropies.append(state_entropy) + ent_dset[t] = state_entropy + + all_entropies.extend(demo_entropies) + demo_pbar.write(f"Finished computing entropy for {demo_name} with {T} frames.") + + # Compute normalization statistics + all_entropies = np.array(all_entropies) + entropy_min = np.min(all_entropies) + entropy_max = np.max(all_entropies) + entropy_range = entropy_max - entropy_min + + # Second pass: normalize entropies to [0,1] + demo_pbar = tqdm(demos, desc="Normalizing entropies") + for demo_name in demo_pbar: + demo_grp = data_grp[demo_name] + demo_entropies = demo_grp["entropy"][:] + + # Normalize to [0,1] range + normalized_entropies = (demo_entropies - entropy_min) / entropy_range + demo_grp["entropy"][:] = normalized_entropies + + demo_pbar.write(f"Normalized entropy for {demo_name}") + + # Store normalization stats in dataset root + if "entropy_stats" in hf: + del hf["entropy_stats"] + stats_grp = hf.create_group("entropy_stats") + stats_grp.create_dataset("min", data=entropy_min) + stats_grp.create_dataset("max", data=entropy_max) + + print(f"Done annotating and normalizing dataset. Dataset saved at: {dataset_path}") + print(f"Entropy statistics - Min: {entropy_min:.4f}, Max: {entropy_max:.4f}") + + +if __name__ == "__main__": + annotate_entropy() diff --git a/code_src/rise_code/sim_pipeline/eval/rollout.py b/code_src/rise_code/sim_pipeline/eval/rollout.py new file mode 100644 index 0000000000000000000000000000000000000000..88e53ec033baa0c6531a952594fd60182a3a0665 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/rollout.py @@ -0,0 +1,262 @@ +import numpy as np +import torch +import cv2 +try: + from pynput import keyboard +except Exception: # rsm_rise patch: headless nodes + keyboard = None + +from collections import deque +from sim_pipeline.eval.rollout_env import PossibleVecEnv +from sim_pipeline.eval.rollout_policies.rollout_policy import RolloutPolicy +from sim_pipeline.eval.rollout_stats import RolloutStats +from sim_pipeline.utils.logger import Video +from sim_pipeline.utils.logger import Logger +from sim_pipeline.utils.rollout_utils import _render_frame, stack_last_n_obs, add_batch_dim + + +def rollout( + policy: RolloutPolicy, + eval_envs: PossibleVecEnv, + rollout_stats: RolloutStats, + reset_state: np.ndarray | None = None, + logger: Logger | None = None, + total_steps: int | None = 200, + render_mode: str | None = 'rgb_array', + log_video: bool = True, + video_writers: list[cv2.VideoWriter] | None = None, + render_dims: tuple[int, int] | None = None, + video_skip: int = 5, + return_trajectory: bool = False, + end_on_success: bool = True, + tag: str = 'eval' + ) -> None | dict[str, list[np.ndarray | float | bool] | list[list[np.ndarray | float | bool]]]: + """ + General function for rolling out a policy in an environment. + + Args: + policy: supports .predict(action) + eval_envs: must have gymnasium api, so `step` returns (obs, rew, term, trunc, info) and `reset` returns (obs, info) + rollout_stats: RolloutStats object to store episode statistics + logger: supports .record(key, value) + total_steps : number of steps to rollout. If None, roll out + until done=True (for all envs) and assumes all environments terminate at the same time. + render_mode: + 'human' - render to screen. no videos can be saved. `eval_envs` can be + a single environment, or if vectorized, only the first environment is rendered. + 'rgb_array' - `eval_envs` is a vectorized environment. videos are logged if `log_video` + is True. + None - no rendering + log_video: whether to save videos of the rollout. If video_writer is not None, writes to video_writer, + and if logger is not None, logs the video to the logger. + video_writer: a cv2.VideoWriter object to write the video to. Must have `log_video` set to True to save + videos. + render_dims: dimensions to render the video in. If None, uses the default camera size of the environment. + Ignored if vectorized environment. + return_trajectory: whether to return the trajectory of the rollout. + + Returns: + if `return_trajectory` is True, returns a dictionary: + { + 'states': list of states, + 'actions': list of actions, + 'rewards': list of rewards, + 'dones': list of dones + } + if `eval_envs` is a vectorized environment, each list is a list of lists, where each inner list + corresponds to a different env's rollout. Otherwise, each list is a list of the rollout trajectory. + else, returns None + """ + assert isinstance(policy, RolloutPolicy) + + render = torch.cuda.device_count() > 0 and render_mode is not None + eval_envs.render_mode = render_mode + if eval_envs.is_sb_vec_env: + # not correct + camera_height = eval_envs.get_camera_sizes()[0][0][0] + else: + camera_height = eval_envs.get_camera_sizes()[0][0] + + if return_trajectory: + if eval_envs.is_vec_env: + trajectory = { + "states": [[] for _ in range(eval_envs.num_envs)], + "actions": [[] for _ in range(eval_envs.num_envs)], + "rewards": [[] for _ in range(eval_envs.num_envs)], + "dones": [[] for _ in range(eval_envs.num_envs)], + } + trajectory = { + "states": [], + "actions": [], + "rewards": [], + "dones": [], + "obs": [], + } + + ######################################## + # obs shapes: + # SB3: + # non-vectorized: (D, ) flat + # obs: (N, D) flat + # policy handles either + # robomimic: + # non-vectorized: dict -> (d,) + # vectorized: dict -> (N, d) + # -> does not support vectorized eval b/c robomimic policy auto-pads batch dim + # diffusion: + # non-vectorized: dict -> (d, ) + # vectorized: dict -> (N, d) + # policy: + # lowdim expects (N, H, D) + # rgb expects dict -> (N, H, d) + # H - obs horizon, D - total obs dim, d - obs key dim, N - num envs + ######################################## + if reset_state is not None and not eval_envs.is_vec_env: + eval_envs.reset() + obs = eval_envs.reset_to({'states': reset_state}) + else: + obs = eval_envs.reset() + policy.reset() + if return_trajectory: + # doesn't work when eval_envs is VecEnv + state_dict = eval_envs.get_state() + state = state_dict['states'] + trajectory['initial_state_dict'] = state_dict + dones = False + if render_mode == 'rgb_array' and log_video: + frames: list[np.ndarray] = [] + if render: + frame = _render_frame(eval_envs, render_mode, log_video, camera_height, video_writers=video_writers, dims=render_dims) + + if render_mode == 'rgb_array' and log_video and video_writers is None: + frames.append(frame) + + # TODO: Don't assume all eval_envs terminate at the same time. If VecEnv, + # steps is not specified, and a env has done = True before others, will error out. + step_count = 0 + # for diffusion policies/policies that do action chunking, execute one action at a time + action_queue = deque() + if not eval_envs.is_vec_env: + obs = add_batch_dim(obs) + if policy.n_obs_steps is not None: + obs_stack: deque[np.ndarray | dict[str, np.ndarray]] = deque(maxlen=policy.n_obs_steps+1) + obs_stack.append(obs) + else: + obs_stack = None + + global should_stop, random_sample + should_stop = False + random_sample = False + def on_press(key): + global should_stop, random_sample + try: + if key.char == 'q': + should_stop = True + elif key.char == 'r': + random_sample = True + except AttributeError: + pass + + listener = None + if keyboard is not None: + try: + listener = keyboard.Listener(on_press=on_press) + listener.start() + except Exception: + listener = None + + while (total_steps is None and not np.all(dones)) or (total_steps is not None and step_count < total_steps): + if should_stop: + break + + obs_input = obs if policy.n_obs_steps is None else stack_last_n_obs(obs_stack, policy.n_obs_steps) + if policy.action_chunking: + if not action_queue: + actions = policy.predict(obs_input, random_sample=random_sample) + # actions has dim (n_envs, execution_horizon, action_dim) + for i in range(actions.shape[1]): + action_queue.append(actions[:, i]) + actions = action_queue.popleft() + else: + # actions has dim (n_envs, action_dim) + actions = policy.predict(obs_input, random_sample=random_sample) + + if policy.is_composite: + switched = policy.switch_policy(obs, actions, eval_envs) + # empty action queue b/c the new policy might not have action chunking + if switched: + action_queue.clear() + + if not eval_envs.is_vec_env: + # for non vectorized envs, remove batch dim + actions = actions[0] + next_obs, rewards, dones, truncated, infos = eval_envs.step(actions) + + if not eval_envs.is_vec_env: + next_obs = add_batch_dim(next_obs) + if obs_stack is not None: + obs_stack.append(next_obs) + + success: list[bool] | bool = eval_envs.get_success() + + rollout_stats.add_step( + reward=rewards, + success=success, + ) + + if return_trajectory: + if eval_envs.is_vec_env: + for i in range(eval_envs.num_envs): + trajectory['states'][i].append(state[i]) + trajectory['actions'][i].append(actions[i]) + trajectory['rewards'][i].append(rewards[i]) + trajectory['dones'][i].append(dones[i]) + else: + trajectory['states'].append(state) + trajectory['actions'].append(actions) + trajectory['rewards'].append(rewards) + trajectory['dones'].append(dones) + trajectory['obs'].append(obs) + state = eval_envs.get_state()['states'] + + if render: + if step_count % video_skip == 0: + frame = _render_frame(eval_envs, render_mode, log_video, camera_height, video_writers=video_writers, dims=render_dims) + + if render_mode == 'rgb_array' and log_video and video_writers is None: + frames.append(frame) + + if end_on_success: + if isinstance(success, list | tuple) and all(success): + break + elif isinstance(success, bool) and success: + break + + obs = next_obs + step_count += 1 + + if listener is not None: + try: + listener.stop() + except Exception: + pass + # Record episode statistics + rollout_stats.finalize_episode() + if logger is not None: + logger.record(f"{tag}/batch_avg_return", rollout_stats.avg_ep_reward) + logger.record(f"{tag}/success", rollout_stats.avg_ep_success) + logger.record(f"{tag}/final_success", rollout_stats.avg_ep_final_success) + + # Log videos + if render and render_mode == 'rgb_array' and log_video: + if logger is not None: + # -> (b, t, 3, h, w) + downsample + video: np.ndarray[np.uint8] = np.stack(frames).transpose(1, 0, 4, 2, 3)[..., ::2, ::2] + logger.record( + f"{tag}/trajectory/env/camera", + Video(video, fps=20), + exclude=["stdout"], + ) + + if return_trajectory: + return trajectory \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/eval/rollout_env.py b/code_src/rise_code/sim_pipeline/eval/rollout_env.py new file mode 100644 index 0000000000000000000000000000000000000000..121f5b67efa6b0879e2ec55e1d66f335a94207d0 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/rollout_env.py @@ -0,0 +1,62 @@ +from functools import partial + +from gym.vector.vector_env import VectorEnv +from stable_baselines3.common.vec_env import VecEnv + + +class PossibleVecEnv: + def __init__(self, env): + """ + Wrapper to easily handle both single and sb3 vectorized environments for rollouts. + + env must have gymnasium format, so `step` returns (obs, rew, term, trunc, info) + and `reset` returns (obs, info) + """ + self.env = env + self.is_sb_vec_env = isinstance(env, VecEnv) + self.is_gym_vec_env = isinstance(env, VectorEnv) + self.is_vec_env = self.is_sb_vec_env or self.is_gym_vec_env + + def __getattr__(self, name): + if self.is_sb_vec_env: + try: + env_method = getattr(self.env, name) + except AttributeError: + env_method = partial(self.env.env_method, name) + return env_method + elif self.is_gym_vec_env: + try: + env_method = getattr(self.env, name) + except AttributeError: + env_method = partial(self.env.call, name) + return env_method + return getattr(self.env, name) + + def get_success(self) -> list[bool] | bool: + if self.is_vec_env: + try: + return self.__getattr__('get_success')() + except AttributeError: + return [False] * self.env.num_envs + try: + # if defined, i.e. for robomimic envs + return self.env.get_success() + except AttributeError: + return [False] + + def step(self, actions): + # SB3 is stupid and VecEnv expects the wrapped env to have truncated, + # but the actual VecEnv doesn't return truncated + # gym VectorEnv needs to have gym api due to being inherited from diffusion policy's + # implementation, which uses gym api + if self.is_sb_vec_env or self.is_gym_vec_env: + next_obs, rew, dones, infos = self.env.step(actions) + return next_obs, rew, dones, None, infos + return self.env.step(actions) + + def reset(self): + # likewise, SB3 is stupid, and VecEnv expects the wrapped env's reset to return + # a tuple (obs, info), but the actual VecEnv doesn't return info + if self.is_sb_vec_env or self.is_gym_vec_env: + return self.env.reset() + return self.env.reset()[0] \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/eval/rollout_policies/__init__.py b/code_src/rise_code/sim_pipeline/eval/rollout_policies/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f68e9555143e638291fe1670abfda900d47d01a3 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/rollout_policies/__init__.py @@ -0,0 +1,28 @@ +from sim_pipeline.eval.rollout_policies.composite_rollout_policy import CompositeRolloutPolicy +from sim_pipeline.eval.rollout_policies.robomimic_rollout_policy import RobomimicRolloutPolicy +from sim_pipeline.eval.rollout_policies.sb_rollout_policy import StableBaselinesRolloutPolicy +from sim_pipeline.eval.rollout_policies.diffusion_rollout_policy import DiffusionRolloutPolicy +# from sim_pipeline.eval.rollout_policies.ogbench_rollout_policy import OGBenchRolloutPolicy +from sim_pipeline.eval.rollout_policies.rollout_policy import RolloutPolicy +from sim_pipeline.eval.rollout_policies.pd_rollout_policy import PDRolloutPolicy +from sim_pipeline.eval.rollout_policies.manual_lookahead_policy import ManualLookaheadRolloutPolicy +from sim_pipeline.eval.rollout_policies.robomimic_opex_rollout_policy import RobomimicOpexRolloutPolicy +from sim_pipeline.eval.rollout_policies.robomimic_sampling_rollout_policy import RobomimicSamplingRolloutPolicy +from sim_pipeline.eval.rollout_policies.combined.heuristic_reset_policy import HeuristicResetPolicy + +from sim_pipeline.eval.rollout_policies.combined.heuristic_reset_split_policy import HeuristicResetSplitPolicy + +__all__ = [ + "RolloutPolicy", + "PDRolloutPolicy", + "CompositeRolloutPolicy", + "StableBaselinesRolloutPolicy", + "RobomimicRolloutPolicy", + "DiffusionRolloutPolicy", + "HeuristicResetPolicy", + "HeuristicResetSplitPolicy", + # 'OGBenchRolloutPolicy', + 'ManualLookaheadRolloutPolicy', + 'RobomimicSamplingRolloutPolicy', + 'RobomimicOpexRolloutPolicy', +] \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/eval/rollout_policies/combined/heuristic_reset_policy.py b/code_src/rise_code/sim_pipeline/eval/rollout_policies/combined/heuristic_reset_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..93104a9b21528a4ac08b8d7901652e895b6bfd04 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/rollout_policies/combined/heuristic_reset_policy.py @@ -0,0 +1,44 @@ +from sim_pipeline.eval.rollout_policies.rollout_policy import RolloutPolicy +from sim_pipeline.eval.rollout_policies.pd_rollout_policy import PDRolloutPolicy + +from sim_pipeline.eval.rollout_policies.composite_rollout_policy import CompositeRolloutPolicy + +class HeuristicResetPolicy(CompositeRolloutPolicy): + def __init__(self, policies: list[RolloutPolicy], n_envs=1, reset_steps=100, init_run_steps=7): + assert isinstance(policies[1], PDRolloutPolicy) + super().__init__(policies=policies, init_policy_index=0, n_envs=n_envs) + self.reset_steps = reset_steps + self.init_run_steps = init_run_steps + self.steps = 0 + self.curr_policy = 0 + + def reset(self): + super().reset() + self.steps = 0 + self.curr_policy = 0 + + def predict(self, obs, *args, **kwargs): + self.steps += 1 + return super().predict(obs, *args, **kwargs) + + def switch_policy(self, obs, act, env) -> bool: + switched = False + if self.steps < self.init_run_steps: + switched = False + elif self.init_run_steps <= self.steps < self.init_run_steps + self.reset_steps: + self.env_to_policy_idx = {env: 1 for env in range(self.n_envs)} + self.n_obs_steps = self.n_obs_steps_dict[1] + self.action_chunking = self.action_chunking_dict[1] + if self.curr_policy != 1: + self.curr_policy = 1 + switched = True + elif self.steps >= self.init_run_steps + self.reset_steps: + self.env_to_policy_idx = {env: 0 for env in range(self.n_envs)} + self.n_obs_steps = self.n_obs_steps_dict[0] + self.action_chunking = self.action_chunking_dict[0] + if self.curr_policy != 0: + self.curr_policy = 0 + switched = True + else: + raise ValueError(f'Invalid state {self.steps}') + return switched \ No newline at end of file