# RL implementation plan Train a **hand/wrist policy on frozen SONIC**, using **CoordEx’s 12-D hand latent** as the finger action, **relative poses** (object and palm frames) instead of world-frame clip tracking, and **smoothed commands** instead of replaying HaWoR/retarget `q` as the target. This is not a plan to train SONIC, not a plan to train CoordEx’s body VAE, and not a plan to DeepMimic the DexYCB trajectory. --- ## 0. Decision (locked) | Choice | Why | | --- | --- | | Body = frozen SONIC v1.1 ONNX | Already tracks standing / walk references. CoordEx body prior is a different teacher; do not mix two body controllers. | | Fingers = frozen CoordEx **hand** VAE (prior + decoder) | 12-D latent of Wuji finger skills. Query **`prior_net` → μ**, add PPO residual Δz, decode. The posterior **encoder** is distillation-only; we reuse its *latent space*, not `E(z \| s^g, s^p)` at RL time. | | Wrist = SONIC teleop target in the **pelvis** frame, then optionally **object-relative** residuals | World-frame HaWoR wrist is unreachable and noisy. | | Demo from video = object-frame grasp geometry + smoothed finger curl | Never use camera/world `q` or the raw retarget trajectory as `s^g`. | | Task reward first, clip shaping second | Lift / contact on the reconstructed can. Weak relative-demo terms only after contact exists. | Encoder vs prior (do not mix these up in code): ``` CoordEx distillation: encoder(obs_with_goal) → z # unused at RL time CoordEx / our RL: μ = prior(hand_proprio) # 12-D z̃ = μ + Δz # Δz from PPO a_fingers = decoder(proprio, z̃) # 20 Wuji joints ``` Checkpoint: `third-party/coordex/ckpts/hand_prior/kinematic_wrist_16k.pt` Variant: `wuji_floating_kinematic_wrist` (66-D proprio, 12-D latent, 20 finger actions). Do **not** load `body_prior/walkgrab_10k.pt` into the SONIC env. --- ## 1. What is already implemented ### Reconstruction / retarget (data, not RL) | Piece | Status | | --- | --- | | RGB → SAM3 / SAM3D / HaWoR / object 6-DoF | Done (`reconstruction/`) | | MANO → Wuji IK (`g1_wuji_retarget.npz`) | Done (`retarget/`). Wrist free-flyer is **HaWoR camera frame**. | | Isaac pack `isaaclab_replay.npz` + textured `object.urdf` | Done | | Relocate object into SONIC wrist band; flatten Y-up rest pose | Done (`sonic/clip_motion.py`, `object_rest.py`) | ### Frozen whole-body | Piece | Status | | --- | --- | | SONIC v1.1 ONNX, Isaac Lab joint order, batched graphs | Done (`v2d_sim/sonic/`) | | Standing teleop: 3-point VR, right wrist commanded | Done (`BatchedSonicController`) | | Walk reference from MotionBricks planner + `g1` mode track | Done (`planner_ref.py`, `g1_sonic_walkgrab/`) — **play only**, not in the PPO env | | Wrist tracking probe (bias ~8 cm, usable band documented) | Done | ### Gym tasks | Gym id | What it is | Trainable for this goal? | | --- | --- | --- | | `V2D-G1-TableObject-v0` | G1 **minimal** USD, cuboid table/box, **joint PD stub** | No. `rl/train.sh` still **defaults here**. | | `V2D-G1-SonicManip-v0` | Wuji G1, reconstructed can, frozen SONIC, **4-D** wrist xyz + 1-D grip | Scaffold yes. Action/obs/reward **not** the CoordEx-latent design. | | `V2D-G1-SonicWalkGrab-v0` | Walk then wrist; planner clip | Locomotion carrier. No PPO, no hand VAE. | | `V2D-CoorDex-WalkGrab-Play-v0` | Full CoordEx residual actor + both VAEs + WalkGrab layout | Literature baseline play. ~3 mm lift on our can. Not our trainer. | ### `V2D-G1-SonicManip-v0` in detail (the env to extend) **Implemented** - Scene: standing pelvis z=0.78, object at ~(0.36, −0.20) on a shallow table, coffee-can URDF, upright rest quat. - Action `SonicWristAction`: 4-D in [−1,1] → pelvis-frame wrist box + uniform finger flexion. SONIC 50 Hz inside the term; fingers **not** through a VAE (one scalar × joint limits). - Obs (~20-D): projected gravity, **achieved** wrist in pelvis, object in pelvis, object−wrist, object lin vel (pelvis), grip, last action. - Reward: tanh reach, lift-from-**rest** gated on proximity, alive, fall, torso, action-rate. - Reset: object xy/yaw jitter about world vertical (correct composition for Y-up mesh). - Rates: physics 200 Hz, SONIC 50 Hz, policy 25 Hz (`dt=0.005`, `decimation=8`). - PPO cfg: small MLP 256–128, 4-D Gaussian, 3000 iters (`G1SonicManipPpoRunnerCfg`). - `rl/scripts/train.py`: RSL-RL `OnPolicyRunner` via `RslRlPpoTrainer` — **algorithm wrapper exists**, pointed at whatever `--task` you pass. **Not implemented (this is the work)** - CoordEx `StudentTeacherVAE` load / `prior_mean` / `decode` on the SONIC robot. - 12-D hand residual in the action (still 1-D grip). - Object-frame or palm-frame observations (everything is pelvis- or world-z). - Demo buffer of **relative** grasp (palm–object, fingertips–object, filtered finger `q`). - Smoothing beyond a small action-rate penalty (no EMA on wrist or Δz; `process_actions` writes the command every policy step). - Fingertip contact forces (CoordEx WalkGrab needs them; our env does not expose them). - Wrist orientation as an action (held at standing VR quat). - Clip-conditioned phase / RSI from retarget. - `rl/train.py` default task is still `V2D-G1-TableObject-v0`. - Play script for SonicManip + checkpoint (play.py is table-object zeros/random). ### CoordEx code we can import (do not reimplement) Already in-tree, used by the WalkGrab **play** port: - `coordex.distillation.vae.StudentTeacherVAE` - `coordex.tasks.locomanip.mdp.actions._load_student_prior` / `_PriorPolicy.infer_with_delta` - `right_hand_proprio` (66-D: palm vel in palm frame, 20 q, 20 dq, 20 last a) - Checkpoint loader that strips `actor.` for teacher and keeps prior+decoder for rollout Isaac Lab 6 `ProxyArray` shims live in `tasks/coordex_v2d/proxy_compat.py`. Reuse that pattern if the VAE path touches `asset.data`. --- ## 2. What we will not do - Train or finetune SONIC; train CoordEx body prior; joint-space PPO on 29/49/69 DoF. - Use world-frame or camera-frame retarget `q` / wrist `xyz` as a tracking target (`s^g`). - Replay DexYCB layout (object at ~1.1 m). - Primary loss = per-frame MANO/Wuji trajectory MSE (noisy, wrong workspace). - Copy CoordEx WalkGrab rewards (walk to x=1.5, bottle cylinder, fingertip-filter that is dead on our mesh). - Run the VAE **encoder** in the RL loop (it needs a reference goal the video does not provide cleanly). --- ## 3. Target MDP (what to implement) One Gym id, extend `g1_sonic_manip` (keep the current 4-D env as a smoke/regression if needed via a cfg flag or `G1SonicManipLiftCfg`). ### 3.1 Action (smooth, latent, not clip `q`) **15-D raw policy output**, all in [−1, 1], then smoothed: | Dim | Meaning | After process | | --- | --- | --- | | 3 | Wrist **residual in the object frame** (or pelvis, see note) | EMA → add to a default hover pose expressed in that frame → convert to SONIC pelvis-frame target, clamp to probe box | | 12 | Hand latent residual Δz | `z̃ = μ + scale * tanh(Δz)`; `μ = prior(right_hand_proprio)` | **Smoothing (required)** - Exponential moving average on both wrist residual and Δz (`α ≈ 0.15–0.35` at 25 Hz), reset EMA on env reset. - Keep / strengthen `action_rate` on the **pre-EMA** or post-EMA command (penalise both jitter and lag if needed). - Optional: policy outputs **deltas** of the residual (`a_t` integrates), which is smoother than absolute 15-D every step. Note on wrist frame: prefer **object-relative**. Default hover = a fixed offset in the object frame (e.g. palm above can, from median pre-grasp of the **relocated, object-frame** demo — a constant, not a time series). PPO only learns a small 3-D nudge. Convert `T_object * hover * residual` into pelvis xyz for SONIC. That is “relative pose,” not “follow `hand_pos_w[t]`.” Fingers never see a 20-D `q_demo[t]`. They only see μ(proprio) + Δz. ### 3.2 Observation (relative) Keep SONIC-bias loop closure (achieved wrist). Add object-centric terms. Drop world xyz. | Term | Dim | Status | | --- | --- | --- | | projected_gravity | 3 | Have | | achieved wrist in **pelvis** | 3 | Have (needed for SONIC bias) | | object in **pelvis** | 3 | Have | | object → wrist in pelvis | 3 | Have | | object lin vel in pelvis | 3 | Have | | last action | 15 | Have pattern, dim change | | **object pose in palm** (pos + 6D rot) | 9 | **Missing** (CoordEx `cube_pose_in_hand`) | | **μ_hand** (prior mean) | 12 | **Missing** | | last Δz | 12 | **Missing** | | grip / mean finger flexion | 1 | Have as 1-D command; keep decoded mean | | fingertip–object distances (5) | 5 | **Missing** (positions, not PhysX filter) | Skip `force_matrix_w` until a smoke shows contacts; CoordEx’s filtered wrench is unreliable on this URDF. Do **not** add `e_abs` / `e_rel` vs `isaaclab_replay` world object path as the main obs. If a demo term is added later, it must be object-frame (palm pose relative to can at contact time), not `(x_t − x_0)` in world. ### 3.3 Reward (task first) 1. Reach: palm / fingertips to object (object frame or Euclidean), same spirit as current tanh. 2. Contact proxy: min fingertip–object distance, or n tips below a threshold. 3. Lift from rest height, **gated** on proximity/contact (already implemented — keep). 4. Smoothness: action-rate on 15-D; optional jerk on object. 5. Fall / table-knock / object-off-table (have fall + object_fell). 6. **Optional weak** relative-demo: `exp(−‖q_fingers − q_rel_demo‖)` only while palm is near the object, with `q_rel_demo` a **single smoothed grasp shape** or a 5-frame blend, not the full clip. Success metric for reports: lift > 5 cm while grasped, fall rate, action smoothness (‖a_t − a_{t−1}‖), not ‖object − clip_world‖. ### 3.4 Demo preprocessing (offline, once per clip) New small script (not in the RL loop): 1. Load `g1_wuji_retarget.npz` + object poses from `isaaclab_replay.npz`. 2. Drop frames with high `tip_err` or object-track jumps. 3. Low-pass finger `q` and palm pose. 4. Express palm and fingertips in the **object frame**; resample to 50 Hz. 5. Pick a contact window; store: - `hover_offset_obj` (median pre-grasp palm in object frame) - `q_grasp` (median closed shape, 20-D) - optional short relative trajectory for RSI **only** (start some episodes with palm near hover) Write `reconstruction/runs//obj_tracking_out/grasp_relative.npz`. The MDP reads this constant/window, never the raw camera trajectory. --- ## 4. Phased work Do not start PPO until Phase B’s scripted latent+hover smoke moves the can more than the current 1-D grip smoke (~0 cm lift, ~6 cm hand gap). ### Phase A — Wire frozen hand VAE into SonicManip (no PPO) **Work** - New action term `SonicWristHandLatentAction` (or flag on the existing term): load `kinematic_wrist_16k.pt` with the same helper CoordEx uses; build 66-D `right_hand_proprio` on Wuji joint names; `μ = prior(obs)`; decode `μ` with Δz=0; PD the 20 fingers; SONIC still owns 29 body joints + wrist target. - Hold wrist at current hover (center of probe box) or at `hover_offset_obj` converted to pelvis. - EMA on decoded finger targets (CoordEx already has `hand_action_moving_average` — copy the idea). - `proxy_compat` if `joint_pos` is a `ProxyArray`. - Obs: expose `μ` for debugging. **Gate.** Env steps; robot stands; fingers take a stable pose (not NaN, not limit bang); `μ` finite and slowly varying as the arm moves. Video: `runs/sonic_manip/vae_zero_delta.mp4`. ### Phase B — Relative hover + scripted close (no PPO) **Work** - Offline `grasp_relative.npz` for coffee can (and later sugar box). - Wrist target = object-frame hover → pelvis, clamped to probe box. - Script: approach (Δz=0), then interpolate Δz toward a **constant** that decodes near `q_grasp` (solve once: least-squares Δz so decoder(μ, μ+Δz) ≈ q_grasp at a recorded proprio, or just ramp a few latent axes). Not `q[t]` from the clip. - Log: palm–object, min tip–object, object Δz vs rest, ‖a_t − a_{t−1}‖. **Gate.** Object lifts or at least displaces vs no-op. If still no contact: fix hover (bias from probe), table friction, thumb CMC limits (already 0.05 on WalkGrab). **Do not train.** ### Phase C — Relative obs + 15-D action + smoothness **Work** - Palm-frame object pose; fingertip distances; μ; last Δz. - Policy action 3+12 with EMA; action-rate on 15-D. - Rewards as §3.3; **no** world-clip tracking terms. - Episode ~6–8 s; object reset with small xy jitter, modest yaw. - Point `rl/train.py` default `--task V2D-G1-SonicManip-v0` (or `V2D-G1-SonicHandLatent-v0` if split). `play.py` loads RSL-RL checkpoint, records mp4, prints lift / smoothness. **Gate.** `train.sh --headless --num_envs 32 --max_iterations 2` with `SONIC_ORT_CUDA=1`. Random policy does not fall immediately. Expert-script return (Phase B) ≫ zero-action return. ### Phase D — PPO **Work** - Actor/critic: not CoordEx’s 28-D coord residual (that expects body μ + cube forces). New MLP: obs → 15-D, similar size to `G1SonicManipPpoRunnerCfg` or slightly larger (512–256) because of 12-D Δz. - Freeze VAE and SONIC (`requires_grad=False`; ONNX already frozen). - Start `num_envs=32`, then 64–256 if H100 memory allows (SONIC + Wuji + VAE). - Metrics: lift cm, contact fraction, fall rate, mean ‖Δa‖, mean ‖Δz‖ (residuals should stay small if the prior is useful). **Gate.** Beats Phase B scripted lift, or matches it with closed-loop correction of SONIC wrist bias. If Δz saturates at ±1 and fingers look unlike a grasp, the prior is OOD for this can → Phase E. ### Phase E — Only if D stalls In order: 1. Probe-bias on wrist hover (signed 8 cm) so 3-D residual stays small. 2. Distill a **new** hand prior from the floating-hand replay of **object-frame** smoothed clip (wrist written in, fingers track filtered `q`). Then PPO residual on *that* μ. This is the only time we train something CoordEx-encoder-like, and the goal is still relative. 3. Wrist orientation (6-D) if palm-down vs standing yaw cannot grasp. 4. After standing grasp works: attach walk (`SonicWalkWristAction` handover) so locomotion stays frozen planner+SONIC and the same 15-D policy runs in reach phase. --- ## 5. File-level sketch | Path | Change | | --- | --- | | `simulation/scripts/export_grasp_relative.py` | **New.** Offline object-frame demo. | | `v2d_sim/tasks/g1_sonic_manip/mdp/hand_prior.py` | **New.** Load VAE, proprio, `infer_with_delta`. | | `v2d_sim/tasks/g1_sonic_manip/mdp/actions.py` | Wrist + 12-D latent, EMA, object-frame hover. | | `.../mdp/observations.py` | Palm-frame object, μ, tip distances. | | `.../mdp/rewards.py` | Keep lift gate; add tips; smoothness; no world clip MSE. | | `.../g1_sonic_manip_env_cfg.py` | New action/obs; optional split cfg class. | | `.../agents/rsl_rl_ppo_cfg.py` | Action dim 15; hidden sizes. | | `rl/scripts/train.py`, `play.py`, `train.sh` | Default SonicManip; play checkpoint + metrics. | | `docs/rl_implementation_plan.md` | This file. | Do not modify `coordex` sources; import and shim. --- ## 6. Order of work ``` A load kinematic_wrist_16k.pt in SonicManip, Δz=0, stand └─ gate: stable fingers, finite μ B object-frame hover + scripted latent close; grasp_relative.npz └─ gate: object moves vs no-op C 15-D smooth action, relative obs, rewards; trainer default task └─ gate: 2 PPO iters D train; compare lift / smoothness to B E new relative-only hand distill, or walk handover, only if D saturates ``` Start A on clip `20200709_141754` (coffee can already in the env). Parallel: CoordEx WalkGrab play stays a literature number, not this training path.