Add fair-comparison/bext-v1
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- fair-comparison/bext-v1/CODE_SNAPSHOT.jsonAdded+283
- fair-comparison/bext-v1/code/lim/__init__.pyAdded+1
- fair-comparison/bext-v1/code/lim/act_optimization.pyAdded+81
- fair-comparison/bext-v1/code/lim/act_policy.pyAdded+1123
- fair-comparison/bext-v1/code/lim/action.pyAdded+77
- fair-comparison/bext-v1/code/lim/action_encoding.pyAdded+120
- fair-comparison/bext-v1/code/lim/action_objective.pyAdded+159
- fair-comparison/bext-v1/code/lim/chunk_coordinates.pyAdded+236
- fair-comparison/bext-v1/code/lim/chunk_endpoint.pyAdded+69
- fair-comparison/bext-v1/code/lim/chunk_phase.pyAdded+32
- fair-comparison/bext-v1/code/lim/chunk_switch.pyAdded+60
- fair-comparison/bext-v1/code/lim/collect_keyposes.pyAdded+564
- fair-comparison/bext-v1/code/lim/evaluate_phase_chunk.pyAdded+327
- fair-comparison/bext-v1/code/lim/evaluate_planned_keypose.pyAdded+1210
- fair-comparison/bext-v1/code/lim/gripper_execution.pyAdded+228
- fair-comparison/bext-v1/code/lim/gripper_feedback.pyAdded+213
- fair-comparison/bext-v1/code/lim/job.pyAdded+102
- fair-comparison/bext-v1/code/lim/keypose_context.pyAdded+156
- fair-comparison/bext-v1/code/lim/keypose_control.pyAdded+139
- fair-comparison/bext-v1/code/lim/keypose_data.pyAdded+317
- fair-comparison/bext-v1/code/lim/keypose_dense.pyAdded+135
- fair-comparison/bext-v1/code/lim/keypose_diagnostics.pyAdded+205
- fair-comparison/bext-v1/code/lim/keypose_oracle.pyAdded+191
- fair-comparison/bext-v1/code/lim/keypose_phase.pyAdded+75
- fair-comparison/bext-v1/code/lim/keypose_policy.pyAdded+260
- fair-comparison/bext-v1/code/lim/keypose_sequence.pyAdded+46
- fair-comparison/bext-v1/code/lim/keypose_stop.pyAdded+77
- fair-comparison/bext-v1/code/lim/keypose_trace.pyAdded+71
- fair-comparison/bext-v1/code/lim/normalization.pyAdded+263
- fair-comparison/bext-v1/code/lim/observations.pyAdded+89
- fair-comparison/bext-v1/code/lim/ood_env.pyAdded+94
- fair-comparison/bext-v1/code/lim/planned_keypose.pyAdded+370
- fair-comparison/bext-v1/code/lim/policy.pyAdded+52
- fair-comparison/bext-v1/code/lim/policy_video.pyAdded+189
- fair-comparison/bext-v1/code/lim/profile.pyAdded+122
- fair-comparison/bext-v1/code/lim/reference_act.pyAdded+855
- fair-comparison/bext-v1/code/lim/replay_pose.pyAdded+247
- fair-comparison/bext-v1/code/lim/run_sequence.pyAdded+194
- fair-comparison/bext-v1/code/lim/smoke.pyAdded+79
- fair-comparison/bext-v1/code/lim/tasks.pyAdded+22
- fair-comparison/bext-v1/code/lim/train_offline.pyAdded+716
- fair-comparison/bext-v1/code/lim/train_resume.pyAdded+219
- fair-comparison/bext-v1/code/lim/waypoints.pyAdded+83
- fair-comparison/bext-v1/runs/dense-q50-u90k-n100-s106/reference.jsonAdded+92
- fair-comparison/bext-v1/runs/dense-q50-u90k-n100-s106/train-spec.jsonAdded+120
- fair-comparison/bext-v1/runs/dense-q50-u90k-n100-s106/train/metrics.jsonlAdded
- fair-comparison/bext-v1/runs/dense-q50-u90k-n100-s106/train/normalization.jsonAdded+119
- fair-comparison/bext-v1/runs/dense-q50-u90k-n100-s106/train/offline-training.jsonAdded+343
- fair-comparison/bext-v1/runs/dense-q50-u90k-n100-s106/train/runs/fair-dense-q50-u90k-n100-s106/checkpoints/89999.ptAdded+3
- fair-comparison/bext-v1/runs/dense-q50-u90k-n100-s106/train/verification.jsonAdded+21
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283{ "artifact": "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1", "files": { "/home/ghz/Work/Research/lim/pixi.toml": "c4646961cd9519cb1ec640821b29b2a12a230a807db21b6e7914b5f59c7cb6e9", "/home/ghz/Work/Research/lim/pixi.lock": "d99598c608997b2284003d1bfb3ac4dc25cd3c5436765b4728ee8e36500d19d8", "/home/ghz/Work/Research/lim/round2/reference-source.json": "a73f863463cce7b3672dc8e8a1f012042579349cf1296af55b02520a5f34fbdc", "/home/ghz/Work/Research/lim/experiments/keypose-mechanism/essence-h800/specs/fendpoint_fg-main-train.json": "5bc2a32c0592bd041c04da4557fcd84d980776e6ce43316e30f55a69215405eb", "/home/ghz/Work/Research/lim/experiments/keypose-mechanism/essence-h800/specs/fendpoint_fg-main-eval.json": "1404828d20e9f10e26c9f7f32e2894428a3d282a159d46067459af194534cbcf", "/home/ghz/Work/Research/lim/artifacts/keypose-data/main/pose/trajectory.h5": "308b8042624e38d90f6f2ff8514969b77f1957664a8a428f7193d2e0c39869c6", "/home/ghz/Work/Research/lim/artifacts/essence-h800/speed/cap95.json": "3a0b63102fbb42c30959fe04e4af60bbeec3f16e3d4741ea405f88ec543910e2", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/__init__.py": "0cc163c61e6ea84e2d0707efb92d5a97f63007460dc3fab12583ee531a1fbf1d", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/act_optimization.py": "45122bf568e42e20fcff5b39ed68c8e238a11dde07c413ae87078b7d6c554af8", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/act_policy.py": "1ecdbb0f3ada222564cc12de40ed625a38771bccc8d1b4320d5cd152eb5747ca", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/action.py": "d787ae6e63b633b38db7d83182c607ce65d4720e0f4f2005a0ff3798ff476bf0", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/action_encoding.py": "178cab172b0afc168bf015599775278240f2126d243c25e9be4a5a7650966a13", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/action_objective.py": "8ed428059d407627d42978a136d5059de4ee686fe805d3edc372e6d628673a55", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/chunk_coordinates.py": "9ae44c42103ba1e286cb4487c20b4df8b414ed28c450fca2493bcd5d47c8a8b0", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/chunk_endpoint.py": "64a86d99276874fdc3be5d63e8abd4b5cf34308f9c77cc0ce859eb76ca802ba8", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/chunk_phase.py": "7cdb66ed1fc09458f8c19119f20f4ce33287d88b9a7bd2d1a610938116494572", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/chunk_switch.py": "72cd6201e69cbb21b065be5a58da8f7ffeccd1b671aa42c1944adba40513d5b9", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/collect_keyposes.py": "fc038e6dae095b3c61fa32079b64dce54a4f43745eef675652d6c03a79192393", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/evaluate_phase_chunk.py": "f8d62d1f62a49415ab774210df2da7888952d9007d5d7a166e1bf227e94ba997", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/evaluate_planned_keypose.py": "a38bc26b814adeb2d5e9108c83dfcdb999a45877018254c61abe68c8ad1da45e", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/gripper_execution.py": "ea0f64a596c6695c8863d12a55a835d11bebd7080f0055a64919b54b4bc944c8", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/gripper_feedback.py": "d61c8edca56f663bbc9a28c381b663efa800661afae26a14a0f127102ff077ac", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/job.py": "66d337f158e7f88717fd4aba1cd83f730778c53e911aee26038a4d9969583729", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/keypose_context.py": "c1d3e9e410b8743ac05791eb82d24e3557fd4de6c020c7614ef5ab28454a1a07", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/keypose_control.py": "c976047a23a831a44e2b6056c3337483c892facc27976b70fcaebea5cb3d8730", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/keypose_data.py": "6ca26ad1640b20d4f2e013a1d6876fab18e88cf27eb048f7b18df0ab6c0091b5", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/keypose_dense.py": "2eaf0cfb30735491613a9431d58e75832196b9578dff611b9e8d74374a77f9cd", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/keypose_diagnostics.py": "5e6fc13c3192970547c858cff8dc230b1573c8e06f2385cb537f2a850b4c2b23", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/keypose_oracle.py": "4a0c5beded686c42289f9dac8b42633033f5d4028c77be659a6c615e6521963f", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/keypose_phase.py": "5381954388521c9e45de1046a99be81fc6967268e9fa37cc7a492eef422e33c2", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/keypose_policy.py": "f0dc4b64217f3014fc91416c2a4e3adebe37a4f598457488511cb630ff7fdbe8", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/keypose_sequence.py": "7f3c8abb456c317bcf30ecd380bf4f2de18adbc90847a7ffc25398a48fd285bd", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/keypose_stop.py": "9e2192abf01d0033250d1235a3fbaf90bd690375687bb18257e30d00631d575e", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/keypose_trace.py": "fce7d06ace6db293a973c6c13529a7e0655996df814f0a4a6cc2dfb860dcd1a3", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/normalization.py": "5fce9ca04e286f980b5d4f3e06f011b529cb70fb9080b1d2994637d13abe5083", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/observations.py": "b83243c45bff96db3d653164fbe5c49801b07e6ba7ed6d394f6e18a1fd7dde1d", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/ood_env.py": "5a2131cea9ca1da648919b3790fd214cca245be6016195561115d0597321513b", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/planned_keypose.py": "bf5e177084c008619845c21d6a90a1ad3c1d6242ea89dea2134fa5ae2c924cec", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/policy.py": "f440e9fc39bfe81d57b334e1f807a3c219253bc185fb141ef932de715d999b24", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/policy_video.py": "88ab77abcc7d5c6b67bf110ab25f36aff88af6ea43e3bfc4284e980df109735d", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/profile.py": "f51d6c88cad12794445d5342972fe76e7378300c77be9252c59a67444ae89e2d", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/reference_act.py": "2be8bddc5c2e800e8b6d9dbb517f1b79fe903a19dca1f9c903b40f3059ec042e", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/replay_pose.py": "e81ee3cfad6cc21286e2ff4505faae031040d68562e69ab784df611f93e24b9f", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/run_sequence.py": "44a4b3c21590bf82e4dfd319f872b77a43a084e07dbf43a9e102163c6ade60ad", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/smoke.py": "c41e00fa8a8290ab80a11996d3ceb6eb0e54c3e36172e59f90ae8f294c5315a1", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/tasks.py": "621d966e1912873bdff182c2e3921b6f456d4f51ea43e46cb5f78779858a9dcf", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/train_offline.py": "02d501edc65edb4bec51b3f6cd94a11c75536aa8a5382afcbdf33259b75ede2f", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/train_resume.py": "3fc973bce5c64415f326afdcd208a5731570c03f6fee326fa250ec36b0803ac2", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/code/lim/waypoints.py": "c7a72725174850b2bcc631cc86740306adbfbdfae6bdec0e61b4f8d6b78aca99", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/tools/check_factor.py": "e2e78fc960083acc2b7f730015e4728cf3e175eaf513501fce64cc5159797680", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/tools/check_training.py": "3a14790143bb8773b4b1fb504c8b4f048777fc245c6703a3f71b0db58094770e", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/tools/expert_ceiling.py": "1b7a40ba482b471dec4e9513b50bb0046a3606a4758271fb072db9150be316f6", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/tools/factor_evaluate.py": "63b1a5f1e1add8e093080eefb461ecb15380c241b1c30f54eb68f9b614a354a7", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/tools/job_queue.py": "f2eeec8471050d5e5fcef3ca6b92ac94684c7eb88298709ff2b4e44fbbc76836", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/tools/merge_datasets.py": "2894c877be16f90b3d100216722d9d365ee986e365428d0185c0c4147edc6045", "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/tools/speed_cap.py": "51b9e7b4735932083249c3ab6f5d16a273f3b39934ae6135b0d0a6ad27292ca1" }, "jobs": 72, "restart": "forbidden; failures keep their terminal ledger", "stage": "b", "selection": { "rule": "PLAN.md \u00a71", "base": { "dense": { "30000": { "queries": 50, "execution": "seq_n8_cap95", "mean": 47.5 }, "90000": { "queries": 50, "execution": "seq_n8", "mean": 49.5 } }, "keypose": { "30000": { "queries": 50, "execution": "seq_n8_cap95", "mean": 47.0 }, "90000": { "queries": 50, "execution": "seq_n8_cap95", "mean": 52.0 } } }, "best_updates": { "dense": 90000, "keypose": 90000 }, "shared_before_extension": 90000, "extension_needed": true, "extended": { "dense": { "queries": 50, "execution": "seq_n8", "mean": 49.5 }, "keypose": { "queries": 50, "execution": "seq_n8_cap95", "mean": 50.0 } }, "extension_gained": false, "updates": 90000, "dense": { "queries": 50, "execution": "seq_n8", "mean": 49.5 }, "keypose": { "queries": 50, "execution": "seq_n8_cap95", "mean": 52.0 } }, "updates": 90000, "train_only": false, "runs": [ { "mode": "dense", "queries": 50, "updates": 90000, "seed": 106, "dataset": "/home/ghz/Work/Research/lim/artifacts/keypose-data/main/pose/trajectory.h5", "demos": 100, "samples": 10461, "data": "main", "env_id": "StackCube-v1", "witness": null, "phase_head": true }, { "mode": "dense", "queries": 50, "updates": 90000, "seed": 107, "dataset": "/home/ghz/Work/Research/lim/artifacts/keypose-data/main/pose/trajectory.h5", "demos": 100, "samples": 10461, "data": "main", "env_id": "StackCube-v1", "witness": null, "phase_head": true }, { "mode": "dense", "queries": 50, "updates": 90000, "seed": 108, "dataset": "/home/ghz/Work/Research/lim/artifacts/keypose-data/main/pose/trajectory.h5", "demos": 100, "samples": 10461, "data": "main", "env_id": "StackCube-v1", "witness": null, "phase_head": true }, { "mode": "dense", "queries": 50, "updates": 90000, "seed": 109, "dataset": "/home/ghz/Work/Research/lim/artifacts/keypose-data/main/pose/trajectory.h5", "demos": 100, "samples": 10461, "data": "main", "env_id": "StackCube-v1", "witness": null, "phase_head": true }, { "mode": "dense", "queries": 50, "updates": 90000, "seed": 110, "dataset": "/home/ghz/Work/Research/lim/artifacts/keypose-data/main/pose/trajectory.h5", "demos": 100, "samples": 10461, "data": "main", "env_id": "StackCube-v1", "witness": null, "phase_head": true }, { "mode": "dense", "queries": 50, "updates": 90000, "seed": 111, "dataset": "/home/ghz/Work/Research/lim/artifacts/keypose-data/main/pose/trajectory.h5", "demos": 100, "samples": 10461, "data": "main", "env_id": "StackCube-v1", "witness": null, "phase_head": true }, { "mode": "keypose", "queries": 50, "updates": 90000, "seed": 106, "dataset": "/home/ghz/Work/Research/lim/artifacts/keypose-data/main/pose/trajectory.h5", "demos": 100, "samples": 10461, "data": "main", "env_id": "StackCube-v1", "witness": null, "phase_head": true }, { "mode": "keypose", "queries": 50, "updates": 90000, "seed": 107, "dataset": "/home/ghz/Work/Research/lim/artifacts/keypose-data/main/pose/trajectory.h5", "demos": 100, "samples": 10461, "data": "main", "env_id": "StackCube-v1", "witness": null, "phase_head": true }, { "mode": "keypose", "queries": 50, "updates": 90000, "seed": 108, "dataset": "/home/ghz/Work/Research/lim/artifacts/keypose-data/main/pose/trajectory.h5", "demos": 100, "samples": 10461, "data": "main", "env_id": "StackCube-v1", "witness": null, "phase_head": true }, { "mode": "keypose", "queries": 50, "updates": 90000, "seed": 109, "dataset": "/home/ghz/Work/Research/lim/artifacts/keypose-data/main/pose/trajectory.h5", "demos": 100, "samples": 10461, "data": "main", "env_id": "StackCube-v1", "witness": null, "phase_head": true }, { "mode": "keypose", "queries": 50, "updates": 90000, "seed": 110, "dataset": "/home/ghz/Work/Research/lim/artifacts/keypose-data/main/pose/trajectory.h5", "demos": 100, "samples": 10461, "data": "main", "env_id": "StackCube-v1", "witness": null, "phase_head": true }, { "mode": "keypose", "queries": 50, "updates": 90000, "seed": 111, "dataset": "/home/ghz/Work/Research/lim/artifacts/keypose-data/main/pose/trajectory.h5", "demos": 100, "samples": 10461, "data": "main", "env_id": "StackCube-v1", "witness": null, "phase_head": true } ]}1"""Compact manipulation policy experiments."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""Isolated training-only ACT candidates; inference stays on the native path."""
from typing import Literal
import torchimport torch.nn.functional as Ffrom pydantic import BaseModel, ConfigDict, NonNegativeInt, PositiveFloat
class ACTOptimizationConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) method: Literal["control", "random_shift", "near_action", "deterministic"] = ( "control" ) """One isolated candidate; methods are not combined during screening.""" shift_pixels: NonNegativeInt = 4 """Symmetric replicated-image padding before integer random cropping.""" horizon_decay: PositiveFloat = 10.0 """Exponential L1 weighting time scale, in predicted actions.""" augmentation_seed: NonNegativeInt = 20260915 """Private augmentation RNG, independent of sampling and native dropout/latent RNG."""
def shift_rgb(rgb, pad, generator): """Translate each sample/camera equally across channels, without interpolation.""" if pad == 0: return rgb batch, cameras, channels, height, width = rgb.shape flat = rgb.reshape(batch * cameras, channels, height, width) padded = F.pad(flat, (pad, pad, pad, pad), mode="replicate") shifts = torch.randint( 2 * pad + 1, (batch * cameras, 2), device=rgb.device, generator=generator ) ys = ( torch.arange(height, device=rgb.device)[None, :, None] + shifts[:, 0, None, None] ) xs = ( torch.arange(width, device=rgb.device)[None, None, :] + shifts[:, 1, None, None] ) indices = torch.arange(batch * cameras, device=rgb.device)[:, None, None] # NHWC indexing keeps all channels at the same spatial displacement. return ( padded.permute(0, 2, 3, 1)[indices, ys, xs] .permute(0, 3, 1, 2) .reshape(batch, cameras, channels, height, width) )
class ACTTrainingObjective: def __init__(self, config: ACTOptimizationConfig): self.config = config self.generator = None
def compute_loss(self, agent, native, obs, actions): method = self.config.method if method == "control": return agent.compute_loss(obs=obs, action_seq=actions) if method == "random_shift": if self.generator is None: self.generator = torch.Generator(device=obs["rgb"].device) self.generator.manual_seed(self.config.augmentation_seed) obs = dict(obs) obs["rgb"] = shift_rgb(obs["rgb"], self.config.shift_pixels, self.generator) return agent.compute_loss(obs=obs, action_seq=actions) obs = dict(obs) obs["rgb"] = agent.normalize(obs["rgb"].float() / 255.0) if method == "deterministic": prediction, _ = agent.model(obs) # Same zero latent used during deployment. l1 = F.l1_loss(prediction, actions) return {"loss": l1, "l1": l1, "kl": l1.new_zeros(())} prediction, (mu, logvar) = agent.model(obs, actions) error = F.l1_loss(prediction, actions, reduction="none") weights = torch.exp( -torch.arange(actions.shape[1], device=actions.device, dtype=error.dtype) / self.config.horizon_decay ) weights = weights / weights.mean() l1 = (error * weights[None, :, None]).mean() kl = native.kl_divergence(mu, logvar)[0][0] return {"loss": l1 + agent.kl_weight * kl, "l1": l1, "kl": kl}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123"""Small ACT policy variants sharing the pinned visual and transformer components."""
import hashlibimport mathfrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Any, Literal
import numpy as npimport torchimport torch.nn.functional as Ffrom pydantic import ( BaseModel, ConfigDict, Field, NonNegativeFloat, NonNegativeInt, PositiveFloat, PositiveInt, model_validator,)from torch import nnfrom torch.utils.data import Dataset
from lim.action_encoding import ( ActionEncoding, EncodedEnvConfig, Rotation6DEnv, encoded_dimension, sixd_to_controller,)from lim.action_objective import ( ActionLossConfig, BinaryGripperEnv, BinaryGripperEnvConfig, BinaryGripperModel, BinaryGripperModelConfig, pose_reconstruction,)from lim.chunk_coordinates import ( ChunkAnchor, ChunkGripperSupervision, ChunkPadding, ChunkPoseSupervision, chunk_relative_to_world, controller_pose_targets, pose_target_contract, resolve_anchor, world_to_chunk_relative,)from lim.keypose_context import ( KeyposeContextMode, KeyposeContextModel, KeyposeContextModelConfig,)from lim.keypose_control import ( KeyposeControlConfig, KeyposeEnv, KeyposeEnvConfig, encode_keypose,)from lim.keypose_dense import ( DenseAuxiliaryHead, DenseAuxiliaryHeadConfig, read_dense_actions,)from lim.keypose_phase import ( KeyposePhaseHead, KeyposePhaseHeadConfig, read_phase_logits,)from lim.keypose_policy import FirstKeyposeAgent, FirstKeyposeAgentConfigfrom lim.keypose_stop import KeyposeStopHead, KeyposeStopHeadConfig, read_stop_logitsfrom lim.chunk_switch import ( SWITCH_HORIZON, ChunkSwitchHead, ChunkSwitchHeadConfig, read_switch_fraction,)from lim.normalization import ( NormalizationConfig, NormalizedModel, NormalizedModelConfig, checked_statistics,)
class ACTPolicyConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) method: Literal["cvae", "state_free", "flow", "chunk_relative"] = "cvae" """One independent policy intervention; cvae preserves the native agent.""" action_encoding: ActionEncoding = "controller" """Rotation6D learns ten-dimensional labels and decodes only after ensembling.""" chunk_anchor: ChunkAnchor = "chunk_start_tcp" """Chunk label frame. Identity isolates the anchor: targets become absolute world poses while the controller boundary still converts against real TCP.""" chunk_pose_supervision: ChunkPoseSupervision = "dense" """Replace only valid-slot pose labels; padding and dense normalization stay shared. Endpoint inference needs no prefix.""" chunk_gripper_supervision: ChunkGripperSupervision = "future" """Future commands, or current command repeated in valid slots; independent of pose and phase labels, with terminal padding and fitted scales preserved.""" chunk_padding: ChunkPadding = "terminal" """Out-of-range slots keep measured terminal targets, or repeat the current complete endpoint target. Valid labels and normalization are unchanged.""" chunk_normalization_population: Literal["dense", "supervised"] = "dense" """Action statistics use dense valid pairs, or one complete current target per observation for the repeated current-target recipe.""" chunk_label_offset: NonNegativeInt = 0 """Slot i supervises time t+offset+i; zero preserves every existing recipe.""" chunk_waypoint_threshold_m: PositiveFloat | None = None """AWE distance threshold (metres) for future_waypoint labels; None otherwise.""" chunk_switch_head: bool = False """Regress the current phase's remaining steps from decoder query zero.""" chunk_switch_weight: NonNegativeFloat = Field(default=1.0, allow_inf_nan=False) """L1 weight on the remaining-steps fraction when the switch head exists.""" flow_steps: PositiveInt = 8 """Euler evaluations per fresh observation for the conditional flow head.""" inference_seed: NonNegativeInt = 20260916 """Private flow inference noise stream, independent of the training RNG.""" normalization: NormalizationConfig = NormalizationConfig() """Independent training-fitted scaling; none preserves existing policies.""" state_input: Literal["full", "no_velocity", "tcp_only"] = "full" """State25 information subset, masked in both CVAE branches with capacity fixed.""" action_loss: ActionLossConfig = ActionLossConfig() """Action objective and linked inference semantics, persisted with the policy.""" keypose: KeyposeControlConfig | None = None """When set, learn next world keypose on all queries; execute the first at 20Hz.""" keypose_phase_weight: NonNegativeFloat = Field(default=0.0, allow_inf_nan=False) """Weight on six-class primitive CE from query-zero features; zero preserves the native action-only model. Labels are supervision only, never inputs.""" keypose_target_sequence: Literal["current", "future"] = "current" """Repeat the current primitive goal, or supervise each future time's goal; both variants still execute query zero with the same keypose controller.""" keypose_context: KeyposeContextMode = "none" """Optional completed-target11 input shared by prior and posterior state projections; zero and previous_target have identical trainable structure.""" keypose_stop_head: bool = False """Add independent terminal-intent logits from decoder query zero.""" keypose_stop_weight: NonNegativeFloat = Field(default=0.1, allow_inf_nan=False) """BCE weight when the stop head exists; zero retains the same head for controls.""" keypose_dense_head: bool = False """Add a dense30 auxiliary decoder projection; never executed at inference.""" keypose_dense_weight: NonNegativeFloat = Field(default=1.0, allow_inf_nan=False) """Dense group-balanced reconstruction weight; zero is the matched head control.""" chunk_phase_head: bool = False """Retain the per-query phase head even when its auxiliary loss is zero.""" chunk_phase_weight: NonNegativeFloat = Field(default=0.0, allow_inf_nan=False) """Per-query phase CE weight. Positive values also enable the head, preserving the architecture of existing checkpoints with no explicit head field."""
@property def has_chunk_phase_head(self): """Whether model construction and diagnostic labels include a phase head.""" return self.chunk_phase_head or self.chunk_phase_weight > 0
@model_validator(mode="after") def check_normalization(self): compact = ( self.chunk_label_offset > 0 or self.chunk_pose_supervision == "phase_segments" or self.chunk_switch_head ) # A Q30 future-endpoint switch arm keeps its template's zero-weight phase # head, so it differs from that template only by the switch head. phase_head_allowed = ( self.chunk_pose_supervision == "future_endpoint" and not self.chunk_label_offset and self.chunk_phase_weight == 0 ) if compact and ( self.method != "chunk_relative" or self.action_encoding != "rotation6d" or self.chunk_anchor != "chunk_start_tcp" or self.chunk_gripper_supervision != "future" or self.chunk_padding != "terminal" or self.chunk_normalization_population != "dense" or (self.has_chunk_phase_head and not phase_head_allowed) ): raise ValueError( "Compact endpoint outputs use TCP-anchored pose6D, own gripper labels, no phase head" ) if self.chunk_label_offset > 0 and self.chunk_pose_supervision != "future_endpoint": raise ValueError("Lookahead labels shift future-time endpoint supervision only") if (self.chunk_pose_supervision == "future_waypoint") != ( self.chunk_waypoint_threshold_m is not None ): raise ValueError("Exactly the waypoint supervision carries a waypoint threshold") if self.chunk_pose_supervision == "phase_segments" and not self.chunk_switch_head: raise ValueError("Phase segments always carry the switch head (weight may be zero)") if self.chunk_switch_head and ( self.chunk_pose_supervision not in ("phase_segments", "future_endpoint") or self.chunk_label_offset ): raise ValueError("The switch head supervises unshifted endpoint recipes only") if self.chunk_pose_supervision == "phase_segments" and self.chunk_label_offset: raise ValueError("Phase segments are indexed by phase, not by time offset") if self.chunk_padding == "current_target" and ( self.chunk_pose_supervision != "current_endpoint" or self.chunk_gripper_supervision != "current" ): raise ValueError( "Current-target padding requires current endpoint and gripper" ) if self.chunk_gripper_supervision != "future" and ( self.method != "chunk_relative" or self.action_encoding != "rotation6d" ): raise ValueError("Chunk gripper supervision requires chunk-relative pose6D") if self.chunk_pose_supervision != "dense" and ( self.method != "chunk_relative" or self.action_encoding != "rotation6d" ): raise ValueError( "Matched endpoint supervision requires pose6D chunk-relative targets" ) if self.has_chunk_phase_head and ( self.method != "chunk_relative" or self.action_encoding != "rotation6d" ): raise ValueError( "Chunk phase supervision requires fixed-anchor pose6D targets" ) if self.chunk_normalization_population == "supervised" and ( self.chunk_pose_supervision != "current_endpoint" or self.chunk_gripper_supervision != "current" or self.chunk_padding != "current_target" ): raise ValueError( "Supervised normalization requires repeated complete current-target endpoint labels" ) if self.keypose_dense_head and not self.keypose_stop_head: raise ValueError( "Dense auxiliary screen requires the existing stop/context policy" ) if self.keypose_stop_head and ( self.keypose is None or self.method != "cvae" or self.state_input != "full" or self.keypose_target_sequence != "current" or self.keypose_context != "previous_target" or self.keypose_phase_weight != 0 ): raise ValueError( "Stop supervision requires current previous-target full-state CVAE keypose without phase" ) if self.keypose_context != "none" and ( self.keypose is None or self.method != "cvae" or self.state_input != "full" or self.keypose_target_sequence != "current" or self.keypose_phase_weight != 0 ): raise ValueError( "Completed-goal context requires current full-state CVAE keypose without a phase head" ) if self.keypose_target_sequence == "future" and self.keypose is None: raise ValueError("Future keypose supervision requires a keypose policy") if self.keypose_phase_weight > 0 and self.keypose is None: raise ValueError("Phase classification requires a keypose policy") if self.chunk_anchor != "chunk_start_tcp" and ( self.method != "chunk_relative" or self.action_encoding != "rotation6d" ): raise ValueError( "Absolute chunk anchors are only defined for pose6D chunk_relative" ) if ( self.method == "chunk_relative" and self.action_encoding == "controller" and self.normalization.method != "none" ): raise ValueError( "Position-only chunk-relative checkpoints retain their original unnormalized contract" ) if self.keypose is not None and ( self.method != "cvae" or self.action_encoding != "rotation6d" or self.state_input != "full" or self.action_loss.method != "group_balanced" or self.normalization.method != "action_zscore" ): raise ValueError( "Keypose screen requires full-state CVAE, rotation6d, group-balanced action-zscore" ) if self.normalization.method != "none" and self.method not in ( "cvae", "chunk_relative", ): raise ValueError( "Screen normalization on the native state-conditioned CVAE" ) if self.state_input != "full" and self.method != "cvae": raise ValueError("State subsets are screened on the native CVAE") if self.action_loss.method != "native" and ( self.method not in ("cvae", "chunk_relative") or self.action_encoding != "rotation6d" or self.state_input != "full" ): raise ValueError("Screen pose action losses on full-state Rotation6D CVAE") if ( self.method == "chunk_relative" and self.action_encoding == "rotation6d" and ( self.keypose is not None or self.state_input != "full" or self.normalization.method != "action_zscore" or self.action_loss.method != "group_balanced" ) ): raise ValueError( "Pose chunk-relative screen requires full-state/group-balanced/action-zscore" ) return self
class ModelBuildConfig(BaseModel, frozen=True): model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid") native_model: Any """Newly initialized pinned DETRVAE; selected modules are reused unchanged.""" policy: ACTPolicyConfig """Validated policy variant and sampler configuration."""
class StateFreeModel(nn.Module): """Constant state tokens preserve capacity but carry no proprioceptive signal."""
def __init__(self, config: ModelBuildConfig): super().__init__() self.base = config.native_model self.state_dim = self.base.input_proj_robot_state.in_features
def forward(self, obs, actions=None): # Both the posterior and action decoder see constants, including training. # The original state values are never read; images determine batch/device. state = torch.zeros( obs["rgb"].shape[0], self.state_dim, device=obs["rgb"].device, dtype=obs["rgb"].dtype, ) return self.base({"rgb": obs["rgb"], "state": state}, actions)
class StateSubsetModel(nn.Module): """Remove selected state information without changing initialization or width."""
def __init__(self, config: ModelBuildConfig): super().__init__() self.config = config self.base = config.native_model if self.base.input_proj_robot_state.in_features != 25: raise ValueError( "State subsets require qpos9, qvel9, TCP position3/quaternion4" ) keep = torch.zeros(25, dtype=torch.bool) if config.policy.state_input == "no_velocity": keep[:9] = True keep[18:] = True elif config.policy.state_input == "tcp_only": keep[18:] = True else: raise ValueError("Full-state control must use the unwrapped native model") self.register_buffer("keep_state", keep, persistent=False)
def forward(self, obs, actions=None): # Applied after optional per-axis normalization, before posterior/decoder. # masked_fill also prevents discarded NaNs from reaching either branch. state = obs["state"].masked_fill(~self.keep_state, 0) return self.base({**obs, "state": state}, actions)
class FlowACT(nn.Module): """Conditional linear-path flow: Gaussian noise -> normalized action chunks.
Observation memory is encoded once per fresh observation. Only the action decoder is iterated, with noisy actions and continuous time as inputs. """
def __init__(self, config: ModelBuildConfig): super().__init__() native = config.native_model self.config = config.policy self.backbones = native.backbones self.input_proj = native.input_proj self.input_proj_robot_state = native.input_proj_robot_state self.transformer = native.transformer self.query_embed = native.query_embed self.action_head = native.action_head self.additional_pos_embed = native.additional_pos_embed self.num_queries = native.num_queries width = self.transformer.d_model self.action_input = nn.Linear(self.action_head.out_features, width) self.time_mlp = nn.Sequential( nn.Linear(width, width), nn.SiLU(), nn.Linear(width, width) ) self.register_buffer( "time_frequencies", torch.exp( -math.log(10000) * torch.arange(width // 2) / max(1, width // 2 - 1) ), ) self.generator = None
def encode_observation(self, obs): features, positions = [], [] for camera in range(obs["rgb"].shape[1]): feature, position = self.backbones[0](obs["rgb"][:, camera]) features.append(self.input_proj(feature[0])) positions.append(position[0]) batch = obs["rgb"].shape[0] src = torch.cat(features, dim=3).flatten(2).permute(2, 0, 1) pos = ( torch.cat(positions, dim=3).flatten(2).permute(2, 0, 1).repeat(1, batch, 1) ) proprio = self.input_proj_robot_state(obs["state"]).unsqueeze(0) # Keep the native proprioceptive position; there is no CVAE latent token. pos = torch.cat( [self.additional_pos_embed.weight[1:2, None].expand(-1, batch, -1), pos] ) src = torch.cat([proprio, src]) memory = self.transformer.encoder(src, pos=pos) return memory, pos
def velocity(self, noisy, time, memory, pos): angles = time[:, None] * self.time_frequencies[None] * 1000 time_embedding = self.time_mlp(torch.cat([angles.sin(), angles.cos()], dim=-1)) target = (self.action_input(noisy) + time_embedding[:, None]).transpose(0, 1) queries = self.query_embed.weight[:, None].expand(-1, noisy.shape[0], -1) hidden = self.transformer.decoder(target, memory, pos=pos, query_pos=queries)[ -1 ] return self.action_head(hidden.transpose(0, 1))
def training_loss(self, obs, actions): memory, pos = self.encode_observation(obs) noise = torch.randn_like(actions) time = torch.rand(actions.shape[0], device=actions.device) noisy = (1 - time[:, None, None]) * noise + time[:, None, None] * actions target = actions - noise return F.mse_loss(self.velocity(noisy, time, memory, pos), target)
def forward(self, obs): memory, pos = self.encode_observation(obs) if self.generator is None or self.generator.device != obs["rgb"].device: self.generator = torch.Generator(device=obs["rgb"].device) self.generator.manual_seed(self.config.inference_seed) batch = obs["rgb"].shape[0] action = torch.randn( batch, self.num_queries, self.action_head.out_features, device=obs["rgb"].device, generator=self.generator, ) step = 1 / self.config.flow_steps for index in range(self.config.flow_steps): time = action.new_full((batch,), index * step) action = action + step * self.velocity(action, time, memory, pos) # Match native ACT: the controller clips after temporal aggregation. return action, (None, None)
def build_policy(native, spaces, args, policy, normalization=None): fitted = checked_statistics( normalization, policy.normalization, policy.action_encoding ) if policy.action_encoding != "controller": spaces = SimpleNamespace( single_observation_space=spaces.single_observation_space, single_action_space=SimpleNamespace( shape=( encoded_dimension( spaces.single_action_space.shape[-1], policy.action_encoding ), ) ), ) agent = native.Agent(spaces, args) if policy.keypose_stop_head: # Attach to the actual native decoder before context/normalization wrappers. agent.model.action_head = KeyposeStopHead( KeyposeStopHeadConfig(action_head=agent.model.action_head) ) if policy.keypose_dense_head: agent.model.action_head = DenseAuxiliaryHead( DenseAuxiliaryHeadConfig( primary=agent.model.action_head, hidden_size=agent.model.action_head.action.in_features, ) ) if policy.keypose_context != "none": if fitted is None: raise ValueError( "Completed-goal context requires checkpoint-owned action statistics" ) agent.model = KeyposeContextModel( KeyposeContextModelConfig( model=agent.model, mode=policy.keypose_context, statistics=fitted ) ) if policy.keypose_phase_weight > 0 or policy.has_chunk_phase_head: agent.model.action_head = KeyposePhaseHead( KeyposePhaseHeadConfig( action_head=agent.model.action_head, all_queries=policy.has_chunk_phase_head, ) ) if policy.chunk_switch_head: # Outermost: it may wrap the phase head; both read the same features. agent.model.action_head = ChunkSwitchHead( ChunkSwitchHeadConfig(action_head=agent.model.action_head) ) if policy.method == "state_free": agent.model = StateFreeModel( ModelBuildConfig(native_model=agent.model, policy=policy) ) elif policy.method == "flow": agent.model = FlowACT(ModelBuildConfig(native_model=agent.model, policy=policy)) if policy.state_input != "full": agent.model = StateSubsetModel( ModelBuildConfig(native_model=agent.model, policy=policy) ) if policy.action_loss.method == "gripper_bce": agent.model = BinaryGripperModel(BinaryGripperModelConfig(model=agent.model)) if fitted is not None: if spaces.single_action_space.shape != ( len(fitted.action.center), ) or spaces.single_observation_space["state"].shape != ( len(fitted.state.center), ): raise ValueError("Fitted normalization shapes differ from the policy") agent.model = NormalizedModel( NormalizedModelConfig(model=agent.model, statistics=fitted) ) return agent
def policy_loss( agent, native, obs, actions, policy, objective, phase_labels=None, stop_labels=None, dense_labels=None, switch_labels=None,): if policy.action_loss.method != "native": if objective.config.method != "control": raise ValueError( "Action loss candidates require the control training recipe" ) obs = {**obs, "rgb": agent.normalize(obs["rgb"].float() / 255)} prediction, (mu, logvar) = agent.model(obs, actions) losses = pose_reconstruction(prediction, actions, policy.action_loss) kl = native.kl_divergence(mu, logvar)[0][0] result = { "loss": losses["reconstruction"] + agent.kl_weight * kl, "kl": kl, **losses, } if policy.keypose_phase_weight > 0: logits = read_phase_logits(agent) if ( phase_labels is None or phase_labels.dtype != torch.long or phase_labels.shape != logits.shape[:1] or not ((phase_labels >= 0) & (phase_labels < 6)).all() ): raise ValueError( "Expected one integer primitive label in [0, 5] per observation" ) phase_ce = F.cross_entropy(logits, phase_labels) result.update( loss=result["loss"] + policy.keypose_phase_weight * phase_ce, phase_ce=phase_ce, phase_accuracy=(logits.argmax(-1) == phase_labels).float().mean(), ) if policy.has_chunk_phase_head: logits = read_phase_logits(agent) if ( phase_labels is None or phase_labels.dtype != torch.long or phase_labels.shape != prediction.shape[:2] or logits.shape != (*prediction.shape[:2], 6) or not ( (phase_labels == -100) | ((phase_labels >= 0) & (phase_labels < 6)) ).all() or not (phase_labels[:, 0] >= 0).all() ): raise ValueError( "Expected valid future phase labels and -100 only for padding" ) phase_ce = F.cross_entropy( logits.flatten(0, 1), phase_labels.flatten(), ignore_index=-100 ) valid = phase_labels != -100 # Keep CE as a diagnostic at weight zero, but remove its graph from # the objective entirely: unused head parameters must get no gradient. if policy.chunk_phase_weight > 0: result["loss"] = result["loss"] + policy.chunk_phase_weight * phase_ce result.update( phase_ce=phase_ce, phase_accuracy=(logits.argmax(-1)[valid] == phase_labels[valid]) .float() .mean(), phase_query0_accuracy=(logits[:, 0].argmax(-1) == phase_labels[:, 0]) .float() .mean(), ) if policy.keypose_stop_head: logits = read_stop_logits(agent) if ( stop_labels is None or not stop_labels.is_floating_point() or stop_labels.shape != logits.shape or logits.ndim != 1 or not ((stop_labels == 0) | (stop_labels == 1)).all() ): raise ValueError("Expected one float binary stop label per observation") stop_bce = F.binary_cross_entropy_with_logits(logits, stop_labels) result.update( loss=result["loss"] + policy.keypose_stop_weight * stop_bce, stop_bce=stop_bce, stop_accuracy=((logits >= 0) == stop_labels.bool()).float().mean(), stop_predicted_positive=(logits >= 0).float().mean(), ) if policy.chunk_switch_head: fraction = read_switch_fraction(agent) if ( switch_labels is None or not switch_labels.is_floating_point() or switch_labels.shape != fraction.shape or not ((switch_labels > 0) & (switch_labels <= 1)).all() ): raise ValueError("Expected one remaining-steps fraction in (0, 1] per observation") switch_l1 = (fraction - switch_labels).abs().mean() # At weight zero the head stays a diagnostic: no graph, no gradient. if policy.chunk_switch_weight > 0: result["loss"] = result["loss"] + policy.chunk_switch_weight * switch_l1 result["switch_l1"] = switch_l1.detach() if policy.keypose_dense_head: dense_prediction = read_dense_actions(agent) if ( dense_labels is None or dense_labels.shape != prediction.shape or dense_prediction.shape != prediction.shape or not torch.isfinite(dense_labels).all() ): raise ValueError( "Expected finite normalized dense labels matching the original Q30 horizon" ) dense_loss = pose_reconstruction( dense_prediction, dense_labels, ActionLossConfig(method="group_balanced"), ) result.update( loss=result["loss"] + policy.keypose_dense_weight * dense_loss["reconstruction"], **{f"dense_{key}": value for key, value in dense_loss.items()}, ) return result if policy.method != "flow": return objective.compute_loss(agent, native, obs, actions) obs = {**obs, "rgb": agent.normalize(obs["rgb"].float() / 255)} loss = agent.model.training_loss(obs, actions) return {"loss": loss, "flow_mse": loss}
class ChunkDatasetConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) dataset: Any """Pinned native preprocessed StackCube dataset with state25 and delta actions.""" action_encoding: ActionEncoding = "controller" """Existing position-only controller labels, or dense fixed-reference pose6D.""" source: Path | None = None """Pose6D H5 used to verify robot-root axes in every saved state.""" chunk_anchor: ChunkAnchor = "chunk_start_tcp" """Label origin; identity makes every target an absolute world pose.""" phase_supervision: bool = False """Return each valid future action's primitive label; ignore padded labels.""" chunk_pose_supervision: ChunkPoseSupervision = "dense" """Only valid-slot pose labels change; phase and fitted scales do not.""" chunk_gripper_supervision: ChunkGripperSupervision = "future" """Future commands or current command repeated in valid slots only.""" chunk_padding: ChunkPadding = "terminal" """Measured terminal pose/last gripper, or repeat the current complete target.""" chunk_normalization_population: Literal["dense", "supervised"] = "dense" """Action statistics use dense valid pairs, or one complete current target per observation for the repeated current-target recipe.""" chunk_label_offset: NonNegativeInt = 0 """Slot i supervises time t+offset+i; zero preserves every existing recipe.""" chunk_waypoint_threshold_m: PositiveFloat | None = None """AWE distance threshold for future_waypoint labels.""" switch_supervision: bool = False """Also return the current primitive's remaining-steps fraction."""
@model_validator(mode="after") def check_supervision(self): if self.chunk_padding == "current_target" and ( self.chunk_pose_supervision != "current_endpoint" or self.chunk_gripper_supervision != "current" ): raise ValueError( "Current-target padding requires current endpoint and gripper" ) if ( self.chunk_gripper_supervision != "future" and self.action_encoding != "rotation6d" ): raise ValueError("Chunk gripper supervision requires pose6D data") if ( self.chunk_pose_supervision != "dense" and self.action_encoding != "rotation6d" ): raise ValueError( "Endpoint labels require pose6D chunk-relative data" ) if self.chunk_normalization_population == "supervised" and ( self.chunk_pose_supervision != "current_endpoint" or self.chunk_gripper_supervision != "current" or self.chunk_padding != "current_target" ): raise ValueError( "Supervised normalization requires repeated complete current-target endpoint labels" ) return self
def remaining_fraction(ends, labels): """Steps left in each observation's primitive, min(steps, horizon)/horizon.""" remaining = torch.from_numpy(ends).long()[labels] - torch.arange(len(labels)) if not (remaining >= 1).all(): raise ValueError("Every observation must have at least one remaining step") return remaining.clamp(max=SWITCH_HORIZON).float() / SWITCH_HORIZON
class ChunkRelativeDataset(Dataset): """Encode actual controller goals relative to each query's current TCP.
StackCube panda_wristcam state = qpos9, qvel9, world TCP pose7. The root orientation is identity and pd_ee_delta_pos uses scale 0.1 m. Positions at future steps are supervised data only, never policy inputs. """
def __init__(self, config: ChunkDatasetConfig): self.config = config self.dataset = config.dataset self.phase_chunks = [] self.waypoint_counts = [] if config.phase_supervision and config.action_encoding != "rotation6d": raise ValueError("Chunk phase labels require pose6D data") for trajectory in self.dataset.trajectories["observations"]: if trajectory["state"].shape[-1] != 25: raise ValueError("Chunk labels require the audited state25 layout") if config.action_encoding == "rotation6d": import h5py
if config.source is None: raise ValueError( "Pose chunk-relative labels require source H5 root-frame verification" ) self.chunks = [] self.world_targets = [] self.switch_labels = [] populations = [] with h5py.File(config.source) as data: names = sorted(data, key=lambda n: int(n.split("_")[-1]))[ : self.dataset.num_traj ] if len(names) != self.dataset.num_traj: raise ValueError( "Source trajectory count differs from the native dataset" ) for name, actions, obs in zip( names, self.trajectories["actions"], self.trajectories["observations"], strict=True, ): tcp = obs["state"][:, 18:25] if actions.shape[-1] != 7 or len(tcp) != len(actions) + 1: raise ValueError( "Expected unencoded pose actions and a terminal TCP" ) stored_tcp = torch.from_numpy(data[name]["obs/extra/tcp_pose"][:]) torch.testing.assert_close(tcp, stored_tcp, atol=0, rtol=0) roots = data[name]["env_states/articulations/panda_wristcam"][ :, 3:7 ] np.testing.assert_allclose( roots, np.tile([1, 0, 0, 0], (len(roots), 1)), atol=1e-5 ) goals = controller_pose_targets(actions, tcp[:-1]) terminal = encode_keypose(tcp[-1], actions[-1, -1])[None] goals = torch.cat([goals, terminal]) times = ( torch.arange(len(actions))[:, None] + config.chunk_label_offset + torch.arange(self.num_queries)[None] ) valid = times < len(actions) if config.chunk_pose_supervision == "future_waypoint": from lim.waypoints import next_waypoint, select_waypoints
waypoints = select_waypoints( goals[: len(actions), :3].numpy(), config.chunk_waypoint_threshold_m, actions[:, -1].numpy(), ) self.waypoint_counts.append((len(waypoints), len(actions))) following = torch.from_numpy( next_waypoint(len(actions), waypoints) ) if ( config.phase_supervision or config.chunk_pose_supervision not in ("dense", "future_waypoint") ): from lim.keypose_phase import KEYPOSE_PHASE_NAMES
key = data[name]["keyframes"] labels = torch.from_numpy( key["action_keyframe_index"][:] ).long() starts, ends = key["start_action"][:], key["end_action"][:] # Six-class phase labels exist only for the canonical # StackCube primitives; other tasks' experts record # their own primitive list, used for endpoints alone. segments = len(starts) if ( ( config.phase_supervision and tuple(key["name"].asstr()[:]) != KEYPOSE_PHASE_NAMES ) or segments < 1 or starts.shape != (segments,) or ends.shape != (segments,) or starts[0] != 0 or ends[-1] != len(actions) or np.any(ends <= starts) or not np.array_equal(starts[1:], ends[:-1]) or not np.array_equal( labels.numpy(), np.repeat(np.arange(segments), ends - starts) ) ): raise ValueError( "Expected aligned canonical primitive indices" ) phase = labels[times.clamp(max=len(actions) - 1)].clone() phase[~valid] = -100 self.phase_chunks.append(phase) relative = world_to_chunk_relative( goals[times.clamp(max=len(actions))], resolve_anchor(tcp[:-1, None], config.chunk_anchor), ) # The default population preserves the original dense labels # and physical loss weights across supervision variants. if config.chunk_normalization_population == "dense": populations.append(relative[valid]) if config.chunk_pose_supervision == "future_waypoint": replacement = world_to_chunk_relative( goals[following[times.clamp(max=len(actions) - 1)]], resolve_anchor(tcp[:-1, None], config.chunk_anchor), ) relative[valid] = torch.cat( [replacement[valid][:, :9], relative[valid][:, -1:]], -1 ) elif config.chunk_pose_supervision != "dense": poses = torch.from_numpy(key["target_pose_world"][:]) grippers = torch.from_numpy(key["gripper_command"][:]) if ( poses.shape != (segments, 7) or grippers.shape != (segments,) or not torch.isfinite(poses).all() or not torch.isfinite(grippers).all() or not torch.equal(grippers[labels], actions[:, -1]) ): raise ValueError( "Endpoint and dense primitive labels disagree" ) endpoints = encode_keypose(poses, grippers) if config.chunk_pose_supervision == "phase_segments": if self.num_queries != 2: raise ValueError("Phase segments require exactly two queries") segments = torch.stack( [labels, (labels + 1).clamp(max=5)], -1 ) # Both slots carry their own primitive gripper command. relative = world_to_chunk_relative( endpoints[segments], resolve_anchor(tcp[:-1, None], config.chunk_anchor), ) self.switch_labels.append(remaining_fraction(ends, labels)) self.chunks.append(relative) self.world_targets.append(goals) continue if config.switch_supervision: self.switch_labels.append(remaining_fraction(ends, labels)) endpoint_indices = ( labels[times.clamp(max=len(actions) - 1)] if config.chunk_pose_supervision == "future_endpoint" else labels[:, None].expand_as(times) ) replacement = world_to_chunk_relative( endpoints[endpoint_indices], resolve_anchor(tcp[:-1, None], config.chunk_anchor), ) # Preserve original dense terminal padding and every # future gripper command, including in current_endpoint. relative[valid] = torch.cat( [replacement[valid][:, :9], relative[valid][:, -1:]], -1 ) if config.chunk_gripper_supervision == "current": # Change the supervised gripper timing only. The current # command is not the phase-end command and never replaces # the terminal padding or dense normalization population. repeated = actions[:, -1, None].expand_as(times) relative[..., -1][valid] = repeated[valid] if config.chunk_padding == "current_target": # Query zero always exists and already has the complete # current endpoint. Only replace out-of-range slots. repeated = relative[:, :1].expand_as(relative) relative[~valid] = repeated[~valid] if config.chunk_normalization_population == "supervised": # One target per original observation, independent of Q # and padding, matching the old KeyposeDataset weighting. populations.append(relative[:, 0]) self.chunks.append(relative) self.world_targets.append(goals) self.normalization_actions = torch.cat(populations) self.target_contract = pose_target_contract( config.chunk_anchor, config.chunk_pose_supervision, config.chunk_gripper_supervision, config.chunk_padding, config.chunk_normalization_population, config.chunk_label_offset, config.chunk_waypoint_threshold_m, ) all_chunks = torch.cat(self.chunks) tensors = { "sample_indices": torch.tensor(self.dataset.slices), "pose_labels": all_chunks[..., :9], "gripper_labels": all_chunks[..., -1], "normalization_population": self.normalization_actions, } if self.phase_chunks: tensors["phase_labels"] = torch.cat(self.phase_chunks) if self.switch_labels: tensors["switch_labels"] = torch.cat(self.switch_labels) self.supervision_audit = { "pose_supervision": config.chunk_pose_supervision, "gripper_supervision": config.chunk_gripper_supervision, "samples": len(self.dataset.slices), "normalization_samples": len(self.normalization_actions), **{ f"{name}_sha256": hashlib.sha256( tensor.contiguous().numpy().tobytes() ).hexdigest() for name, tensor in tensors.items() }, **( { "waypoints": sum(w for w, _ in self.waypoint_counts), "actions": sum(n for _, n in self.waypoint_counts), "waypoint_threshold_m": config.chunk_waypoint_threshold_m, } if self.waypoint_counts else {} ), }
def __getattr__(self, name): return getattr(self.dataset, name)
def __len__(self): return len(self.dataset)
def __getitem__(self, index): trajectory, start = self.dataset.slices[index] if self.config.action_encoding == "rotation6d": return { "observations": { k: v[start] for k, v in self.trajectories["observations"][trajectory].items() }, "actions": self.chunks[trajectory][start], **( {"phase": self.phase_chunks[trajectory][start]} if self.config.phase_supervision else {} ), **( {"switch": self.switch_labels[trajectory][start]} if self.switch_labels else {} ), } sample = self.dataset[index] positions = self.dataset.trajectories["observations"][trajectory]["state"][ :, 18:21 ] length = len(self.dataset.trajectories["actions"][trajectory]) if len(positions) != length + 1: raise ValueError("Expected terminal TCP observation for stationary padding") times = torch.arange(start, start + self.dataset.num_queries).clamp(max=length) actions = sample["actions"].clone() # Native labels contain already bounded normalized delta commands. Do not # clip the resulting chunk targets: legitimate offsets can exceed +/-1. actions[:, :3] += (positions[times] - positions[start]) / 0.1 return {"observations": sample["observations"], "actions": actions}
class TargetTransportConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) wrapped: Any """Agent or environment at the existing native evaluator boundary.""" action_encoding: ActionEncoding = "controller" """Position-only scaled world goals, or world xyz plus 6D rotation goals.""" chunk_anchor: ChunkAnchor = "chunk_start_tcp" """Frame the model's output is expressed in; must match its training labels."""
class TargetFrameAgent: """Express all predicted TCP goals in one frame before native ensembling."""
def __init__(self, config: TargetTransportConfig): self.config = config self.wrapped = config.wrapped
def __getattr__(self, name): return getattr(self.wrapped, name)
def get_action(self, obs): target = self.wrapped.get_action(obs).clone() if self.config.action_encoding == "rotation6d": # Restore with the SAME frame the labels were written in. return chunk_relative_to_world( target, resolve_anchor(obs["state"][:, None, 18:25], self.config.chunk_anchor), ) if self.config.chunk_anchor != "chunk_start_tcp": raise ValueError("Absolute anchors require the pose6D encoding") target[:, :, :3] += obs["state"][:, None, 18:21] / 0.1 return target
class TargetFrameEnv: """Convert the ensembled goal to the current controller delta exactly once."""
def __init__(self, config: TargetTransportConfig): self.config = config self.wrapped = config.wrapped self.current_tcp = None if config.action_encoding == "rotation6d": import gymnasium as gym
self.action_space = gym.spaces.Box( -np.inf, np.inf, (self.wrapped.num_envs, 10), dtype=np.float32 ) self.single_action_space = gym.spaces.Box( -np.inf, np.inf, (10,), dtype=np.float32 )
def __getattr__(self, name): return getattr(self.wrapped, name)
def remember(self, observation): self.current_tcp = np.array(observation["state"][:, 18:25], copy=True)
def reset(self): observation, info = self.wrapped.reset() self.remember(observation) return observation, info
def step(self, target): if self.config.action_encoding == "rotation6d": delta = world_to_chunk_relative( torch.as_tensor(target), torch.as_tensor(self.current_tcp) ) action = sixd_to_controller(delta).numpy() else: action = np.array(target, copy=True) action[:, :3] -= self.current_tcp[:, :3] / 0.1 result = self.wrapped.step(action) self.remember(result[0]) return result
def evaluation_transport(agent, env, policy): if policy.keypose is not None: return ( FirstKeyposeAgent(FirstKeyposeAgentConfig(agent=agent)), KeyposeEnv(KeyposeEnvConfig(env=env, control=policy.keypose)), ) if policy.method == "chunk_relative": return ( TargetFrameAgent( TargetTransportConfig( wrapped=agent, action_encoding=policy.action_encoding, chunk_anchor=policy.chunk_anchor, ) ), # The environment converts world goals against the real measured TCP # under every anchor mode; that boundary is physical, not a label frame. TargetFrameEnv( TargetTransportConfig( wrapped=env, action_encoding=policy.action_encoding ) ), ) if policy.action_loss.method == "gripper_bce": env = BinaryGripperEnv(BinaryGripperEnvConfig(env=env)) if policy.action_encoding == "rotation6d": return agent, Rotation6DEnv(EncodedEnvConfig(env=env)) return agent, env1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677"""Invertible action coordinates with one shared controller contract."""
from typing import Literal
import numpy as npfrom scipy.spatial.transform import Rotation
ActionFrame = Literal["absolute", "tcp", "target"]POSITION_SCALE = 0.1# ManiSkill 3.0.1 PDEEPoseController scales by config.rot_lower (-0.1).ROTATION_SCALE = -0.1
def tcp_rotation(tcp: np.ndarray) -> Rotation: # SAPIEN exposes wxyz; scipy expects xyzw. return Rotation.from_quat(tcp[..., [4, 5, 6, 3]])
def reference_position( frame: ActionFrame, tcp: np.ndarray, target: np.ndarray) -> np.ndarray: if frame == "absolute": return np.zeros_like(tcp[..., :3]) if frame == "tcp": return tcp[..., :3] if frame == "target": return target raise ValueError(frame)
def controller_targets( tcp: np.ndarray, actions: np.ndarray) -> tuple[np.ndarray, np.ndarray]: position = tcp[..., :3] + actions[..., :3] * POSITION_SCALE raw_rotation = actions[..., 3:6] raw_rotation = raw_rotation / np.maximum( np.linalg.norm(raw_rotation, axis=-1, keepdims=True), 1 ) delta = Rotation.from_euler("XYZ", raw_rotation * ROTATION_SCALE) rotation = (delta * tcp_rotation(tcp)).as_matrix() return position, rotation
def encode_chunk(position, rotation, gripper, current_tcp, target, frame: ActionFrame): anchor = reference_position(frame, current_tcp, target) pos = (position - anchor) / POSITION_SCALE relative_rotation = tcp_rotation(current_tcp).as_matrix().T @ rotation rot6d = relative_rotation[..., :, :2].reshape(*relative_rotation.shape[:-2], 6) return np.concatenate([pos, rot6d, gripper[..., None]], axis=-1).astype(np.float32)
def prediction_to_world( prediction: np.ndarray, tcp: np.ndarray, target: np.ndarray, frame: ActionFrame): position = prediction[:3] * POSITION_SCALE + reference_position(frame, tcp, target) columns = prediction[3:9].reshape(3, 2) x = columns[:, 0] / max(np.linalg.norm(columns[:, 0]), 1e-8) y = columns[:, 1] - x * np.dot(x, columns[:, 1]) y /= max(np.linalg.norm(y), 1e-8) relative = np.stack([x, y, np.cross(x, y)], axis=1) current = tcp_rotation(tcp) desired = current * Rotation.from_matrix(relative) return position, desired.as_matrix(), float(prediction[9])
def world_to_controller(position, rotation, gripper, tcp): current = tcp_rotation(tcp) desired = Rotation.from_matrix(rotation) delta = (desired * current.inv()).as_euler("XYZ") / ROTATION_SCALE translation = (position - tcp[:3]) / POSITION_SCALE return np.clip(np.r_[translation, delta, gripper], -1, 1).astype(np.float32)
def decode_action(prediction, tcp, target, frame: ActionFrame): return world_to_controller( *prediction_to_world(prediction, tcp, target, frame), tcp )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120"""Continuous 6D rotation targets, distinct from the low-level controller ABI."""
from typing import Any, Literal
import gymnasium as gymimport numpy as npimport torchfrom mani_skill.utils.geometry.rotation_conversions import ( euler_angles_to_matrix, matrix_to_euler_angles,)from pydantic import BaseModel, ConfigDict
ActionEncoding = Literal["controller", "rotation6d"]ROTATION_SCALE = -0.1 # Installed ManiSkill 3.0.1 CPU PDEEPoseController.SIXD_SCALE = 0.1 # Affine label scaling; zero is the identity rotation.
def encoded_dimension(controller_dimension, encoding): if encoding == "controller": return controller_dimension if encoding != "rotation6d" or controller_dimension != 7: raise ValueError("Rotation6D requires the seven-dimensional pose controller") return 10
def matrix_to_sixd(matrix): identity = torch.eye(3, dtype=matrix.dtype, device=matrix.device)[:, :2] return ((matrix[..., :, :2] - identity) / SIXD_SCALE).flatten(-2)
def sixd_to_matrix(sixd): if not torch.isfinite(sixd).all(): raise ValueError("Nonfinite 6D rotation") identity = torch.eye(3, dtype=sixd.dtype, device=sixd.device) columns = sixd.reshape(*sixd.shape[:-1], 3, 2) * SIXD_SCALE + identity[:, :2] first, second = columns[..., 0], columns[..., 1] norm = torch.linalg.vector_norm(first, dim=-1, keepdim=True) x = torch.where(norm > 1e-6, first / norm.clamp(min=1e-6), identity[:, 0]) second = second - (second * x).sum(-1, keepdim=True) * x norm = torch.linalg.vector_norm(second, dim=-1, keepdim=True) # Undefined zero/collinear network outputs get a deterministic orthogonal basis. basis = identity[x.abs().argmin(-1)] fallback = basis - (basis * x).sum(-1, keepdim=True) * x fallback = fallback / torch.linalg.vector_norm(fallback, dim=-1, keepdim=True) y = torch.where(norm > 1e-6, second / norm.clamp(min=1e-6), fallback) return torch.stack([x, y, torch.linalg.cross(x, y, dim=-1)], dim=-1)
def controller_to_sixd(actions): if actions.shape[-1] != 7: raise ValueError("Expected seven-dimensional controller commands") rotation = actions[..., 3:6] rotation = rotation / torch.linalg.vector_norm( rotation, dim=-1, keepdim=True ).clamp(min=1) matrix = euler_angles_to_matrix(rotation * ROTATION_SCALE, "XYZ") return torch.cat([actions[..., :3], matrix_to_sixd(matrix), actions[..., -1:]], -1)
def sixd_to_controller(actions): if actions.shape[-1] != 10 or not torch.isfinite(actions).all(): raise ValueError("Expected finite ten-dimensional policy actions") matrix = sixd_to_matrix(actions[..., 3:9]) # A 0.2-rad SO(3) ball avoids gimbal lock and contains all valid controller # rotations: Euler norm<=0.1 implies angle<=sqrt(3)*0.1. Do not cap at0.1: # some valid compound Euler commands have a geodesic angle slightly above0.1. from mani_skill.utils.geometry.rotation_conversions import ( axis_angle_to_matrix, matrix_to_axis_angle, )
vector = matrix_to_axis_angle(matrix) angle = torch.linalg.vector_norm(vector, dim=-1, keepdim=True) bounded = axis_angle_to_matrix(vector * (0.2 / angle.clamp(min=1e-8)).clamp(max=1)) euler = matrix_to_euler_angles(bounded, "XYZ") / ROTATION_SCALE euler = euler / torch.linalg.vector_norm(euler, dim=-1, keepdim=True).clamp(min=1) return torch.cat([actions[..., :3], euler, actions[..., -1:]], -1)
def encode_dataset_actions(dataset, encoding): if encoding == "controller": return dataset if encoding != "rotation6d" or not dataset.delta_control: raise ValueError("Expected unnormalized delta-control demonstration labels") # Precompute once. RGB, sample ordering, original H5, and temporal slices stay intact. dataset.trajectories["actions"] = [ controller_to_sixd(a) for a in dataset.trajectories["actions"] ] dataset.pad_action_arm = torch.zeros(9) return dataset
class EncodedEnvConfig(BaseModel, frozen=True): model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid") env: Any """Native evaluator transport; step receives ensembled policy coordinates."""
class Rotation6DEnv: def __init__(self, config: EncodedEnvConfig): self.config = config if config.env.action_space.shape[-1] != 7: raise ValueError( "Rotation6D transport requires a seven-dimensional controller" ) self.action_space = gym.spaces.Box( -np.inf, np.inf, (config.env.num_envs, 10), dtype=np.float32 ) self.single_action_space = gym.spaces.Box( -np.inf, np.inf, (10,), dtype=np.float32 )
def __getattr__(self, name): return getattr(self.config.env, name)
def step(self, actions): # Called AFTER the pinned evaluator averages overlapping 10D predictions. command = sixd_to_controller(torch.as_tensor(actions)).numpy() return self.config.env.step(command)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159"""Pose ACT loss groups and binary-gripper inference semantics."""
from typing import Any, Literal
import numpy as npimport torchimport torch.nn.functional as Ffrom pydantic import BaseModel, ConfigDict, PositiveFloat, model_validatorfrom torch import nn
class ActionLossConfig(BaseModel, frozen=True): model_config = ConfigDict( extra="forbid", use_attribute_docstrings=True, allow_inf_nan=False ) method: Literal["native", "gripper_bce", "group_balanced"] = "native" """Native 3:6:1 L1; 3:6:1 with gripper BCE; or equal means of the three L1 groups.""" position_axis_weights: tuple[PositiveFloat, PositiveFloat, PositiveFloat] = ( 1.0, 1.0, 1.0, ) """XYZ absolute-error weights before averaging in group_balanced only.
Errors are in the coordinates supplied to the loss, including any fitted normalization; this changes no labels, normalization or inference decoding. """
@model_validator(mode="after") def check_position_weights(self): if self.method != "group_balanced" and self.position_axis_weights != ( 1.0, 1.0, 1.0, ): raise ValueError("Non-default position weights require group_balanced") return self
def pose_reconstruction(prediction, actions, config: ActionLossConfig): if prediction.shape != actions.shape or actions.shape[-1] != 10: raise ValueError( "Pose objectives require matching ten-dimensional action chunks" ) position = F.l1_loss(prediction[..., :3], actions[..., :3]) rotation = F.l1_loss(prediction[..., 3:9], actions[..., 3:9]) groups = {"position_l1": position, "rotation_l1": rotation} if config.method == "gripper_bce": labels = (actions[..., -1] + 1) / 2 gripper = F.binary_cross_entropy_with_logits(prediction[..., -1], labels) reconstruction = 0.3 * position + 0.6 * rotation + 0.1 * gripper groups["gripper_bce"] = gripper else: gripper = F.l1_loss(prediction[..., -1], actions[..., -1]) groups["gripper_l1"] = gripper if config.method == "group_balanced": # Reuse the original tensor/graph at the default, preserving the # exact historical loss and gradients rather than multiplying by 1. weighted_position = position if config.position_axis_weights != (1.0, 1.0, 1.0): weighted_position = ( (prediction[..., :3] - actions[..., :3]).abs() * prediction.new_tensor(config.position_axis_weights) ).mean() groups["weighted_position_l1"] = weighted_position reconstruction = (weighted_position + rotation + gripper) / 3 else: reconstruction = F.l1_loss(prediction, actions) return {"reconstruction": reconstruction, **groups}
def validate_binary_gripper(dataset): """Validate every unpadded training label once; padding holds its final label.""" for actions in dataset.trajectories["actions"]: gripper = actions[..., -1] if not torch.all((gripper == -1) | (gripper == 1)): raise ValueError("Binary gripper supervision requires exactly -1/+1 labels")
class BinaryGripperModelConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) model: Any """Native CVAE; the last output coordinate is a logit during training."""
class BinaryGripperModel(nn.Module): def __init__(self, config: BinaryGripperModelConfig): super().__init__() self.config = config self.base = config.model
def forward(self, obs, actions=None): prediction, latent = self.base(obs, actions) if actions is None: # Native temporal aggregation averages 2*p(open)-1, equivalent to # averaging probabilities. Do not threshold each chunk in isolation. prediction = torch.cat( [prediction[..., :-1], 2 * prediction[..., -1:].sigmoid() - 1], dim=-1 ) return prediction, latent
class BinaryGripperEnvConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) env: Any """Physical environment receiving controller commands after temporal averaging."""
class BinaryGripperEnv: def __init__(self, config: BinaryGripperEnvConfig): self.config = config self.commands = 0 self.open_commands = 0 self.close_commands = 0 self.switches = 0 self.previous_gripper = None
def __getattr__(self, name): return getattr(self.config.env, name)
def reset(self, *args, **kwargs): self.previous_gripper = None return self.config.env.reset(*args, **kwargs)
def step(self, action): command = np.array(action, copy=True) score = command[..., -1] if not np.isfinite(score).all(): raise ValueError("Nonfinite ensembled gripper probability") gripper = np.where(score >= 0, 1.0, -1.0) command[..., -1] = gripper # p(open)>=0.5 opens, including exact ties. self.commands += gripper.size self.open_commands += int((gripper == 1).sum()) self.close_commands += int((gripper == -1).sum()) if self.previous_gripper is not None: self.switches += int( ( np.isfinite(self.previous_gripper) & (self.previous_gripper != gripper) ).sum() ) result = self.config.env.step(command) # Vector SAME_STEP autoreset starts a new episode after this last command. done = np.asarray(result[2]) | np.asarray(result[3]) self.previous_gripper = np.where(done, np.nan, gripper) return result
def diagnostics(self): return { "commands": self.commands, "open_commands": self.open_commands, "close_commands": self.close_commands, "within_episode_switches": self.switches, "rule": "average p(open) with native weights; >=0.5 opens; no hysteresis", }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236"""Dense pose targets with one fixed reference per observation/chunk."""
from typing import Literal
import torchfrom mani_skill.utils.geometry.rotation_conversions import quaternion_to_matrix
from lim.action_encoding import controller_to_sixd, matrix_to_sixd, sixd_to_matrix
RELATIVE_POSE_CONTRACT = { "version": "chunk_start_pose6d_v1", "position": "(world_command_target - observed_chunk_start_tcp) / 0.1", "rotation": "scaled6d(R_world_command_target @ R_chunk_start_tcp.T)", "gripper": "original continuous command, not a relative offset", "target_source": "each saved pre-action TCP composed with its own controller command", "padding": "terminal measured TCP pose and last gripper command", "normalization_population": "all valid anchor/future-target pairs, no terminal padding",}
ABSOLUTE_POSE_CONTRACT = { "version": "absolute_world_pose6d_v1", "position": "world_command_target / 0.1, no anchor subtraction", "rotation": "scaled6d(R_world_command_target), no anchor rotation removed", "gripper": "original continuous command, not a relative offset", "target_source": "each saved pre-action TCP composed with its own controller command", "padding": "terminal measured TCP pose and last gripper command", "normalization_population": "all valid future targets, no terminal padding", "isolation": "identical to chunk_start_pose6d_v1 except the label anchor; the" " controller boundary still converts against the real measured TCP",}
ChunkAnchor = Literal["chunk_start_tcp", "identity"]ChunkPoseSupervision = Literal[ "dense", "future_endpoint", "current_endpoint", "phase_segments", "future_waypoint"]ChunkGripperSupervision = Literal["future", "current"]ChunkPadding = Literal["terminal", "current_target"]
def pose_target_contract( anchor: ChunkAnchor, supervision: ChunkPoseSupervision, gripper: ChunkGripperSupervision = "future", padding: ChunkPadding = "terminal", normalization_population: Literal["dense", "supervised"] = "dense", label_offset: int = 0, waypoint_threshold_m: float | None = None,): """Persist target semantics for the audited StackCube world-frame dataset.
An identity anchor keeps coordinates in the stored TCP/keyframe frame; that frame is world in this simulator, not a universal property of absolute poses. Existing dense-population recipes retain their checkpoint contract exactly. """ if anchor not in ("chunk_start_tcp", "identity"): raise ValueError(f"Unknown chunk anchor mode: {anchor}") if (supervision == "future_waypoint") != (waypoint_threshold_m is not None): raise ValueError("Exactly the waypoint supervision carries a waypoint threshold") if supervision == "future_waypoint": if (anchor, gripper, padding, normalization_population, label_offset) != ( "chunk_start_tcp", "future", "terminal", "dense", 0 ): raise ValueError("Waypoint labels use the TCP anchor and default label fields") return { **RELATIVE_POSE_CONTRACT, "version": f"chunk_start_pose6d_future_waypoint_eta{waypoint_threshold_m:g}_v1", "pose_supervision": supervision, "waypoint_threshold_m": waypoint_threshold_m, "target_source": "dense controller target at the first AWE waypoint strictly after each future action time; waypoints by dynamic programming on target positions with gripper changes forced, the last action maps to itself", "gripper": "original future dense gripper command at each slot, unchanged", "normalization_population": "original dense valid anchor/future-target pairs, no terminal padding", } if supervision == "phase_segments": if (anchor, gripper, padding, normalization_population, label_offset) != ( "chunk_start_tcp", "future", "terminal", "dense", 0 ): raise ValueError("Phase segments use the TCP anchor and default label fields") return { **RELATIVE_POSE_CONTRACT, "version": "chunk_start_pose6d_phase_segments_v1", "pose_supervision": supervision, "target_source": "slot0 current primitive endpoint, slot1 next primitive endpoint (last primitive repeats)", "gripper": "each slot carries its own primitive gripper command", "padding": "none; both slots always exist", "switch": "remaining steps in the current primitive, min(steps,30)/30, from decoder query zero", "normalization_population": "frozen statistics from a completed training; never refit", } if label_offset: if label_offset < 0 or supervision != "future_endpoint" or anchor != "chunk_start_tcp": raise ValueError("Lookahead offsets apply to TCP-anchored future endpoints") original = pose_target_contract( anchor, supervision, gripper, padding, normalization_population ) return { **original, "version": original["version"] + f"_lookahead{label_offset}_v1", "label_offset": label_offset, "target_source": f"primitive endpoint and gripper at time t+{label_offset}+i", "normalization_population": "frozen statistics from a completed training; never refit", } if normalization_population == "supervised": if ( supervision != "current_endpoint" or gripper != "current" or padding != "current_target" ): raise ValueError( "Supervised normalization requires repeated complete current-target endpoint labels" ) original = pose_target_contract(anchor, supervision, gripper, padding) return { **original, "version": original["version"] + "_supervised_population_v1", "anchor": anchor, "normalization_population": "query-zero complete current endpoint once per original observation; no future-pair or padding reweighting", } if normalization_population != "dense": raise ValueError("Unknown chunk normalization population") if padding == "current_target": if supervision != "current_endpoint" or gripper != "current": raise ValueError( "Current-target padding requires current endpoint and gripper" ) original = pose_target_contract(anchor, supervision, gripper) return { **original, "version": original["version"] + "_current_padding_v1", "padding": "repeat current observation complete endpoint target in all out-of-range slots", "gripper": "current observation command repeated in every slot including padding", } if padding != "terminal": raise ValueError("Unknown chunk padding") if gripper == "current": original = pose_target_contract(anchor, supervision) return { **original, "version": original["version"] + "_current_gripper_v1", "gripper": "current observation command repeated in valid slots; terminal padding unchanged", "gripper_supervision": "current", } if gripper != "future": raise ValueError("Unknown chunk gripper supervision") base = ( RELATIVE_POSE_CONTRACT if anchor == "chunk_start_tcp" else ABSOLUTE_POSE_CONTRACT ) if supervision == "dense": return base if supervision not in ("future_endpoint", "current_endpoint"): raise ValueError("Unknown endpoint supervision") return { **base, "version": ( f"chunk_start_pose6d_{supervision}_v1" if anchor == "chunk_start_tcp" else f"absolute_world_pose6d_{supervision}_v1" ), "pose_supervision": supervision, "target_source": ( "primitive endpoint at each future action time" if supervision == "future_endpoint" else "current observation primitive endpoint repeated in valid future slots" ), "gripper": "original future dense gripper command at each slot, unchanged", "normalization_population": "original dense valid anchor/future-target pairs, no terminal padding", **( { "anchor": "identity", "coordinate_frame": "stored TCP/keyframe frame, world in this audited StackCube dataset", } if anchor == "identity" else {} ), }
def resolve_anchor(anchor, mode: ChunkAnchor): """Pick the label origin; identity preserves the stored pose coordinate frame.
Only the label/restore frame changes. Converting an absolute goal into a physical controller delta always uses the real measured TCP, so this stays a pure representation switch rather than a change of what is commanded. """ if mode == "chunk_start_tcp": return anchor if mode != "identity": raise ValueError(f"Unknown chunk anchor mode: {mode}") shape = (*anchor.shape[:-1], 7) fixed = torch.zeros(shape, dtype=anchor.dtype, device=anchor.device) fixed[..., 3] = 1.0 # identity quaternion, zero translation return fixed
def controller_pose_targets(actions, tcp): """Reconstruct actual CPU controller goals in audited world-aligned root axes.""" if actions.shape[-1] != 7 or tcp.shape[-1] != 7: raise ValueError("Expected controller7 and world TCP7") delta = controller_to_sixd(actions) rotation = sixd_to_matrix(delta[..., 3:9]) @ quaternion_to_matrix(tcp[..., 3:]) return torch.cat( [ tcp[..., :3] + actions[..., :3].clamp(-1, 1) * 0.1, matrix_to_sixd(rotation), actions[..., -1:], ], -1, )
def world_to_chunk_relative(target, anchor): """World target10 -> fixed-origin translation and root-aligned relative rotation.""" rotation = sixd_to_matrix(target[..., 3:9]) @ quaternion_to_matrix( anchor[..., 3:] ).transpose(-1, -2) return torch.cat( [ (target[..., :3] - anchor[..., :3]) / 0.1, matrix_to_sixd(rotation), target[..., -1:], ], -1, )
def chunk_relative_to_world(target, anchor): """Restore every goal using the SAME anchor; never integrate or clip offsets.""" rotation = sixd_to_matrix(target[..., 3:9]) @ quaternion_to_matrix(anchor[..., 3:]) return torch.cat( [ anchor[..., :3] + target[..., :3] * 0.1, matrix_to_sixd(rotation), target[..., -1:], ], -1, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869"""Nominal endpoint of dense delta commands under perfect per-step tracking.
This is a geometric diagnostic, not a dynamics rollout: the trained deltas usefuture measured TCP poses, which are unavailable when skipping intermediate steps."""
import torchfrom mani_skill.utils.geometry.rotation_conversions import ( euler_angles_to_matrix, quaternion_to_matrix,)
from lim.action_encoding import ROTATION_SCALE, matrix_to_sixd, sixd_to_controller
def check_endpoint_controller(config): """Fail if the source controller differs from the audited CPU Panda contract.""" if not ( config.frame == "root_translation:root_aligned_body_rotation" and config.use_delta and not config.use_target and config.normalize_action and config.root_link_name is None and config.pos_lower == -0.1 and config.pos_upper == 0.1 and config.rot_lower == ROTATION_SCALE ): raise ValueError( "Dense endpoint requires the audited Panda delta-pose controller" )
def dense_chunk_endpoint(chunk, current_tcp, robot_root): """Return world target10 and decoded commands; keep ONLY the last gripper.
Commands are composed in robot-root coordinates with left-multiplied rotations, matching ManiSkill CPU's target construction. Rotations are decoded through the same 6D adapter and controller clipping as native dense execution. No simulation, future feedback, object poses or IK are used. """ chunk = torch.as_tensor(chunk, dtype=torch.float32) current = torch.as_tensor(current_tcp, dtype=chunk.dtype, device=chunk.device) root = torch.as_tensor(robot_root, dtype=chunk.dtype, device=chunk.device) if chunk.ndim != 2 or chunk.shape[1] != 10 or len(chunk) == 0: raise ValueError("Expected nonempty H x 10 dense delta predictions") for pose in (current, root): if pose.shape != (7,) or not torch.isfinite(pose).all(): raise ValueError("Expected finite world xyz,wxyz poses") if not torch.isclose(pose[3:].norm(), pose.new_tensor(1.0), atol=1e-4): raise ValueError("Expected unit pose quaternion") commands = sixd_to_controller(chunk).clone() commands[:, :3] = commands[:, :3].clamp(-1, 1) commands[:, -1] = commands[:, -1].clamp(-1, 1) root_rotation = quaternion_to_matrix(root[3:]) position = root_rotation.T @ (current[:3] - root[:3]) rotation = root_rotation.T @ quaternion_to_matrix(current[3:]) for command in commands: position = position + 0.1 * command[:3] rotation = ( euler_angles_to_matrix(command[3:6] * ROTATION_SCALE, "XYZ") @ rotation ) target = torch.cat( [ root[:3] + root_rotation @ position, matrix_to_sixd(root_rotation @ rotation), commands[-1, -1:], ] ) return target, commands1234567891011121314151617181920212223242526272829303132"""Predicted primitive boundaries in fixed-anchor action chunks, without an FSM."""
import torch
def phase_prefix(phases): """Count the first constant-label run; no observed change means horizon, not arrival.""" phases = torch.as_tensor(phases) if ( phases.ndim != 1 or len(phases) != 30 or not ((phases >= 0) & (phases < 6)).all() ): raise ValueError("Expected 30 predicted primitive indices in [0, 5]") changes = torch.nonzero(phases != phases[0]).flatten() return int(changes[0]) if len(changes) else 30
def chunk_selection(logits, mode): if logits.shape != (30, 6) or not torch.isfinite(logits).all(): raise ValueError("Expected finite prior logits with shape 30 x 6") if mode not in ("full", "boundary", "endpoint"): raise ValueError("Unknown phase chunk execution mode") labels = logits.argmax(-1) prefix = phase_prefix(labels) return { "phase_labels": labels.tolist(), "phase_prefix_length": prefix, "boundary_kind": "phase_change" if prefix < 30 else "horizon", "consume_length": 30 if mode == "full" else prefix, "selected_index": (30 if mode == "full" else prefix) - 1, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960"""Remaining-steps regression for two-segment phase endpoint outputs."""
import torchfrom pydantic import BaseModel, ConfigDictfrom torch import nn
SWITCH_HORIZON = 30"""Remaining steps are clipped to this horizon and supervised as a fraction of it."""
class ChunkSwitchHeadConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) action_head: nn.Module """Existing action projection (optionally wrapped by the phase head)."""
class ChunkSwitchHead(nn.Module): def __init__(self, config: ChunkSwitchHeadConfig): super().__init__() self.config = config self.action = config.action_head linear = getattr(self.action, "action", self.action) if not isinstance(linear, nn.Linear): raise ValueError("Switch head wraps a linear action projection") device = linear.weight.device devices = [device.index] if device.type == "cuda" else [] # Preserve subsequent EMA initialization and sampling/dropout RNG. with torch.random.fork_rng(devices=devices): self.switch = nn.Linear( linear.in_features, 1, device=device, dtype=linear.weight.dtype, ) self.switch_fraction = None
def forward(self, features): if features.ndim != 3 or features.shape[1] < 1: raise ValueError("Expected ACT decoder features batch x query x hidden") actions = self.action(features) self.switch_fraction = self.switch(features[:, 0]).squeeze(-1) return actions
def read_switch_fraction(model): """Raw remaining-steps fraction from the latest forward, not clipped or rerun.""" heads = [part for part in model.modules() if isinstance(part, ChunkSwitchHead)] if len(heads) != 1: raise ValueError("Expected exactly one enabled chunk switch head") fraction = heads[0].switch_fraction if fraction is None: raise RuntimeError("Switch fraction requires a completed policy forward") return fraction
def switch_steps(fraction): """Predicted steps until the second segment applies, rounded and bounded.""" return torch.round(fraction.clamp(0, 1) * SWITCH_HORIZON).long()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564"""Collect annotated native StackCube experts and map labels through pose replay.
The upstream expert is unchanged. Its planner factory is temporarily wrapped inthis single-process CLI to observe executed primitives; trial plans are excluded.An optional task-irrelevant perturbation (segment time scaling, pauses, detoursthrough an offset via-point and tapered joint jitter) changes how each plannedmove is executed; primitive targets, and so keypose labels, stay the expert's."""
import hashlibimport importlib.metadataimport inspectimport jsonimport timefrom pathlib import Pathfrom typing import Anyfrom unittest.mock import patch
import gymnasium as gymimport mani_skill.envs # noqa: F401import numpy as npimport sapienimport torchfrom mani_skill.utils import commonfrom mani_skill.utils.wrappers.record import RecordEpisodefrom pydantic import ( BaseModel, ConfigDict, Field, NonNegativeFloat, NonNegativeInt, PositiveFloat, PositiveInt, SkipValidation,)from pydantic_settings import CliApp
from lim.keypose_data import ( AnnotationConfig, AuditConfig, KeyposeSegment, audit_dataset, write_annotations,)from lim.replay_pose import ( TargetReplayConfig, replace_last, replay_targets, tree_first,)from lim.tasks import expert_module
# These are the native StackCube expert's primitives, not an invented phase split.STACK_CUBE_SEQUENCE = ( ("move", "approach"), ("move", "grasp_pose"), ("close", "close_gripper"), ("move", "lift"), ("move", "place_pose"), ("open", "open_gripper"),)
FREE_SPACE = ("approach", "place_pose")"""Moves away from contact: the reach above cube A and the transport onto B."""
class PerturbationConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) time_scale: tuple[PositiveFloat, PositiveFloat] = (1.0, 1.0) """Log-uniform range of each move's duration factor (>1 slower).""" pause_probability: float = Field(default=0.0, ge=0, le=1) """Chance that a move holds its current command mid-way.""" pause_steps: tuple[PositiveInt, PositiveInt] = (3, 10) """Inclusive range of held steps.""" detour_probability: float = Field(default=0.0, ge=0, le=1) """Chance that a free-space move first passes an offset via-point.""" detour_m: NonNegativeFloat = 0.0 """Sideways offset of the via-point from the straight path's midpoint (plus half of it upwards).""" jitter_rad: NonNegativeFloat = 0.0 """Std of smooth joint noise on free-space moves, tapered to zero at both ends.""" jitter_smoothing_steps: PositiveFloat = 5.0 """Gaussian smoothing width of the joint noise, in control steps.""" seed: NonNegativeInt = 20261005 """Perturbation stream; each attempt uses (seed, scene seed)."""
PERTURBATION_LEVELS = { 1: PerturbationConfig(time_scale=(0.8, 1.25), pause_probability=0.2, detour_probability=0.2, detour_m=0.03, jitter_rad=0.005), 2: PerturbationConfig(time_scale=(0.67, 1.5), pause_probability=0.4, detour_probability=0.4, detour_m=0.05, jitter_rad=0.01), 3: PerturbationConfig(time_scale=(0.5, 2.0), pause_probability=0.6, detour_probability=0.6, detour_m=0.08, jitter_rad=0.02),}
class CollectionConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) output_dir: Path """New dataset directory; existing files are never overwritten.""" episodes: PositiveInt = 100 """Number of successful pose demonstrations to retain.""" seed_start: NonNegativeInt = 71000 """First fresh scene seed, incremented once per attempt without retries.""" max_attempts: PositiveInt = 150 """Finite attempt budget including planner and converted-execution failures.""" save_video: bool = False """Record successful raw-expert videos for a small visual audit.""" perturbation_level: int = Field(default=0, ge=0, le=3) """0 keeps the native execution; 1-3 apply PERTURBATION_LEVELS.""" max_episode_steps: PositiveInt = 200 """Environment time limit; demonstrations longer than it are rejected.""" task: str = "StackCube-v1" """ManiSkill task with an annotated native expert (lim.tasks)."""
class PlannerConfig(BaseModel, frozen=True): model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid") planner: Any """Native Panda planner; all motions are executed by this object.""" recorder: Any """RecordEpisode supplies the actual dense-action clock.""" segments: SkipValidation[list[KeyposeSegment]] """Append-only events for this one expert attempt.""" sequence: tuple[tuple[str, str], ...] | None = STACK_CUBE_SEQUENCE """Expected (kind, name) primitives; None records whatever the expert executes, named by kind and position.""" perturbation: PerturbationConfig | None = None rng: SkipValidation[Any] = None """numpy Generator for this attempt's perturbation draws.""" log: SkipValidation[list] = Field(default_factory=list) """One record per executed move describing the applied perturbation."""
class PlanningFailure(RuntimeError): pass
def pose_vector(pose): return tuple( float(x) for x in np.r_[ common.to_numpy(pose.p).reshape(3), common.to_numpy(pose.q).reshape(4) ] )
class AnnotatedPlanner: sequence = STACK_CUBE_SEQUENCE
def __init__(self, config: PlannerConfig): self.config = config
def name(self, index, kind): if self.config.sequence is None: return f"{kind}_{index}" return self.config.sequence[index][1]
def record(self, kind, target, gripper, execute): index = len(self.config.segments) sequence = self.config.sequence if sequence is not None and (index >= len(sequence) or sequence[index][0] != kind): raise ValueError("Upstream expert primitive sequence changed") start = len(self.config.recorder._trajectory_buffer.action) - 1 goal = pose_vector(target) result = execute() if isinstance(result, int) and result == -1: raise PlanningFailure( f"Native planning failed during {self.name(index, kind)}" ) end = len(self.config.recorder._trajectory_buffer.action) - 1 if end <= start: raise ValueError("Executed primitive recorded no actions") self.config.segments.append( KeyposeSegment( name=self.name(index, kind), kind=kind, start=start, end=end, target_pose=goal, gripper=gripper, ) ) return result
def move_to_pose_with_screw(self, pose, dry_run=False, refine_steps=0): planner = self.config.planner if dry_run: return planner.move_to_pose_with_screw( pose, dry_run=True, refine_steps=refine_steps ) if self.config.perturbation is None: execute = lambda: planner.move_to_pose_with_screw(pose, refine_steps=refine_steps) else: name = self.name(len(self.config.segments), "move") execute = lambda: self.perturbed_move(pose, name, refine_steps) return self.record("move", pose, int(planner.gripper_state), execute)
def perturbed_move(self, pose, name, refine_steps): """Execute one planned move with this attempt's perturbation.""" planner, config, rng = self.config.planner, self.config.perturbation, self.config.rng free = name in FREE_SPACE record = {"segment": name, "detour": False} goals = [pose] if free and rng.random() < config.detour_probability and config.detour_m > 0: start = common.to_numpy(planner.base_env.agent.tcp.pose.p).reshape(3) end = common.to_numpy(pose.p).reshape(3) direction = end[:2] - start[:2] if np.linalg.norm(direction) < 1e-6: angle = rng.uniform(0, 2 * np.pi) direction = np.array([np.cos(angle), np.sin(angle)]) side = np.array([-direction[1], direction[0]]) / np.linalg.norm(direction) side *= rng.choice([-1.0, 1.0]) * config.detour_m via = (start + end) / 2 + np.r_[side, config.detour_m / 2] via_pose = sapien.Pose(via, common.to_numpy(pose.q).reshape(4)) if planner.move_to_pose_with_screw(via_pose, dry_run=True) != -1: goals = [via_pose, pose] record.update(detour=True, via=via.tolist()) result = None for index, goal in enumerate(goals): plan = planner.move_to_pose_with_screw(goal, dry_run=True) if isinstance(plan, int) and plan == -1: return -1 positions = np.asarray(plan["position"], dtype=np.float64) scale = float(np.exp(rng.uniform(*np.log(config.time_scale)))) steps = max(2, round(len(positions) * scale)) grid = np.linspace(0, len(positions) - 1, steps) positions = np.stack( [np.interp(grid, np.arange(len(positions)), joint) for joint in positions.T], -1 ) if free and config.jitter_rad > 0 and steps > 2: noise = rng.normal(size=positions.shape) width = config.jitter_smoothing_steps radius = min(int(3 * width), (steps - 1) // 2) kernel = np.exp(-0.5 * (np.arange(-radius, radius + 1) / width) ** 2) noise = np.stack([np.convolve(n, kernel, mode="same") for n in noise.T], -1) noise /= noise.std(0, keepdims=True) + 1e-12 taper = np.sin(np.linspace(0, np.pi, steps))[:, None] positions = positions + config.jitter_rad * noise * taper pause = 0 if index == len(goals) - 1 and rng.random() < config.pause_probability: pause = int(rng.integers(config.pause_steps[0], config.pause_steps[1] + 1)) at = int(rng.integers(1, steps)) positions = np.concatenate( [positions[:at], np.repeat(positions[at - 1 : at], pause, 0), positions[at:]] ) record.setdefault("parts", []).append( {"planned_steps": len(plan["position"]), "time_scale": scale, "executed_steps": len(positions), "pause_steps": pause} ) velocity = np.gradient(positions, axis=0) / planner.base_env.control_timestep result = planner.follow_path( {"position": positions, "velocity": velocity}, refine_steps=refine_steps ) self.config.log.append(record) return result
def close_gripper(self, t=6, gripper_state=None): planner = self.config.planner return self.record( "close", planner.base_env.agent.tcp.pose, int(planner.CLOSED if gripper_state is None else gripper_state), lambda: planner.close_gripper(t=t, gripper_state=gripper_state), )
def open_gripper(self, t=6, gripper_state=None): planner = self.config.planner return self.record( "open", planner.base_env.agent.tcp.pose, int(planner.OPEN if gripper_state is None else gripper_state), lambda: planner.open_gripper(t=t, gripper_state=gripper_state), )
def close(self): self.config.planner.close()
def clear_recording(recorder): if recorder._trajectory_buffer is not None: recorder.flush_trajectory(save=False) if recorder.save_video: recorder.flush_video(save=False)
def sha256(path): digest = hashlib.sha256() with Path(path).open("rb") as f: for block in iter(lambda: f.read(8 * 1024 * 1024), b""): digest.update(block) return digest.hexdigest()
def run(config: CollectionConfig): if config.max_attempts < config.episodes: raise ValueError("Attempt budget cannot be smaller than the requested dataset") torch.set_num_threads(4) config.output_dir.mkdir(parents=True, exist_ok=False) (config.output_dir / "config.json").write_text( config.model_dump_json(indent=2) + "\n" ) # Freeze the actual collector, replay code and native expert used for this dataset. from lim import keypose_data, replay_pose
expert = expert_module(config.task) files = [ Path(__file__), Path(keypose_data.__file__), Path(replay_pose.__file__), Path(inspect.getfile(expert)), ] provenance = { "source_sha256": {str(p): sha256(p) for p in files}, "software_versions": { p: importlib.metadata.version(p) for p in ["mani-skill", "sapien", "torch", "numpy", "mplib"] }, "observation_policy": "all RGB, TCP, qpos/qvel and dense actions retained", "annotation_policy": "native primitive targets/events; no image or action decimation", "expert_information": "native expert uses simulator object poses to create labels; not policy inputs", "perturbation": PERTURBATION_LEVELS[config.perturbation_level].model_dump(mode="json") if config.perturbation_level else None, } snapshot = config.output_dir / "source_snapshot" snapshot.mkdir() for p in files: (snapshot / p.name).write_bytes(p.read_bytes()) (config.output_dir / "provenance.json").write_text( json.dumps(provenance, indent=2) + "\n" ) kwargs = { "sim_backend": "physx_cpu", "num_envs": 1, "max_episode_steps": config.max_episode_steps, "reward_mode": "sparse", "render_mode": "rgb_array", "sensor_configs": {"shader_pack": "default"}, "human_render_camera_configs": {"shader_pack": "default"}, "viewer_camera_configs": {"shader_pack": "default"}, } raw = RecordEpisode( gym.make(config.task, obs_mode="rgb", control_mode="pd_joint_pos", **kwargs), output_dir=str(config.output_dir / "source"), trajectory_name="trajectory", save_on_reset=False, save_video=config.save_video, video_fps=20, source_type="motionplanning", source_desc=f"native {config.task} expert with primitive annotations", ) original = gym.make( config.task, obs_mode="none", control_mode="pd_joint_pos", **kwargs ) target = RecordEpisode( gym.make( config.task, obs_mode="rgb", control_mode="pd_ee_delta_pose", **kwargs ), output_dir=str(config.output_dir / "pose"), trajectory_name="trajectory", save_on_reset=False, save_video=False, source_type="motionplanning", source_desc="pose replay with exact source-action annotation mapping", ) started = time.monotonic() accepted = 0 attempts = [] native_planner = expert.PandaArmMotionPlanningSolver sequence = STACK_CUBE_SEQUENCE if config.task == "StackCube-v1" else None try: for attempt in range(config.max_attempts): seed = config.seed_start + attempt clear_recording(raw) clear_recording(target) segments = [] planners = []
perturbation = PERTURBATION_LEVELS.get(config.perturbation_level) moves = [] rng = ( np.random.default_rng([perturbation.seed, seed]) if perturbation else None )
def factory( *args, _planners=planners, _segments=segments, _moves=moves, _perturbation=perturbation, _rng=rng, **kwargs, ): planner = native_planner(*args, **kwargs) _planners.append(planner) return AnnotatedPlanner( PlannerConfig( planner=planner, recorder=raw, segments=_segments, sequence=sequence, perturbation=_perturbation, rng=_rng, log=_moves, ) )
failure = None try: # Scoped single-process adapter; the upstream function and planner remain unchanged. with patch.object(expert, "PandaArmMotionPlanningSolver", factory): result = expert.solve(raw, seed=seed, debug=False, vis=False) raw_success = not isinstance(result, int) and bool( result[-1]["success"].item() ) except PlanningFailure as error: raw_success = False failure = str(error) finally: for planner in planners: planner.close() record = { "attempt": attempt, "seed": seed, "raw_success": raw_success, "pose_success": False, "failure": failure, } if perturbation is not None: record["perturbation"] = moves if raw_success and len(raw._trajectory_buffer.action) - 1 > config.max_episode_steps: # Demonstrations must fit the time limit the policies are evaluated # with; the planner can return very long paths from some states. raw_success = False record.update( raw_success=False, failure=f"expert exceeded the {config.max_episode_steps}-step limit", source_steps=len(raw._trajectory_buffer.action) - 1, ) if raw_success: if sequence is not None and len(segments) != len(sequence): raise ValueError("Successful source has incomplete annotations") raw_steps = len(raw._trajectory_buffer.action) - 1 raw.flush_trajectory() source_id = raw._episode_id source_group = raw._h5_file[f"traj_{source_id}"] write_annotations( source_group, AnnotationConfig( segments=tuple(segments), source_steps=raw_steps, target_to_source=tuple(range(raw_steps)), ), ) raw._h5_file.flush() if config.save_video: raw.flush_video(name=f"seed{seed}") original.reset(seed=seed) target.reset(seed=seed) initial = tree_first(source_group["env_states"]) original.unwrapped.set_state_dict(initial) target.unwrapped.set_state_dict(initial) obs = target.unwrapped.get_obs() replace_last(target._trajectory_buffer.state, common.batch(initial)) replace_last( target._trajectory_buffer.observation, common.to_numpy(common.batch(obs)), ) # Exact identity/state correspondence is checked before executing any converted action. for name in ["qpos", "qvel"]: np.testing.assert_allclose( common.to_numpy(obs["agent"][name])[0], source_group[f"obs/agent/{name}"][0], rtol=0, atol=1e-6, ) mapping = [] info = replay_targets( TargetReplayConfig( original=original, target=target, actions=source_group["actions"][:], on_target_step=mapping.append, ) ) pose_success = ( bool(info["success"].item()) and len(mapping) <= config.max_episode_steps ) record.update( source_episode_id=source_id, source_steps=raw_steps, pose_steps=len(mapping), pose_success=pose_success, ) if pose_success: target.flush_trajectory() output_id = target._episode_id write_annotations( target._h5_file[f"traj_{output_id}"], AnnotationConfig( segments=tuple(segments), source_steps=raw_steps, target_to_source=tuple(mapping), ), ) target._json_data["episodes"][-1].update( source_episode_id=source_id, source_episode_seed=seed ) target._h5_file.flush() accepted += 1 record["output_episode_id"] = output_id # Explicitly discard failed buffers before reset, including the last attempt. clear_recording(raw) clear_recording(target) record.update(accepted=accepted, elapsed_s=time.monotonic() - started) attempts.append(record) with (config.output_dir / "attempts.jsonl").open("a") as f: f.write(json.dumps(record) + "\n") (config.output_dir / "progress.json").write_text( json.dumps(record, indent=2) + "\n" ) print("KEYPOSE_ATTEMPT", json.dumps(record), flush=True) if accepted == config.episodes: break finally: clear_recording(raw) clear_recording(target) raw.close() original.close() target.close() audits = {} for variant in ["source", "pose"]: audit = audit_dataset( AuditConfig( dataset=config.output_dir / variant / "trajectory.h5", output=config.output_dir / f"audit-{variant}.json", source_dataset=config.output_dir / "source" / "trajectory.h5" if variant == "pose" else None, ) ) audits[variant] = {k: v for k, v in audit.items() if k != "rows"} summary = { "status": "complete" if accepted == config.episodes else "insufficient_successes", "requested": config.episodes, "accepted": accepted, "attempted": len(attempts), "wall_s": time.monotonic() - started, "audits": audits, "scope": "new annotated demonstration data; no learned keypose policy evaluated", } (config.output_dir / "result.json").write_text(json.dumps(summary, indent=2) + "\n") print("KEYPOSE_COMPLETE", json.dumps(summary), flush=True) if accepted != config.episodes: raise RuntimeError("Collection exhausted its declared attempt budget") return summary
if __name__ == "__main__": run(CliApp.run(CollectionConfig))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327"""One frozen dense+phase model, three separately logged execution contracts."""
import jsonimport timefrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Literal
import gymnasium as gymimport mani_skill.envs # noqa: F401import numpy as npimport torchfrom mani_skill.utils.wrappers import CPUGymWrapperfrom pydantic import BaseModel, ConfigDict, PositiveIntfrom pydantic_settings import CliApp
from lim.act_policy import build_policyfrom lim.action_encoding import sixd_to_controllerfrom lim.chunk_coordinates import chunk_relative_to_world, world_to_chunk_relativefrom lim.chunk_endpoint import check_endpoint_controllerfrom lim.chunk_phase import chunk_selectionfrom lim.evaluate_planned_keypose import planning_state, verify_planning_unchangedfrom lim.gripper_feedback import ( FeedbackReaderConfig, GripperCompletionConfig, PandaGripperFeedback,)from lim.keypose_diagnostics import ( TrainingResetConfig, TrainingSceneReset, predict_action_chunk,)from lim.keypose_phase import read_phase_logitsfrom lim.planned_keypose import ( MplibKeyposePlanner, PlannedExecutorConfig, PlannedKeyposeExecutor, PlannerConfig,)from lim.reference_act import ( ReferenceConfig, check_policy_checkpoint, load_checkpoint, load_official,)
class PhaseChunkEvaluationConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) reference: Path """Frozen fixed-anchor phase-supervised dense checkpoint and sensor configuration.""" output_dir: Path """New results directory; never overwrite a previous run.""" mode: Literal["full", "boundary", "endpoint"] """Full30 playback, phase-prefix playback, or planned prefix endpoint.""" episodes: PositiveInt = 60 """All consecutive scenes, including failures.""" seed_start: int = 54000 """First scene seed.""" training_dataset: Path | None = None """Optional restoration of training initial states only, never labels for control.""" gripper_completion: GripperCompletionConfig = GripperCompletionConfig() """Original planned executor completion contract; playback has no extra dwell."""
def write_row(stream, row): stream.write(json.dumps(row, allow_nan=False) + "\n")
def run(config: PhaseChunkEvaluationConfig): torch.set_num_threads(4) torch.manual_seed(0) np.random.seed(0) reference = ReferenceConfig.model_validate_json(config.reference.read_text()) if not ( reference.policy.chunk_phase_weight > 0 and reference.policy.method == "chunk_relative" and reference.policy.chunk_anchor == "chunk_start_tcp" and reference.num_queries == 30 and reference.control_mode == "pd_ee_delta_pose" and not reference.gripper_execution.active ): raise ValueError("Expected one phase-supervised fixed-anchor Q30 pose6D model") checkpoint, provenance = load_checkpoint(reference.checkpoint) check_policy_checkpoint(checkpoint, reference) module = load_official(reference) metadata = json.loads(reference.demonstration_metadata.read_text()) sensor = metadata["env_info"]["env_kwargs"]["sensor_configs"] planned = config.mode == "endpoint" control_mode = "pd_joint_pos" if planned else "pd_ee_delta_pose" config.output_dir.mkdir(parents=True, exist_ok=False) for folder in ("plans", "query_observations"): (config.output_dir / folder).mkdir() raw = gym.make( "StackCube-v1", obs_mode="rgb", control_mode=control_mode, reward_mode="sparse", render_mode="rgb_array", sim_backend="physx_cpu", num_envs=1, reconfiguration_freq=1, max_episode_steps=200, sensor_configs=sensor, ) if config.training_dataset is not None: raw = TrainingSceneReset( TrainingResetConfig(env=raw, dataset=config.training_dataset) ) env = CPUGymWrapper( module.FlattenRGBDObservationWrapper(raw, depth=False), ignore_terminations=True, record_metrics=True, ) spaces = SimpleNamespace( single_observation_space=env.observation_space, single_action_space=gym.spaces.Box(-1, 1, (7,), dtype=np.float32), ) records = [] started = time.time() try: agent = ( build_policy( module, spaces, module.args, reference.policy, checkpoint.get("normalization"), ) .cuda() .eval() ) agent.load_state_dict(checkpoint["ema_agent"]) if not np.isclose(env.unwrapped.control_timestep, 0.05): raise ValueError("Expected 20Hz physical playback") with ( (config.output_dir / "predictions.jsonl").open("x") as queries, (config.output_dir / "steps.jsonl").open("x") as steps, (config.output_dir / "episodes.jsonl").open("x") as episodes, ): for seed in range(config.seed_start, config.seed_start + config.episodes): obs, _ = env.reset(seed=seed) base = env.unwrapped check_endpoint_controller( base.agent._controller_configs["pd_ee_delta_pose"]["arm"] ) np.testing.assert_allclose( base.agent.robot.pose.raw_pose[0, 3:].cpu().numpy(), [1, 0, 0, 0], atol=1e-5, ) torch.save( { "observation": obs, "cubeA_pose": base.cubeA.pose.raw_pose.cpu(), "cubeB_pose": base.cubeB.pose.raw_pose.cpu(), }, config.output_dir / f"initial-{seed}.pt", ) initial_grip = float( np.float32( np.clip((obs["state"][7:9].mean() + 0.01) / 0.05 * 2 - 1, -1, 1) ) ) executor = PlannedKeyposeExecutor( PlannedExecutorConfig( initial_gripper=initial_grip, gripper_completion=config.gripper_completion, ) ) planner = ( MplibKeyposePlanner(PlannerConfig(env=env)) if planned else None ) feedback = ( PandaGripperFeedback( FeedbackReaderConfig( env=env, completion=config.gripper_completion ) ) if planned else None ) query = cursor = consume = failures = 0 once = False world = None for step in range(200): before = obs["state"].copy() needs_query = ( executor.needs_prediction if planned else cursor == consume ) if needs_query: query += 1 np.savez_compressed( config.output_dir / f"query_observations/seed{seed}-query{query}.npz", **obs, ) chunk = predict_action_chunk(agent, obs) logits = read_phase_logits(agent)[0].detach().cpu() if chunk.shape != (30, 10) or not torch.isfinite(chunk).all(): raise ValueError("Expected finite fixed-anchor chunk") selection = chunk_selection(logits, config.mode) consume, cursor = selection["consume_length"], 0 world = chunk_relative_to_world( chunk, torch.tensor(before[18:25]) ) target = world[selection["selected_index"]] prefix_grip = world[: selection["phase_prefix_length"], -1] >= 0 row = { "seed": seed, "step": step, "query": query, "state_before": before.tolist(), "relative_chunk": chunk.tolist(), "world_chunk": world.tolist(), "phase_logits": logits.tolist(), **selection, "within_prefix_gripper_sign_changes": int( (prefix_grip[1:] != prefix_grip[:-1]).sum() ), "model_target": target.tolist(), "planning_status": None, "path_steps": 0, } if planned: physical = planning_state(base) plan = planner.plan(target) verify_planning_unchanged(physical, planning_state(base)) row["planning_status"] = planner.last_status failures += int(plan is None) if plan is not None: np.savez_compressed( config.output_dir / f"plans/seed{seed}-query{query}.npz", position=plan["position"], velocity=plan["velocity"], time=plan["time"], ) row["path_steps"] = len(plan["position"]) executor.begin( target, None if plan is None else plan["position"], before[:9], source_query=query, ) write_row(queries, row) if planned: index = selection["selected_index"] command, details = executor.command(before[18:25]) else: index = cursor command = sixd_to_controller( world_to_chunk_relative( world[index], torch.tensor(before[18:25]) ) ).numpy() cursor += 1 details = {"phase": "playback"} obs, _, _, _, info = env.step(command) if planned: measured = feedback.read(float(command[-1])) details["gripper_measurement"] = measured.model_dump( mode="json" ) if details["phase"] == "gripper": details["gripper_feedback"] = executor.observe_gripper( measured ) details["executor_phase_after"] = executor.phase success = bool(info["success"]) once = once or success write_row( steps, { "seed": seed, "step": step, "query": query, "chunk_index": index, "state_before": before.tolist(), "state_after": obs["state"].tolist(), "command": command.tolist(), "success": success, **details, }, ) episode = { "seed": seed, "steps": 200, "success_once": once, "success_at_end": success, "policy_calls": query, "planning_failures": failures, "gripper_timeouts": executor.gripper_timeouts if planned else 0, } assert once == bool( info["episode"]["success_once"] ) and success == bool(info["episode"]["success_at_end"]) write_row(episodes, episode) records.append(episode) finally: env.close() result = { "status": "complete", "config": config.model_dump(mode="json"), "policy": reference.policy.model_dump(mode="json"), "provenance": provenance, "sensor_configs": sensor, "parameters": sum(p.numel() for p in agent.parameters()), "control_mode": control_mode, "control_hz": 20, "episodes": len(records), "counts": { key: sum(int(r[key]) for r in records) for key in ("success_once", "success_at_end") }, "started_epoch": started, "ended_epoch": time.time(), "scope": "Single frozen EMA; predicted per-action phases only. Fixed-anchor targets, never integrated. No temporal ensemble. Full/boundary use identical per-step TCP conversion; endpoint changes controller/path/feedback too. Horizon truncation is not certified stage completion. Success is recorded only, never a control input.", } (config.output_dir / "result.json").write_text( json.dumps(result, indent=2, allow_nan=False) + "\n" ) print("PHASE_CHUNK_COMPLETE", json.dumps(result), flush=True)
if __name__ == "__main__": run(CliApp.run(PhaseChunkEvaluationConfig))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210"""Matched single-environment evaluation of frozen reactive and planned keyposes."""
import hashlibimport inspectimport jsonimport timefrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Literal
import gymnasium as gymimport mani_skill.envs # noqa: F401import numpy as npimport torchfrom mani_skill.utils.wrappers import CPUGymWrapperfrom pydantic import ( BaseModel, ConfigDict, Field, NonNegativeInt, PositiveInt, model_validator,)from pydantic_settings import CliApp
from lim.act_policy import build_policyfrom lim.chunk_coordinates import chunk_relative_to_worldfrom lim.chunk_endpoint import check_endpoint_controller, dense_chunk_endpointfrom lim.gripper_feedback import ( FeedbackReaderConfig, GripperCompletionConfig, PandaGripperFeedback,)from lim.keypose_control import KeyposeControlConfig, keypose_commandfrom lim.keypose_diagnostics import ( FirstTargetXYZConfig, TrainingFirstTargetXYZ, TrainingResetConfig, TrainingSceneReset, first_target_intervention, nearest_cube_intervention, predict_action_chunk, predict_keypose,)from lim.keypose_phase import KEYPOSE_PHASE_NAMES, read_phase_logitsfrom lim.keypose_stop import read_stop_logitsfrom lim.planned_keypose import ( MplibKeyposePlanner, PlannedExecutorConfig, PlannedKeyposeExecutor, PlannerConfig,)from lim.policy_video import PolicyVideo, PolicyVideoConfigfrom lim.reference_act import ( AuditConfig, ReferenceConfig, ReleasedSupportAudit, check_policy_checkpoint, load_checkpoint, load_official, source_provenance,)
class EvaluationConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) reference: Path = Path("round9/specs/eval-keypose-main.json") """Frozen model and sensor contract; checked against its trained action semantics.""" target_source: Literal[ "keypose", "dense_chunk_endpoint", "chunk_relative_endpoint" ] = "keypose" """Direct query-zero keypose, or nominal endpoint composed from a dense delta chunk.""" mode: Literal["reactive", "planned"] """Fresh prediction each step, or full planned path before each prediction.""" reactive_gripper_gate: bool = True """Reactive only: false directly executes predicted gripper, changing no motion command.""" output_dir: Path """New directory containing every episode, command, prediction and plan.""" episodes: PositiveInt = 60 """Consecutive original ID scenes; no selection or retries.""" seed_start: int = 54000 """First paired scene seed.""" max_steps: PositiveInt = 200 """Physical control steps per scene; non-200 budgets are horizon diagnostics.""" video_seeds: tuple[int, ...] = (54000, 54017) """Selected recordings; the model does not see the observer camera.""" gripper_completion: GripperCompletionConfig = GripperCompletionConfig() """Finger encoder/contact feedback criteria for planned execution completion.""" resume_after_incomplete: bool = False """Keep querying after an unmet gripper command instead of freezing the episode.
The original contract has no path back from gripper_timeout: the 27 stalled chunk_relative endpoint episodes spent 2,314 further steps (42.9% of their budget) without a single new query. Default false preserves scored runs. """ carry_gripper_feedback: bool = False """Reuse fresh motion-time gripper stability for an exactly unchanged command.""" phase_gripper_events: bool = False """Use predicted close/open classes to hold the arm and execute the predicted continuous gripper immediately; other classes retain full planned motion.""" motion_replan_steps: NonNegativeInt = 0 """Refresh the target after N actual motion steps; zero executes full paths.""" first_close_hold: bool = False """On the first requested open-to-close transition, hold measured arm joints and execute only the predicted gripper. Context retains the raw request, whose arm pose was bypassed, after gripper feedback completion.""" hold_after_first_release: bool = False """After the first predicted negative-to-nonnegative gripper transition completes its original path and feedback, hold its final command to horizon.""" honor_predicted_stop: bool = False """Consume the checkpoint's stop-after-target prediction only after full execution and feedback; false logs the same logits but continues querying.""" terminal_gripper_event: bool = False """For a predicted terminal target with nonnegative gripper, bypass its arm pose and hold measured joints during the original gripper feedback.""" training_dataset: Path | None = None """Diagnostic only: restore saved training states selected by episode seed.""" first_target_xyz_alpha: float | None = Field( default=None, ge=0, le=1, allow_inf_nan=False ) """Training-scene oracle only: first XYZ = expert + alpha * model residual. None preserves the original path; alpha=1 is an exact identity diagnostic. Rotation, gripper and all later predictions remain the model's outputs. """ first_target_xy: Literal["predicted", "cube_center"] = "predicted" """Diagnostic only: replace first target XY, retaining all other predictions.""" every_target_xy: Literal["predicted", "nearest_cube_center"] = "predicted" """Diagnostic only: replace EVERY target XY with the nearest cube center.
Isolates localization precision from phase advancement: height, orientation, continuous gripper and the decision of when to advance remain the model's. """
@property def diagnostic_xy(self): """Number of active privileged-XY interventions; zero for a scored run.""" return int(self.first_target_xy != "predicted") + int( self.every_target_xy != "predicted" )
@model_validator(mode="after") def check_single_intervention(self): if self.terminal_gripper_event and not self.honor_predicted_stop: raise ValueError("Terminal gripper events require predicted-stop execution") if self.honor_predicted_stop and ( self.mode != "planned" or self.target_source != "keypose" or self.hold_after_first_release or self.first_close_hold or self.motion_replan_steps or self.carry_gripper_feedback or self.resume_after_incomplete or self.phase_gripper_events or self.diagnostic_xy or self.first_target_xyz_alpha is not None or not self.reactive_gripper_gate ): raise ValueError("Predicted stop requires an isolated planned context lane") if self.hold_after_first_release and ( self.mode != "planned" or self.target_source != "keypose" or self.first_close_hold or self.motion_replan_steps or self.carry_gripper_feedback or self.resume_after_incomplete or self.phase_gripper_events or self.diagnostic_xy or self.first_target_xyz_alpha is not None or not self.reactive_gripper_gate ): raise ValueError("Release hold requires an isolated planned context lane") if self.first_close_hold and ( self.mode != "planned" or self.target_source != "keypose" or self.motion_replan_steps or self.carry_gripper_feedback or self.resume_after_incomplete or self.phase_gripper_events or self.diagnostic_xy or self.first_target_xyz_alpha is not None or not self.reactive_gripper_gate ): raise ValueError("First-close hold requires an isolated planned lane") if self.motion_replan_steps and ( self.mode != "planned" or self.target_source != "keypose" or self.carry_gripper_feedback or self.resume_after_incomplete or self.phase_gripper_events or self.diagnostic_xy or self.first_target_xyz_alpha is not None or not self.reactive_gripper_gate ): raise ValueError("Motion replanning requires an isolated planned lane") if self.phase_gripper_events and ( self.mode != "planned" or self.target_source != "keypose" or self.carry_gripper_feedback or self.resume_after_incomplete or self.diagnostic_xy or self.first_target_xyz_alpha is not None ): raise ValueError( "Phase gripper events require an isolated planned keypose lane" ) if not self.reactive_gripper_gate and self.mode != "reactive": raise ValueError("Disabling the gripper gate requires reactive execution") if self.carry_gripper_feedback and self.mode != "planned": raise ValueError("Motion feedback carry requires planned execution") if self.diagnostic_xy > 1: raise ValueError( "Choose one XY intervention; combining them confounds the diagnostic" ) if self.first_target_xyz_alpha is not None: if ( self.mode != "planned" or self.target_source != "keypose" or self.training_dataset is None ): raise ValueError( "First XYZ residual diagnostic requires planned keypose and training_dataset" ) if self.diagnostic_xy: raise ValueError( "First XYZ residual diagnostic cannot combine with XY interventions" ) if self.target_source != "keypose" and ( self.mode != "planned" or self.diagnostic_xy or self.training_dataset is not None ): raise ValueError( "Dense endpoint diagnostic uses planned execution without privileged interventions" ) return self
def reactive_action(current, target, previous_gripper, control, *, gripper_gate=True): """Apply the original TCP controller, optionally replacing its gripper only.""" command, reached, position_error, rotation_error = keypose_command( current, target, previous_gripper, control ) gated = command[..., -1].clone() requested = target[..., -1].clamp(-1, 1) would_change = bool((gated != requested).item()) if not gripper_gate: command[..., -1] = requested return command, { "phase": "reactive", "reached": bool(reached.item()), "position_error_m": position_error.item(), "rotation_error_rad": rotation_error.item(), "requested_gripper": requested.item(), "gated_gripper": gated.item(), "gate_would_change_gripper": would_change, "gripper_gate_blocked": bool(gripper_gate and would_change), "reactive_gripper_gate": gripper_gate, }
def phase_prediction_details(agent): """Read only the latest batch-one prior forward; no environment phase input.""" logits = read_phase_logits(agent).detach().cpu() if ( logits.shape != (1, len(KEYPOSE_PHASE_NAMES)) or not torch.isfinite(logits).all() ): raise ValueError("Expected finite batch-one six-class prior phase logits") return { "phase_logits_prior": logits[0].tolist(), "predicted_phase": int(logits[0].argmax().item()), }
def is_gripper_phase(details): """Only the current model argmax selects an event; no ordering or sign rule.""" index = details["predicted_phase"] if index not in range(len(KEYPOSE_PHASE_NAMES)): raise ValueError("Invalid predicted phase") return KEYPOSE_PHASE_NAMES[index] in ("close_gripper", "open_gripper")
def with_completed_target(observation, previous): """Encode the prior feedback-completed request; no expert phase is supplied.
Normally its arm path executed. The explicit first-close-hold intervention preserves the requested pose despite bypassing it and logs that exception. """ context = np.zeros(11, dtype=np.float32) if previous is not None: value = np.asarray(previous, dtype=np.float32) if value.shape != (10,) or not np.isfinite(value).all(): raise ValueError("Expected a finite completed world keypose10") context[:10], context[10] = value, 1 return {**observation, "completed_target": context}
def should_hold_first_close(predicted, executed_gripper, *, already_held): """First closing request after an actual nonnegative actuator command.""" target = torch.as_tensor(predicted) if target.shape != (10,) or not torch.isfinite(target).all(): raise ValueError("Expected finite raw predicted world keypose10") if executed_gripper is not None and not np.isfinite(executed_gripper): raise ValueError("Expected a finite previously executed gripper command") return bool( not already_held and executed_gripper is not None and executed_gripper >= 0 and target[-1] < 0 )
def is_first_release_request(predicted, executed_gripper, *, already_requested): """A predicted opening follows an actual negative actuator command.""" target = torch.as_tensor(predicted) if target.shape != (10,) or not torch.isfinite(target).all(): raise ValueError("Expected finite raw predicted world keypose10") if executed_gripper is not None and not np.isfinite(executed_gripper): raise ValueError("Expected a finite previously executed gripper command") return bool( not already_requested and executed_gripper is not None and executed_gripper < 0 and target[-1] >= 0 )
def completed_target_hold_command(command, feedback, *, query, hold_query): """Latch only a physically executed command after the selected feedback completes.""" if ( hold_query is None or query != hold_query or feedback.get("status") != "complete" ): return None result = np.asarray(command, dtype=np.float32).copy() if result.shape != (8,) or not np.isfinite(result).all(): raise ValueError("Expected the finite executed joint/gripper command8") return result
def stop_prediction_details(agent): """Read the latest prior forward without another model call or oracle input.""" logits = read_stop_logits(agent).detach().cpu().clone() if logits.shape != (1,) or not torch.isfinite(logits).all(): raise ValueError("Expected one finite stop-after-target logit") return { "stop_logit": float(logits[0]), "stop_probability": float(logits[0].sigmoid()), "stop_after_target": bool(logits[0] >= 0), }
def is_terminal_gripper_event(predicted, stop_after_target): """Use only the model's terminal intent and original gripper request.""" target = torch.as_tensor(predicted) if target.shape != (10,) or not torch.isfinite(target).all(): raise ValueError("Expected finite raw predicted world keypose10") return bool(stop_after_target and target[-1] >= 0)
def planning_state(base): """Read physical state without rendering or taking a simulation step.""" return { "qpos": base.agent.robot.get_qpos().detach().cpu().numpy().copy(), "qvel": base.agent.robot.get_qvel().detach().cpu().numpy().copy(), "tcp": base.agent.tcp.pose.raw_pose.detach().cpu().numpy().copy(), "elapsed_steps": torch.as_tensor(base.elapsed_steps).cpu().numpy().copy(), }
def verify_planning_unchanged(before, after): if before.keys() != after.keys(): raise ValueError("Planning state fields differ") for key in before: if not np.array_equal(before[key], after[key]): raise RuntimeError(f"Planner dry-run changed physical {key}") return True
def executor_trace(executor): """Log active execution separately from the latest (possibly rejected) query.""" return { "goal_id": executor.goal_id, "path_revision": executor.path_revision, "active_target_query": executor.active_query, "completed_target_from_query": executor.completed_target_query, "completed_target": None if executor.completed_target is None else executor.completed_target.tolist(), "completed_goals": executor.completed_goals, "motion_steps_since_attempt": executor.motion_steps_since_attempt, "goal_motion_steps": executor.goal_motion_steps, "total_motion_steps": executor.total_motion_steps, "goal_replan_attempts": executor.goal_replan_attempts, }
def run(config: EvaluationConfig): torch.set_num_threads(4) torch.manual_seed(0) np.random.seed(0) config.output_dir.mkdir(parents=True, exist_ok=False) (config.output_dir / "plans").mkdir() if config.motion_replan_steps: (config.output_dir / "query_observations").mkdir() reference = ReferenceConfig.model_validate_json(config.reference.read_text()) context_enabled = reference.policy.keypose_context != "none" stop_enabled = reference.policy.keypose_stop_head if config.honor_predicted_stop and not stop_enabled: raise ValueError( "Predicted stop requires a checkpoint trained with a stop head" ) if stop_enabled and ( config.hold_after_first_release or config.first_close_hold or config.motion_replan_steps ): raise ValueError("Stop-head evaluation cannot combine execution interventions") if config.hold_after_first_release and not context_enabled: raise ValueError("Release hold requires a context-enabled keypose checkpoint") if context_enabled and ( config.mode != "planned" or config.target_source != "keypose" or config.diagnostic_xy or config.first_target_xyz_alpha is not None or config.phase_gripper_events or config.carry_gripper_feedback or config.resume_after_incomplete ): raise ValueError( "Completed goal conditioning requires an isolated planned lane" ) if config.phase_gripper_events and reference.policy.keypose_phase_weight <= 0: raise ValueError( "Phase gripper events require a checkpoint trained with phase outputs" ) dense_endpoint = config.target_source == "dense_chunk_endpoint" relative_endpoint = config.target_source == "chunk_relative_endpoint" if dense_endpoint or relative_endpoint: if not ( reference.policy.keypose is None and reference.policy.method == ("chunk_relative" if relative_endpoint else "cvae") and reference.policy.action_encoding == "rotation6d" and reference.control_mode == "pd_ee_delta_pose" and reference.num_queries == 30 and not reference.gripper_execution.active ): raise ValueError("Expected frozen 30-query dense CVAE pose6D model") elif reference.policy.keypose is None: raise ValueError("Direct keypose evaluation requires a trained keypose model") control = reference.policy.keypose or KeyposeControlConfig() module = load_official(reference) checkpoint, provenance = load_checkpoint(reference.checkpoint) check_policy_checkpoint(checkpoint, reference) first_xyz_oracle = ( TrainingFirstTargetXYZ( FirstTargetXYZConfig( dataset=config.training_dataset, alpha=config.first_target_xyz_alpha ) ) if config.first_target_xyz_alpha is not None else None ) metadata = json.loads(reference.demonstration_metadata.read_text()) sensor = metadata["env_info"]["env_kwargs"]["sensor_configs"] control_mode = "pd_joint_pos" if config.mode == "planned" else "pd_ee_delta_pose" raw = gym.make( "StackCube-v1", obs_mode="rgb", control_mode=control_mode, reward_mode="sparse", render_mode="rgb_array", sim_backend="physx_cpu", reconfiguration_freq=1, max_episode_steps=config.max_steps, sensor_configs=sensor, ) if config.training_dataset is not None: raw = TrainingSceneReset( TrainingResetConfig(env=raw, dataset=config.training_dataset) ) env = ReleasedSupportAudit( AuditConfig( env=raw, snapshots=config.output_dir / "raw_observations", stride=10, seed_start=config.seed_start, ) ) env = PolicyVideo( PolicyVideoConfig( env=env, output_dir=config.output_dir / "videos", seeds=config.video_seeds, label=f"{config.target_source}-{config.mode}", max_steps=config.max_steps, ) ) env = module.FlattenRGBDObservationWrapper(env, depth=False) env = CPUGymWrapper(env, ignore_terminations=True, record_metrics=True) # Build against the checkpoint's original pose controller7, independent of # physical joint ABI8. The policy config distinguishes world poses from deltas. spaces = SimpleNamespace( single_observation_space=env.observation_space, single_action_space=gym.spaces.Box(-1, 1, (7,), dtype=np.float32), ) episodes = [] started = time.time() try: agent = ( build_policy( module, spaces, module.args, reference.policy, checkpoint.get("normalization"), ) .cuda() .eval() ) agent.load_state_dict(checkpoint["ema_agent"]) with ( (config.output_dir / "steps.jsonl").open("x") as trace, (config.output_dir / "predictions.jsonl").open("x") as predictions, ): for seed in range(config.seed_start, config.seed_start + config.episodes): obs, _ = env.reset(seed=seed) base = env.unwrapped if dense_endpoint or relative_endpoint: check_endpoint_controller( base.agent._controller_configs["pd_ee_delta_pose"]["arm"] ) if relative_endpoint: np.testing.assert_allclose( base.agent.robot.pose.raw_pose[0, 3:].cpu().numpy(), [1, 0, 0, 0], atol=1e-5, ) torch.save( { "observation": obs, "cubeA_pose": base.cubeA.pose.raw_pose.cpu(), "cubeB_pose": base.cubeB.pose.raw_pose.cpu(), }, config.output_dir / f"initial-{seed}.pt", ) grip = torch.tensor( [np.clip((obs["state"][7:9].mean() + 0.01) / 0.05 * 2 - 1, -1, 1)], dtype=torch.float32, ) planner = ( MplibKeyposePlanner(PlannerConfig(env=env)) if config.mode == "planned" else None ) executor = PlannedKeyposeExecutor( PlannedExecutorConfig( control=control, gripper_completion=config.gripper_completion, initial_gripper=float(grip.item()), resume_after_incomplete=config.resume_after_incomplete, carry_gripper_feedback=config.carry_gripper_feedback, motion_replan_steps=config.motion_replan_steps, ) ) feedback_reader = ( PandaGripperFeedback( FeedbackReaderConfig( env=env, completion=config.gripper_completion ) ) if planner is not None else None ) calls, failures, plans_completed, gripper_events = 0, 0, 0, 0 previous_command = None first_close_hold_query = None release_query, release_request_step = None, None release_feedback_complete_step, hold_started_step = None, None stop_query, stop_request_step, stop_feedback_complete_step = ( None, None, None, ) terminal_command = None terminal_event_query = None terminal_hold_steps = 0 for step in range(config.max_steps): before = obs["state"].copy() replan = executor.needs_motion_replan if terminal_command is None and ( config.mode == "reactive" or executor.needs_prediction or replan ): if ( config.mode == "planned" and calls and not config.motion_replan_steps ): plans_completed += 1 query_state_before = ( executor_trace(executor) if config.motion_replan_steps else {} ) inference_start = ( time.monotonic() if config.motion_replan_steps else None ) endpoint_details = {} if dense_endpoint: chunk = predict_action_chunk(agent, obs) if chunk.shape != (reference.num_queries, 10): raise ValueError( "Dense checkpoint returned unexpected chunk shape" ) root_pose = base.agent.robot.pose.raw_pose[0].cpu() predicted, decoded = dense_chunk_endpoint( chunk, before[18:25], root_pose ) endpoint_details = { "dense_chunk": chunk.tolist(), "decoded_commands": decoded.tolist(), "robot_root_pose": root_pose.tolist(), "model_target_semantics": "nominal composed endpoint; raw model output is dense_chunk", } elif relative_endpoint: chunk = predict_action_chunk(agent, obs) if chunk.shape != (reference.num_queries, 10): raise ValueError( "Expected a 30x10 fixed-reference chunk" ) anchor = torch.tensor(before[18:25]) predicted = chunk_relative_to_world(chunk[-1], anchor) endpoint_details = { "relative_chunk": chunk.tolist(), "chunk_start_tcp": anchor.tolist(), "selected_query_index": len(chunk) - 1, "model_target_semantics": "query29 restored from its fixed chunk-start TCP; no delta accumulation", } else: model_obs = ( with_completed_target(obs, executor.completed_target) if context_enabled else obs ) predicted = predict_keypose(agent, model_obs) if context_enabled: endpoint_details = { "completed_target_input": model_obs[ "completed_target" ].tolist(), "completed_target_from_query": executor.completed_target_query, "context_mode": reference.policy.keypose_context, } if config.first_close_hold: endpoint_details.update( requested_target_context=model_obs[ "completed_target" ].tolist(), context_semantics="historical_requested_target_after_feedback", context_arm_pose_executed=None if executor.completed_target_query is None else executor.completed_target_query != first_close_hold_query, ) if reference.policy.keypose_phase_weight > 0: endpoint_details = phase_prediction_details(agent) if stop_enabled: endpoint_details.update(stop_prediction_details(agent)) if config.motion_replan_steps: inference_wall_s = time.monotonic() - inference_start observation_path = ( config.output_dir / f"query_observations/seed{seed}-query{calls + 1}.npz" ) np.savez_compressed(observation_path, **model_obs) target = first_target_intervention( predicted, query=calls + 1, cube_xy=base.cubeA.pose.p[0, :2].cpu() if config.first_target_xy == "cube_center" and calls == 0 else None, ) nearest = None if config.every_target_xy == "nearest_cube_center": # Live poses: a perfect localizer would read current state. target, nearest = nearest_cube_intervention( predicted, cubes={ "cubeA": base.cubeA.pose.p[0, :2].cpu(), "cubeB": base.cubeB.pose.p[0, :2].cpu(), }, ) xyz_intervention = None if first_xyz_oracle is not None: target, xyz_intervention = first_xyz_oracle.apply( predicted, query=calls + 1, seed=seed ) calls += 1 prediction = { "seed": seed, "step": step, "query": calls, "target": target.tolist(), "model_target": predicted.tolist(), "first_xy_overridden": config.first_target_xy == "cube_center" and calls == 1, "every_xy_overridden": nearest is not None, "state_before": before.tolist(), **( {"nearest_cube": nearest} if nearest is not None else {} ), **( {"first_xyz_intervention": xyz_intervention} if xyz_intervention is not None else {} ), **endpoint_details, } if stop_enabled: if stop_query is None and prediction["stop_after_target"]: stop_query, stop_request_step = calls, step prediction.update( stop_query=stop_query, stop_request_step=stop_request_step, honor_predicted_stop=config.honor_predicted_stop, ) event = config.phase_gripper_events and is_gripper_phase( endpoint_details ) hold_close = ( config.first_close_hold and should_hold_first_close( predicted, None if previous_command is None else float(previous_command[-1]), already_held=first_close_hold_query is not None, ) ) hold_terminal = ( config.terminal_gripper_event and is_terminal_gripper_event( predicted, prediction["stop_after_target"] ) ) if config.terminal_gripper_event: prediction.update( terminal_gripper_event=hold_terminal, arm_pose_executed=False if hold_terminal else None, ) if config.hold_after_first_release: release_requested = is_first_release_request( predicted, None if previous_command is None else float(previous_command[-1]), already_requested=release_query is not None, ) if release_requested: release_query, release_request_step = calls, step prediction.update( release_requested=release_requested, release_query=release_query, release_request_step=release_request_step, previous_executed_gripper=None if previous_command is None else float(previous_command[-1]), ) if config.first_close_hold: prediction.update( first_close_hold_triggered=hold_close, previous_executed_gripper=None if previous_command is None else float(previous_command[-1]), arm_pose_executed=False if hold_close else None, ) if event or hold_close or hold_terminal: executor.begin_gripper( target, before[:9], source_query=calls ) if hold_close: first_close_hold_query = calls elif hold_terminal: terminal_event_query = calls else: gripper_events += 1 prediction.update( planning_status="first_close_hold" if hold_close else "terminal_gripper_event" if hold_terminal else "gripper_event", planning_wall_s=0.0, path_steps=0, hold_arm_qpos=before[:7].tolist(), ) elif planner is not None: physical_before_plan = ( planning_state(base) if config.motion_replan_steps else None ) start = time.monotonic() plan = planner.plan(target) prediction["planning_wall_s"] = time.monotonic() - start prediction["planning_status"] = planner.last_status failures += int(plan is None) if config.motion_replan_steps: unchanged = verify_planning_unchanged( physical_before_plan, planning_state(base) ) if plan is not None: np.savez_compressed( config.output_dir / f"plans/seed{seed}-query{calls}.npz", position=plan["position"], velocity=plan["velocity"], time=plan["time"], ) prediction["path_steps"] = len(plan["position"]) if replan: accepted = executor.replace_motion_plan( target, None if plan is None else plan["position"], source_query=calls, ) else: executor.begin( target, None if plan is None else plan["position"], before[:9], source_query=calls, ) accepted = plan is not None if config.motion_replan_steps: prediction.update( query_kind="motion_replan" if replan else "goal_start", candidate_target=target.tolist(), accepted=accepted, active_target=executor.target.tolist(), query_state_before=query_state_before, **executor_trace(executor), candidate_path_steps=0 if plan is None else len(plan["position"]), dry_run_state_unchanged=unchanged, inference_wall_s=inference_wall_s, inference_planning_wall_s=inference_wall_s + prediction["planning_wall_s"], deadline_50ms_exceeded=inference_wall_s + prediction["planning_wall_s"] > 0.05, deadline_200ms_exceeded=inference_wall_s + prediction["planning_wall_s"] > 0.2, observation_file=str( observation_path.relative_to(config.output_dir) ), observation_sha256=hashlib.sha256( observation_path.read_bytes() ).hexdigest(), ) if accepted: prediction["first_command_minus_qpos"] = ( executor.path[0] - before[:7] ).tolist() prediction["first_command_minus_previous"] = ( None if previous_command is None else ( executor.path[0] - previous_command[:7] ).tolist() ) # A failed candidate must never become the executed target. target = executor.target.clone() predictions.write(json.dumps(prediction) + "\n") phase_before = executor.phase if terminal_command is not None: command = terminal_command.copy() if hold_started_step is None: hold_started_step = step terminal_hold_steps += 1 details = { "phase": "terminal_hold", "held_command": command.tolist(), } elif planner is None: command_tensor, details = reactive_action( torch.tensor(before[18:25])[None], target[None], grip, control, gripper_gate=config.reactive_gripper_gate, ) command = command_tensor[0].numpy() grip = command_tensor[:, -1].clone() else: command, details = executor.command(before[18:25]) obs, _, terminated, truncated, info = env.step(command) if config.motion_replan_steps and details["phase"] == "trajectory": executor.observe_motion_step() measured_gripper = ( feedback_reader.read( float(command[-1]) if config.carry_gripper_feedback else executor.gripper ) if planner is not None and details["phase"] != "terminal_hold" else None ) if planner is not None and details["phase"] == "gripper": details["gripper_feedback"] = executor.observe_gripper( measured_gripper ) elif ( planner is not None and config.carry_gripper_feedback and details["phase"] == "trajectory" ): details["motion_gripper_feedback"] = ( executor.observe_motion_gripper(measured_gripper) ) if config.motion_replan_steps: details.update( **executor_trace(executor), phase_before=phase_before, phase_after=executor.phase, qpos_before=before[:9].tolist(), qvel_before=before[9:18].tolist(), qvel_after=obs["state"][9:18].tolist(), completion_published=details.get( "gripper_feedback", {} ).get("status") == "complete", ) previous_command = command.copy() if config.first_close_hold: completed_now = ( details.get("gripper_feedback", {}).get("status") == "complete" ) details.update( first_close_hold_query=first_close_hold_query, first_close_hold_active=calls == first_close_hold_query, arm_pose_executed=False if calls == first_close_hold_query else (True if completed_now else None), request_feedback_completed=completed_now, completed_target_from_query=executor.completed_target_query, completed_target_arm_pose_executed=None if executor.completed_target_query is None else executor.completed_target_query != first_close_hold_query, ) previous_command = command.copy() if config.hold_after_first_release: if terminal_command is None: terminal_command = completed_target_hold_command( command, details.get("gripper_feedback", {}), query=calls, hold_query=release_query, ) if terminal_command is not None: release_feedback_complete_step = step details.update( release_query=release_query, release_request_step=release_request_step, release_feedback_complete_step=release_feedback_complete_step, hold_started_step=hold_started_step, terminal_hold_steps=terminal_hold_steps, ) previous_command = command.copy() if stop_enabled: if stop_feedback_complete_step is None: completed_command = completed_target_hold_command( command, details.get("gripper_feedback", {}), query=calls, hold_query=stop_query, ) if completed_command is not None: stop_feedback_complete_step = step if config.honor_predicted_stop: terminal_command = completed_command details.update( stop_query=stop_query, stop_request_step=stop_request_step, stop_feedback_complete_step=stop_feedback_complete_step, hold_started_step=hold_started_step, terminal_hold_steps=terminal_hold_steps, ) if config.terminal_gripper_event: details.update( terminal_event_query=terminal_event_query, terminal_gripper_event_active=calls == terminal_event_query, arm_pose_executed=False if calls == terminal_event_query else None, ) assert not terminated and bool(truncated) == ( step == config.max_steps - 1 ) trace.write( json.dumps( { "seed": seed, "step": step, "query": calls, "target": target.tolist(), "command": command.tolist(), "tcp_before": before[18:25].tolist(), "tcp_after": obs["state"][18:25].tolist(), "qpos_after": obs["state"][:9].tolist(), "success": bool(info["success"]), **details, } ) + "\n" ) row = {k: np.asarray(v).item() for k, v in info["episode"].items()} row.update( seed=seed, audit_release_once=bool(info["audit_release_once"]), audit_release_at_end=bool(info["audit_release_at_end"]), steps=config.max_steps, policy_calls=calls, planning_failures=failures, completed_plans=executor.completed_goals if config.motion_replan_steps else plans_completed + int(planner is not None and executor.needs_prediction), last_phase="terminal_hold" if terminal_hold_steps else executor.phase if planner else "reactive", # Cumulative: resuming clears the phase that used to record it. # With resume disabled a timeout is terminal, so this still # equals the previous 0/1 indicator on every scored run. gripper_timeouts=executor.gripper_timeouts if planner else 0, gripper_arrests=executor.gripper_arrests if planner else 0, ) if config.carry_gripper_feedback: row["gripper_feedback_carried"] = executor.gripper_feedback_carried if config.phase_gripper_events: row["gripper_event_queries"] = gripper_events if config.first_close_hold: row.update( first_close_hold_queries=int( first_close_hold_query is not None ), first_close_hold_query=first_close_hold_query, ) if config.hold_after_first_release: row.update( release_query=release_query, release_request_step=release_request_step, release_feedback_complete_step=release_feedback_complete_step, hold_started_step=hold_started_step, terminal_hold_steps=terminal_hold_steps, held_command=None if terminal_command is None else terminal_command.tolist(), ) if stop_enabled: row.update( stop_query=stop_query, stop_request_step=stop_request_step, stop_feedback_complete_step=stop_feedback_complete_step, honor_predicted_stop=config.honor_predicted_stop, hold_started_step=hold_started_step, terminal_hold_steps=terminal_hold_steps, held_command=None if terminal_command is None else terminal_command.tolist(), ) if config.terminal_gripper_event: row["terminal_event_query"] = terminal_event_query if config.motion_replan_steps: row.update( completed_goals=executor.completed_goals, accepted_paths=executor.accepted_paths, replan_attempts=executor.replan_attempts, replan_failures=executor.replan_failures, total_motion_steps=executor.total_motion_steps, unfinished_path_steps=len(executor.path) - executor.index if executor.phase == "trajectory" else 0, ) episodes.append(row) with (config.output_dir / "episodes.jsonl").open("a") as stream: stream.write(json.dumps(row) + "\n") predictions.flush() trace.flush() print("EPISODE_COMPLETE", json.dumps(row), flush=True) finally: env.close() from mani_skill.examples.motionplanning.base_motionplanner import motionplanner
result = { "config": config.model_dump(mode="json"), "provenance": provenance | source_provenance(reference), "policy": reference.policy.model_dump(mode="json"), "sensor_configs": sensor, "control_mode": control_mode, "control_hz": 20, "diagnostic": config.training_dataset is not None or config.first_target_xyz_alpha is not None or config.first_target_xy != "predicted" or config.every_target_xy != "predicted" or config.max_steps != 200 or not config.reactive_gripper_gate or dense_endpoint or relative_endpoint, "pose_control_diagnostics": control.model_dump(mode="json"), "target_semantics": ( "Compose all 30 decoded deltas assuming perfect tracking; only final gripper is retained. " "Intermediate motion and gripper events are discarded, then re-planned by the unchanged executor." if dense_endpoint else ( "Last predicted relative target restored from the fixed chunk-start TCP; only final gripper retained." if relative_endpoint else "Latest query-zero world keypose" ) ), "episodes": len(episodes), "counts": { k: sum(r[k] for r in episodes) for k in ( "success_once", "success_at_end", "audit_release_once", "audit_release_at_end", ) }, "policy_calls": sum(r["policy_calls"] for r in episodes), "planning_failures": sum(r["planning_failures"] for r in episodes), "started_epoch": started, "ended_epoch": time.time(), "planner_source_sha256": hashlib.sha256( Path(inspect.getfile(motionplanner)).read_bytes() ).hexdigest(), "scope": f"Frozen final EMA ({config.target_source}); {config.max_steps} physical steps per scene. Planned: full joint trajectory then measured finger position/velocity or bilateral contact stability. Contact feedback only in executor, no task labels in model inputs or model updates. Timeout holds without replanning; TCP errors diagnostic only. Control20Hz is not fresh-observation policy20Hz." + ( f" Motion-only target updates after {config.motion_replan_steps} actual path steps; latest accepted path completes before gripper feedback. Failed replan retains old target/path/index. Completed context changes only on real feedback completion; unexecuted targets never enter it. No temporal ensemble. Additional inference/planning cost is logged; no continuity or realtime guarantee." if config.motion_replan_steps else "" ) + ( " Historical requested-target context retains the previous raw model request after feedback completion; initially invalid. The first-close-hold request bypasses its arm pose, so that context does not claim the pose executed or was reached. No expert target or phase is supplied." if context_enabled and config.first_close_hold else " Completed-target context comes only from the previous model target after executor completion; initially invalid. The zero-context control masks this input inside its model. No expert target or phase is supplied." if context_enabled else "" ) + ( " First-close hold is an actuator intervention: the first negative gripper request following an actual nonnegative gripper command holds measured joints and applies the unchanged continuous gripper request with native clipping/feedback. The raw requested pose is bypassed, not corrected. Trigger uses no query number, expert phase or task geometry. completed_plans includes this feedback-completed request and does not certify all poses executed." if config.first_close_hold else "" ) + ( " First predicted release after an actual negative gripper command executes its original full path and gripper feedback, then holds the last executed command through the unchanged horizon without further queries. This heuristic does not use task success, certify release, or implement a learned stop. Failure/timeout never enters terminal hold." if config.hold_after_first_release else "" ) + ( " Stop-after-target logits are read from the same zero-latent forward, with fixed probability threshold 0.5. Enabled execution holds the last actual command only after the selected request's declared execution and gripper feedback complete, through the unchanged horizon. Ignored execution records the same prediction without changing commands or queries. Task success, expert phase, and gripper sign never substitute for predicted terminal intent." if stop_enabled else "" ) + ( " A predicted terminal target with a nonnegative gripper request bypasses its arm pose: measured joints are held while the original continuous gripper request is completed by feedback, then the existing stop holds its last command to horizon. This request's raw world pose was not executed, and is never passed into a subsequent query. Completion counts refer to the gripper event, not reaching the bypassed world pose." if config.terminal_gripper_event else "" ) + ( " Privileged first-query XYZ = saved training approach XYZ + alpha * model residual. Rotation, gripper and all subsequent targets remain predicted. Every alpha, including the alpha=1 identity control, is an oracle diagnostic, not learned-policy performance." if first_xyz_oracle is not None else "" ) + ( " Motion-time stable feedback can complete an unchanged gripper command at the final path step; changed commands still require post-path feedback." if config.carry_gripper_feedback else "" ) + ( " Reactive gripper gate disabled: only the gripper scalar is replaced by the clipped model request; arm motion commands are unchanged." if not config.reactive_gripper_gate else "" ) + ( " The current prior-mode phase argmax selects arm hold for close/open events; continuous gripper is still the model prediction. No expert phase, forced stage order, or forced gripper sign. completed_plans counts completed action targets including gripper events." if config.phase_gripper_events else " Phase logits and argmax are diagnostic outputs from the current prior-mode policy forward only; no environment phase labels, target changes or phase-based execution decisions." if reference.policy.keypose_phase_weight > 0 else "" ), } (config.output_dir / "result.json").write_text(json.dumps(result, indent=2) + "\n") print("PLANNED_COMPARISON_COMPLETE", json.dumps(result), flush=True)
if __name__ == "__main__": run(CliApp.run(EvaluationConfig))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228"""Inference-only gripper interventions around the unchanged native evaluator."""
import jsonfrom collections import dequefrom pathlib import Pathfrom typing import Any, Literal
import numpy as npimport torchfrom pydantic import BaseModel, ConfigDict, PositiveInt
class GripperExecutionConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) aggregation: Literal["native", "latest"] = "native" """Native temporal mean, or the newest chunk's first gripper prediction only.""" binary: bool = False """Threshold the gripper at zero after aggregation; BCE already does this.""" trace: bool = False """Write every aligned chunk contribution and actual physical command."""
@property def active(self): return self.trace or self.binary or self.aggregation != "native"
class GripperTraceConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) execution: GripperExecutionConfig """Execution intervention, separate from the checkpoint's training policy.""" output_dir: Path """Evaluation directory for gripper_steps.jsonl.""" num_envs: PositiveInt """Synchronous vector slots, each with exactly one model query per step.""" horizon: PositiveInt """Number of predicted actions per chunk.""" seed_start: int """Recorder's explicit initial scene seed; each batch advances num_envs.""" bce: bool """Whether the model output is 2*p(open)-1 rather than continuous L1 output."""
class GripperTrace: def __init__(self, config: GripperTraceConfig): self.config = config self.chunks = deque(maxlen=config.horizon) self.step = 0 self.batch = 0 self.pending = None self.command = None self.rows = 0 self.disagreements = 0 self.stream = ( (config.output_dir / "gripper_steps.jsonl").open("x") if config.execution.trace else None )
def reset(self): self.chunks.clear() self.step = 0 self.batch = 0 self.pending = None self.command = None
def prediction(self, chunk): if chunk.shape != (self.config.num_envs, self.config.horizon, 10): raise ValueError("Expected one finite 10D pose chunk per vector slot") if not torch.isfinite(chunk).all(): raise ValueError("Nonfinite policy chunk") if self.chunks and self.chunks[-1][0] == self.step: raise ValueError("More than one prediction for the same physical step") self.chunks.append((self.step, chunk.detach().clone()))
def select(self, native_action): if not self.chunks or self.chunks[-1][0] != self.step: raise ValueError("Physical action must follow a fresh observation query") native = np.asarray(native_action) times = [time for time, _ in self.chunks] aligned = torch.stack( [chunk[:, self.step - time] for time, chunk in self.chunks], dim=1 ) # Exact vendor ordering: oldest to newest; older predictions get slightly # larger weights. This recomputation audits; it NEVER replaces native pose. weights = torch.exp(-0.01 * torch.arange(len(times), device=aligned.device)) weights = weights / weights.sum() reconstructed = (aligned * weights[None, :, None]).sum(dim=1).cpu().numpy() np.testing.assert_allclose(native, reconstructed, rtol=1e-5, atol=1e-6) selected = np.array(native, copy=True) latest = self.chunks[-1][1][:, 0, -1].cpu().numpy() if self.config.execution.aggregation == "latest": selected[:, -1] = latest self.pending = { "chunk_created_step0": times, "chunk_action_index": [self.step - time for time in times], "weights": weights.cpu().tolist(), "aligned_gripper": aligned[..., -1].cpu().numpy(), "native": native.copy(), "selected": selected.copy(), "latest": latest.copy(), } return selected
def physical_command(self, action): if self.pending is None or self.command is not None: raise ValueError("Unexpected physical command ordering") self.command = np.array(action, copy=True)
def completed(self, terminated, truncated): pending, command = self.pending, self.command if pending is None or command is None: raise ValueError("Missing prediction or physical command record") expected = pending["selected"][:, -1] if self.config.bce or self.config.execution.binary: expected = np.where(expected >= 0, 1.0, -1.0) np.testing.assert_array_equal(command[:, -1], expected) for slot in range(self.config.num_envs): row = { "seed": self.config.seed_start + self.batch * self.config.num_envs + slot, "step0": self.step, "post_action_step": self.step + 1, "chunk_created_step0": pending["chunk_created_step0"], "chunk_action_index": pending["chunk_action_index"], "weights": pending["weights"], "chunk_gripper_scores": pending["aligned_gripper"][slot].tolist(), "latest_gripper_score": float(pending["latest"][slot]), "native_gripper_score": float(pending["native"][slot, -1]), "selected_gripper_score": float(pending["selected"][slot, -1]), "native_action_6d": pending["native"][slot].tolist(), "selected_action_6d": pending["selected"][slot].tolist(), "controller_command": command[slot].tolist(), } if self.config.bce: row["chunk_p_open"] = ( (pending["aligned_gripper"][slot] + 1) / 2 ).tolist() row["latest_p_open"] = (row["latest_gripper_score"] + 1) / 2 row["native_p_open"] = (row["native_gripper_score"] + 1) / 2 self.disagreements += int( (row["latest_gripper_score"] >= 0) != (row["native_gripper_score"] >= 0) ) if self.stream is not None: self.stream.write(json.dumps(row, allow_nan=False) + "\n") self.rows += 1 self.pending = self.command = None if np.asarray(truncated).any(): if not np.asarray(truncated).all(): raise ValueError("Native ACT requires simultaneous vector truncation") self.chunks.clear() self.batch += 1 self.step = 0 if self.stream is not None: self.stream.flush() else: if np.asarray(terminated).any(): raise ValueError("Native ACT requires ignore_terminations=True") self.step += 1
def diagnostics(self): return { "recorded_commands": self.rows, "latest_native_sign_disagreements": self.disagreements, "aggregation": self.config.execution.aggregation, "binary": self.config.bce or self.config.execution.binary, "trace": "gripper_steps.jsonl" if self.stream is not None else None, "weights": "exp(-0.01*rank), normalized; oldest prediction rank=0", "scope": "controller input, before the controller's own clipping; " "probabilities only for BCE; geometry is diagnostic video metadata only", }
def close(self): if self.stream is not None: self.stream.close()
class GripperBoundaryConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) wrapped: Any """Existing agent or environment; all unrelated behavior is delegated.""" trace: Any """Shared per-evaluation GripperTrace; never passed into the learned policy."""
class GripperAgent: def __init__(self, config: GripperBoundaryConfig): self.config = config
def __getattr__(self, name): return getattr(self.config.wrapped, name)
def get_action(self, obs): chunk = self.config.wrapped.get_action(obs) self.config.trace.prediction(chunk) return chunk
class GripperDecisionEnv: def __init__(self, config: GripperBoundaryConfig): self.config = config
def __getattr__(self, name): return getattr(self.config.wrapped, name)
def reset(self, *args, **kwargs): self.config.trace.reset() return self.config.wrapped.reset(*args, **kwargs)
def step(self, action): selected = self.config.trace.select(action) result = self.config.wrapped.step(selected) self.config.trace.completed(result[2], result[3]) return result
class GripperPhysicalEnv: def __init__(self, config: GripperBoundaryConfig): self.config = config
def __getattr__(self, name): return getattr(self.config.wrapped, name)
def step(self, action): self.config.trace.physical_command(action) return self.config.wrapped.step(action)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213"""Measured gripper completion and a CPU SAPIEN feedback adapter."""
from collections import defaultdictfrom typing import Any
import numpy as npfrom pydantic import BaseModel, ConfigDict, PositiveFloat, PositiveInt
class GripperCompletionConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) position_tolerance_m: PositiveFloat = 0.001 """Maximum absolute position error of each finger for target completion.""" velocity_tolerance_m_s: PositiveFloat = 0.005 """Maximum absolute velocity of either finger for stable completion.""" stable_steps: PositiveInt = 3 """Consecutive post-action feedback samples required for the same condition.""" timeout_steps: PositiveInt = 40 """Maximum actual gripper control steps; timeout is not completion.""" minimum_contact_force_n: PositiveFloat = 0.5 """Per-finger force threshold for bilateral contact against one external body.""" detect_arrest: bool = False """Recognise a driven-but-frozen finger as arrested instead of waiting out the timeout. The original contract only exits a BLOCKED CLOSING, because closing_against_object requires position > target; a blocked opening has no exit and its finite-difference velocity reads ~0 while the joint is still driven. Default false preserves every previously scored run.""" arrest_encoder_tolerance_m: PositiveFloat = 0.0001 """Maximum encoder displacement per step still counted as frozen.""" arrest_drive_velocity_m_s: PositiveFloat = 0.05 """Minimum instantaneous joint velocity proving the drive is still pushing.""" arrest_steps: PositiveInt = 5 """Consecutive frozen-but-driven samples required to declare an arrest."""
class GripperMeasurement(BaseModel, frozen=True): model_config = ConfigDict( extra="forbid", use_attribute_docstrings=True, allow_inf_nan=False ) positions_m: tuple[float, float] """Measured positions of the two finger joints.""" velocities_m_s: tuple[float, float] """Measured encoder displacement over the last physical control interval.""" targets_m: tuple[float, float] """Command mapped to physical joint coordinates and clipped to joint limits.""" bilateral_contact: bool """Both finger inner sides currently contact the same external body.""" contact_forces_n: tuple[float, float] = (0.0, 0.0) """Force components along the inner-finger normals for the accepted pair.""" joint_velocities_m_s: tuple[float, float] = (0.0, 0.0) """Instantaneous simulator joint velocities, logged separately for diagnosis."""
class GripperCompletion: def __init__(self, config: GripperCompletionConfig): self.config = config self.steps = 0 self.streak = 0 self.arrested_streak = 0 self.condition = None self.status = "running"
def update(self, measured: GripperMeasurement): if self.status != "running": raise RuntimeError("Completion monitor already ended") self.steps += 1 position = np.asarray(measured.positions_m) target = np.asarray(measured.targets_m) error = np.abs(position - target) stationary = ( max(abs(v) for v in measured.velocities_m_s) <= self.config.velocity_tolerance_m_s ) at_target = bool(np.all(error <= self.config.position_tolerance_m)) # Contact can complete a closing command, never a blocked opening. closing_against_object = bool( np.all(position >= target - self.config.position_tolerance_m) and np.any(position > target + self.config.position_tolerance_m) ) condition = None if stationary: if at_target: condition = "target_reached" elif closing_against_object and measured.bilateral_contact: condition = "contact_stable" self.streak = ( self.streak + 1 if condition is not None and condition == self.condition else int(condition is not None) ) self.condition = condition # Frozen encoder while the drive still pushes: the finger is held by # something. Never reported as completion, since the command was not met. frozen = ( max(abs(v) for v in measured.velocities_m_s) <= self.config.arrest_encoder_tolerance_m ) driven = ( max(abs(v) for v in measured.joint_velocities_m_s) >= self.config.arrest_drive_velocity_m_s ) arrested = bool(frozen and driven and not at_target) self.arrested_streak = self.arrested_streak + 1 if arrested else 0 if self.streak >= self.config.stable_steps: self.status = "complete" elif ( self.config.detect_arrest and self.arrested_streak >= self.config.arrest_steps ): self.status = "arrested" elif self.steps >= self.config.timeout_steps: self.status = "timeout" return { **measured.model_dump(mode="json"), "position_error_m": error.tolist(), "stationary": stationary, "condition": condition, "stable_steps": self.streak, "arrested": arrested, "arrested_steps": self.arrested_streak, "elapsed_steps": self.steps, "status": self.status, }
class FeedbackReaderConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) env: Any """One CPU Panda physical environment exposing encoders and contact impulses.""" completion: GripperCompletionConfig = GripperCompletionConfig() """Contact-force threshold shared with the completion contract."""
class PandaGripperFeedback: def __init__(self, config: FeedbackReaderConfig): self.config = config base = config.env.unwrapped if base.gpu_sim_enabled or base.num_envs != 1: raise ValueError("Feedback adapter requires a single CPU environment") self.robot = base.agent.robot self.fingers = (base.agent.finger1_link, base.agent.finger2_link) self.finger_entities = tuple(f._bodies[0].entity for f in self.fingers) self.robot_entities = { link._bodies[0].entity for link in self.robot.get_links() } self.controller = base.agent.controller.controllers["gripper"] if ( self.controller.config.use_delta or not self.controller.config.normalize_action ): raise ValueError("Expected normalized absolute gripper commands") self.joint_indices = [ self.robot.active_joints_map[name].active_index[0].item() for name in base.agent.gripper_joint_names ] self.limits = self.robot.get_qlimits()[0, self.joint_indices].cpu().numpy() self.previous_positions = ( self.robot.get_qpos()[0, self.joint_indices].cpu().numpy().copy() )
def read(self, command): base = self.config.env.unwrapped # Backend contact adapter: no cube identity, task success, or geometry is # used. Contact against arbitrary external bodies is tactile-style input. forces = defaultdict(lambda: np.zeros((2, 3))) for contact in base.scene.get_contacts(): entities = [body.entity for body in contact.bodies] for finger, entity in enumerate(self.finger_entities): if entity not in entities: continue index = entities.index(entity) other = entities[1 - index] if other in self.robot_entities: continue impulse = np.sum([point.impulse for point in contact.points], axis=0) forces[other][finger] += ( impulse * (1 if index == 0 else -1) / base.scene.px.timestep ) directions = np.stack( [ self.fingers[0].pose.to_transformation_matrix()[0, :3, 1].cpu().numpy(), -self.fingers[1] .pose.to_transformation_matrix()[0, :3, 1] .cpu() .numpy(), ] ) bilateral = False magnitudes = np.zeros(2) for pair in forces.values(): normal_forces = (pair * directions).sum(axis=1) if np.all(normal_forces >= self.config.completion.minimum_contact_force_n): bilateral = True magnitudes = normal_forces break lower, upper = self.controller.config.lower, self.controller.config.upper requested = (float(np.clip(command, -1, 1)) + 1) / 2 * (upper - lower) + lower targets = np.clip(np.full(2, requested), self.limits[:, 0], self.limits[:, 1]) positions = self.robot.get_qpos()[0, self.joint_indices].cpu().numpy().copy() velocity = (positions - self.previous_positions) / base.control_timestep self.previous_positions = positions return GripperMeasurement( positions_m=tuple(positions), velocities_m_s=tuple(velocity), joint_velocities_m_s=tuple( self.robot.get_qvel()[0, self.joint_indices].cpu().tolist() ), targets_m=tuple(targets), bilateral_contact=bilateral, contact_forces_n=tuple(magnitudes), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""Run one declared GPU job with durable output and measured process lifetime."""
import jsonimport osimport signalimport subprocessimport timefrom pathlib import Path
from pydantic import BaseModel, ConfigDict, Field, NonNegativeInt, PositiveIntfrom pydantic_settings import CliApp
class JobConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) command: list[str] = Field(min_length=1) """Exact executable and arguments; executed without a shell.""" cwd: Path """Working directory for the program and its generated outputs.""" output_dir: Path """New job ledger directory containing process.log and result.json.""" gpu: NonNegativeInt """Physical GPU index assigned to this job through CUDA_VISIBLE_DEVICES.""" timeout_s: PositiveInt = 7200 """Maximum allocated job duration, including startup, loading and evaluation."""
class JobCLIConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) spec: Path """JSON file containing the single validated JobConfig."""
def run_job(config: JobConfig): config.output_dir.mkdir(parents=True, exist_ok=True) if (config.output_dir / "launch.json").exists(): raise ValueError("Job was already launched; use a new declared run directory") env = os.environ.copy() env.update(CUDA_VISIBLE_DEVICES=str(config.gpu), PYTHONUNBUFFERED="1") started = time.monotonic() epoch = time.time() result = {"config": config.model_dump(mode="json"), "started_epoch": epoch} (config.output_dir / "launch.json").write_text(json.dumps(result, indent=2)) process = None
def interrupt(signum, frame): raise KeyboardInterrupt(f"Job runner received signal {signum}")
late = [] previous = signal.signal(signal.SIGTERM, interrupt) try: with (config.output_dir / "process.log").open("w") as log: process = subprocess.Popen( config.command, cwd=config.cwd, env=env, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, start_new_session=True, ) result["pid"] = process.pid result["exit_code"] = process.wait(timeout=config.timeout_s) result["status"] = "complete" if result["exit_code"] == 0 else "failed" except subprocess.TimeoutExpired: result.update(status="timeout", exit_code=None) except KeyboardInterrupt: result.update(status="interrupted", exit_code=None) except (OSError, ValueError) as error: result.update( status="failed", exit_code=None, error=f"{type(error).__name__}: {error}" ) finally: # A repeated or late SIGTERM must not abort cleanup (child kill and # result.json); it is recorded here and honoured once the ledger exists. signal.signal(signal.SIGTERM, lambda signum, frame: late.append(signum)) if process is not None and process.poll() is None: os.killpg(process.pid, signal.SIGTERM) try: process.wait(timeout=20) except subprocess.TimeoutExpired: os.killpg(process.pid, signal.SIGKILL) process.wait() result.update( ended_epoch=time.time(), allocated_device_wall_s=time.monotonic() - started ) result["timing_scope"] = ( "one assigned GPU job process lifetime, including CPU startup/data/evaluation; not GPU utilization integration" ) (config.output_dir / "result.json").write_text(json.dumps(result, indent=2)) signal.signal(signal.SIGTERM, signal.SIG_DFL if previous is None else previous) print("JOB_COMPLETE", json.dumps(result), flush=True) if result["status"] != "complete": raise SystemExit(1) if late: # The job itself finished; the stop request still ends the caller's queue. raise KeyboardInterrupt(f"Job runner received signal {late[0]} during cleanup")
if __name__ == "__main__": args = CliApp.run(JobCLIConfig) run_job(JobConfig.model_validate_json(args.spec.read_text()))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156"""Explicit completed-goal context for both native ACT state projections.
Training supplies the previous primitive's recorded target. Deployment mustsupply only a model target whose path and gripper execution have completed.The wrapper never infers a phase, advances a state machine, or reads task state."""
from typing import Literal
import torchfrom pydantic import BaseModel, ConfigDictfrom torch import nn
from lim.normalization import FittedNormalizationConfig
KeyposeContextMode = Literal["none", "zero", "previous_target"]STATE_DIM = 25CONTEXT_DIM = 11
class ContextProjectionConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) state_projection: nn.Linear """Existing state25 projection; preserve its parameters and bias verbatim."""
class StateContextProjection(nn.Module): """Project concatenated state25/context11 through separate additive paths."""
def __init__(self, config: ContextProjectionConfig): super().__init__() self.config = config self.state = config.state_projection if self.state.in_features != STATE_DIM: raise ValueError( "Completed-goal context requires the audited state25 projection" ) self.in_features = STATE_DIM + CONTEXT_DIM self.out_features = self.state.out_features self.context = nn.Linear( CONTEXT_DIM, self.state.out_features, bias=False, device=self.state.weight.device, dtype=self.state.weight.dtype, )
def forward(self, combined): if combined.shape[-1] != self.in_features: raise ValueError("Expected concatenated state25 and completed-target11") return self.state(combined[..., :STATE_DIM]) + self.context( combined[..., STATE_DIM:] )
class KeyposeContextModelConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) model: nn.Module """Pinned DETRVAE before NormalizedModel wraps the state/action contract.""" mode: KeyposeContextMode """Zero ablation or previous_target; none must keep the original model unwrapped.""" statistics: FittedNormalizationConfig """Original checkpoint-owned affine action statistics for the context target10."""
class KeyposeContextModel(nn.Module): def __init__(self, config: KeyposeContextModelConfig): super().__init__() self.config = config if config.mode == "none": raise ValueError( "Disabled completed-goal context must not wrap the native model" ) if len(config.statistics.action.center) != 10: raise ValueError( "Completed-goal context requires world keypose10 statistics" ) self.base = config.model prior = self.base.input_proj_robot_state posterior = self.base.encoder_state_proj if ( not isinstance(prior, nn.Linear) or not isinstance(posterior, nn.Linear) or prior.in_features != STATE_DIM or posterior.in_features != STATE_DIM or prior.out_features != posterior.out_features or prior.weight.device != posterior.weight.device ): raise ValueError( "Expected matching native prior/posterior state25 projections" ) devices = [prior.weight.device.index] if prior.weight.is_cuda else [] # One fork for both draws gives distinct context projections while # preserving all caller RNG streams (native weights, EMA and sampling). with torch.random.fork_rng(devices=devices): self.base.input_proj_robot_state = StateContextProjection( ContextProjectionConfig(state_projection=prior) ) self.base.encoder_state_proj = StateContextProjection( ContextProjectionConfig(state_projection=posterior) ) self.register_buffer( "action_center", torch.tensor(config.statistics.action.center), persistent=False, ) self.register_buffer( "action_scale", torch.tensor(config.statistics.action.scale), persistent=False, )
def encode_context(self, obs): state = obs["state"] if state.ndim != 2 or state.shape[-1] != STATE_DIM: raise ValueError( "Expected batch x state25 before appending completed-goal context" ) if self.config.mode == "zero": # Ablation carries no completed-goal signal, including the valid bit. return state.new_zeros((state.shape[0], CONTEXT_DIM)) if "completed_target" not in obs: raise ValueError( "previous_target policy requires explicit completed_target observations" ) context = torch.as_tensor( obs["completed_target"], device=state.device, dtype=state.dtype ) if context.shape != (state.shape[0], CONTEXT_DIM): raise ValueError("Expected completed_target shape batch x 11") validity = context[:, -1] if not ((validity == 0) | (validity == 1)).all(): raise ValueError("Completed-target validity must be exactly zero or one") valid = validity.bool() if not torch.isfinite(context[valid, :10]).all(): raise ValueError( "A valid completed target must contain finite world keypose10" ) # Mask before and after normalization: invalid placeholders can never # leak a centering offset, NaN, or previous episode's target. target = context[:, :10].masked_fill(~valid[:, None], 0) target = ((target - self.action_center) / self.action_scale).masked_fill( ~valid[:, None], 0 ) return torch.cat([target, validity[:, None]], dim=-1)
def forward(self, obs, actions=None): context = self.encode_context(obs) combined = torch.cat([obs["state"], context], dim=-1) # The native forward sees the combined vector in both state projections; # action targets and RGB pass through unchanged. No hooks/global state. return self.base({**obs, "state": combined}, actions)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139"""Observed TCP feedback for world-frame position/6D-orientation keypose commands."""
from typing import Any
import torchfrom mani_skill.utils.geometry.rotation_conversions import ( axis_angle_to_matrix, matrix_to_axis_angle, matrix_to_euler_angles, quaternion_to_matrix,)from pydantic import BaseModel, ConfigDict, PositiveFloat
from lim.action_encoding import ROTATION_SCALE, matrix_to_sixd, sixd_to_matrix
class KeyposeControlConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) max_translation_m: PositiveFloat = 0.01 """Maximum requested Cartesian displacement per 20 Hz control step.""" max_rotation_rad: PositiveFloat = 0.05 """Maximum requested SO(3) angle per control step, before controller decoding.""" position_tolerance_m: PositiveFloat = 0.003 """Measured TCP distance required before accepting the target gripper command.""" rotation_tolerance_rad: PositiveFloat = 0.05 """Measured angular distance required before accepting the target gripper command."""
def encode_keypose(pose, gripper): """Input xyz,wxyz; output world xyz, continuous6D rotation, continuous gripper.""" if pose.shape[-1] != 7 or not torch.isfinite(pose).all(): raise ValueError("Expected finite world xyz,wxyz poses") q = pose[..., 3:] if not torch.allclose(q.norm(dim=-1), torch.ones_like(q[..., 0]), atol=1e-4): raise ValueError("Keypose quaternions must be unit length") return torch.cat( [pose[..., :3], matrix_to_sixd(quaternion_to_matrix(q)), gripper[..., None]], -1 )
def keypose_error(current, target): if current.shape[-1] != 7 or target.shape[-1] != 10: raise ValueError("Expected observed TCP7 and target10") if not torch.isfinite(current).all() or not torch.isfinite(target).all(): raise ValueError("Nonfinite observed TCP or keypose target") delta = target[..., :3] - current[..., :3] rotation = sixd_to_matrix(target[..., 3:9]) @ quaternion_to_matrix( current[..., 3:] ).transpose(-1, -2) vector = matrix_to_axis_angle(rotation) return delta, vector
def keypose_command(current, target, previous_gripper, config: KeyposeControlConfig): """Pure observed-state controller; audited Panda root axes coincide with world.""" delta, rotation = keypose_error(current, target) position_error = delta.norm(dim=-1) rotation_error = rotation.norm(dim=-1) reached = (position_error <= config.position_tolerance_m) & ( rotation_error <= config.rotation_tolerance_rad ) translation = ( delta * (config.max_translation_m / position_error.clamp_min(1e-8)).clamp(max=1)[ ..., None ] ) vector = ( rotation * (config.max_rotation_rad / rotation_error.clamp_min(1e-8)).clamp(max=1)[ ..., None ] ) # Euler exists ONLY at the installed low-level controller boundary. Targets # and SO(3) error/interpolation never learn or interpolate Euler coordinates. angles = ( matrix_to_euler_angles(axis_angle_to_matrix(vector), "XYZ") / ROTATION_SCALE ) angles = angles / angles.norm(dim=-1, keepdim=True).clamp(min=1) gripper = torch.where(reached, target[..., -1].clamp(-1, 1), previous_gripper) command = torch.cat( [(translation / 0.1).clamp(-1, 1), angles, gripper[..., None]], -1 ) return command, reached, position_error, rotation_error
class KeyposeEnvConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) env: Any """Physical vector environment exposing full state25 observations.""" control: KeyposeControlConfig = KeyposeControlConfig() """Pure keypose tracking and gripper synchronization settings."""
class KeyposeEnv: def __init__(self, config: KeyposeEnvConfig): import gymnasium as gym import numpy as np
self.config = config self.current = None self.gripper = None self.action_space = gym.spaces.Box( -np.inf, np.inf, (config.env.num_envs, 10), dtype=np.float32 ) self.single_action_space = gym.spaces.Box( -np.inf, np.inf, (10,), dtype=np.float32 )
def __getattr__(self, name): return getattr(self.config.env, name)
def remember(self, obs, reset=None): state = torch.as_tensor(obs["state"], dtype=torch.float32) if state.shape[-1] != 25: raise ValueError("Expected audited qpos9,qvel9,TCP7 state layout") self.current = state[:, 18:25].clone() # Panda PDJointPosMimicController maps [-1,1] to [-.01,.04] m. measured = ((state[:, 7:9].mean(-1) + 0.01) / 0.05 * 2 - 1).clamp(-1, 1) if reset is None: self.gripper = measured else: self.gripper = torch.where(torch.as_tensor(reset), measured, self.gripper)
def reset(self, *args, **kwargs): obs, info = self.config.env.reset(*args, **kwargs) self.remember(obs) return obs, info
def step(self, target): command, _, _, _ = keypose_command( self.current, torch.as_tensor(target), self.gripper, self.config.control ) self.gripper = command[:, -1].clone() result = self.config.env.step(command.numpy()) self.remember(result[0], result[2] | result[3]) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317"""Keypose annotations with explicit pre-action/next-observation index semantics.
Dense observations and actions remain the canonical trajectory. Annotations areadditional supervision, never extra policy observations."""
from contextlib import ExitStackfrom pathlib import Pathfrom typing import Literal
import h5pyimport numpy as npfrom pydantic import BaseModel, ConfigDict, Field, NonNegativeInt, PositiveIntfrom pydantic_settings import CliApp
class KeyposeSegment(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) name: str """Human-readable expert primitive name.""" kind: Literal["move", "close", "open"] """Executed motion or gripper primitive; dry-run planning has no segment.""" start: NonNegativeInt """Inclusive action index, referring to the observation before that action.""" end: PositiveInt """Exclusive action index, also the achieved endpoint observation index.""" target_pose: tuple[float, ...] = Field(min_length=7, max_length=7) """Commanded world TCP position and quaternion in xyz,wxyz order.""" gripper: Literal[-1, 1] """Command during the segment; closing and opening are explicit events."""
class AnnotationConfig(BaseModel, frozen=True): model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid") segments: tuple[KeyposeSegment, ...] """Contiguous expert primitives in source-action coordinates.""" source_steps: PositiveInt """Number of source actions, before any controller conversion.""" target_to_source: tuple[int, ...] """Source action index for every actually executed target action."""
def annotation_arrays(config: AnnotationConfig) -> dict[str, np.ndarray]: segments = config.segments if ( not segments or segments[0].start != 0 or segments[-1].end != config.source_steps ): raise ValueError("Segments must cover all source actions") previous = 0 for segment in segments: if segment.start != previous or segment.end <= segment.start: raise ValueError("Segment gaps, overlap or empty primitive") pose = np.asarray(segment.target_pose) if not np.isfinite(pose).all() or not np.isclose( np.linalg.norm(pose[3:]), 1, atol=1e-4 ): raise ValueError( "Target poses must have finite values and unit quaternions" ) previous = segment.end mapping = np.asarray(config.target_to_source, dtype=np.int64) if ( not len(mapping) or mapping[0] != 0 or mapping[-1] != config.source_steps - 1 or not np.array_equal(np.unique(mapping), np.arange(config.source_steps)) or np.any(np.diff(mapping) < 0) ): raise ValueError("Replay mapping must cover every source action monotonically") source_ends = np.asarray([s.end for s in segments], dtype=np.int64) ends = np.searchsorted(mapping, source_ends, side="left") starts = np.r_[0, ends[:-1]] ids = np.searchsorted(ends, np.arange(len(mapping)), side="right") return { "start_action": starts, "end_action": ends, "source_start_action": np.asarray([s.start for s in segments], dtype=np.int64), "source_end_action": source_ends, "target_pose_world": np.asarray( [s.target_pose for s in segments], dtype=np.float32 ), "gripper_command": np.asarray([s.gripper for s in segments], dtype=np.float32), "action_keyframe_index": ids, "target_to_source_action": mapping, }
def write_annotations(group, config: AnnotationConfig): arrays = annotation_arrays(config) if len(group["actions"]) != len(arrays["action_keyframe_index"]): raise ValueError("Replay trace and saved actions differ") keyframes = group.create_group("keyframes") keyframes.attrs.update( schema_version=1, pose_frame="world", pose_encoding="xyz,wxyz", interval="actions[start:end]; obs[end] is the achieved endpoint", label_scope="supervision only; never policy input", ) for name, data in arrays.items(): keyframes.create_dataset(name, data=data) for name, values in { "name": [s.name for s in config.segments], "kind": [s.kind for s in config.segments], }.items(): keyframes.create_dataset(name, data=values, dtype=h5py.string_dtype("utf-8")) keyframes.create_dataset( "achieved_pose_world", data=group["obs/extra/tcp_pose"][:][arrays["end_action"]] )
class AuditConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) dataset: Path """Annotated ManiSkill H5; neighboring JSON supplies episode metadata.""" output: Path """New audit JSON; no existing audit is overwritten.""" source_dataset: Path | None = None """Annotated joint-control source for cross-file pose replay identity checks."""
def audit_dataset(config: AuditConfig): import hashlib import json
metadata = json.loads(config.dataset.with_suffix(".json").read_text()) rows = [] with ExitStack() as stack: data = stack.enter_context(h5py.File(config.dataset, "r")) source = None source_episodes = {} if config.source_dataset is not None: source = stack.enter_context(h5py.File(config.source_dataset, "r")) source_metadata = json.loads( config.source_dataset.with_suffix(".json").read_text() ) source_episodes = {e["episode_id"]: e for e in source_metadata["episodes"]} if len(data) != len(metadata["episodes"]): raise ValueError("Episode count differs from metadata") for episode in metadata["episodes"]: group = data[f"traj_{episode['episode_id']}"] actions = group["actions"][:] count = len(actions) key = group["keyframes"] starts, ends = key["start_action"][:], key["end_action"][:] if ( len(starts) == 0 or starts[0] != 0 or ends[-1] != count or np.any(ends <= starts) or not np.array_equal(starts[1:], ends[:-1]) ): raise ValueError("Invalid segment boundaries") if count != episode["elapsed_steps"] or not bool(group["success"][-1]): raise ValueError("Incomplete or unsuccessful saved demonstration")
def check_observation(name, item, count=count): if isinstance(item, h5py.Dataset): if len(item) != count + 1: raise ValueError(f"Dense observations dropped: {name}") if not np.isfinite(item[:]).all(): raise ValueError(f"Nonfinite observations: {name}")
group["obs"].visititems(check_observation) ids = key["action_keyframe_index"][:] expected_ids = np.repeat(np.arange(len(ends)), ends - starts) if not np.array_equal(ids, expected_ids): raise ValueError("Pre-action target labels are misaligned") for field in [ "name", "kind", "gripper_command", "target_pose_world", "achieved_pose_world", ]: if len(key[field]) != len(ends): raise ValueError(f"Wrong number of segment labels: {field}") kinds = key["kind"].asstr()[:] if not set(kinds).issubset({"move", "close", "open"}): raise ValueError("Unknown segment kind") commands = key["gripper_command"][:] if np.any(commands[kinds == "close"] != -1) or np.any( commands[kinds == "open"] != 1 ): raise ValueError("Gripper event type disagrees with its command") if not np.array_equal(actions[:, -1], key["gripper_command"][:][ids]): raise ValueError("Gripper event/action mismatch") actual = group["obs/extra/tcp_pose"][:][ends] if not np.array_equal(actual, key["achieved_pose_world"][:]): raise ValueError("Endpoint observation is misaligned") mapping = key["target_to_source_action"][:] source_ends = key["source_end_action"][:] source_starts = key["source_start_action"][:] if not np.array_equal(source_starts, np.r_[0, source_ends[:-1]]) or np.any( source_ends <= source_starts ): raise ValueError("Source segment boundaries are inconsistent") if not np.array_equal(np.unique(mapping), np.arange(source_ends[-1])): raise ValueError("Replay omitted source actions") if np.any(np.diff(mapping) < 0) or not np.array_equal( np.searchsorted(mapping, source_ends), ends ): raise ValueError("Replay boundary mapping is invalid") target = key["target_pose_world"][:] if not np.isfinite(actions).all() or not np.isfinite(target).all(): raise ValueError("Nonfinite actions or targets") if not np.allclose(np.linalg.norm(target[:, 3:], axis=1), 1, atol=1e-4): raise ValueError("Invalid quaternion target") image_differences = {} if source is not None: source_id = episode["source_episode_id"] source_group = source[f"traj_{source_id}"] if not ( episode["episode_seed"] == episode["source_episode_seed"] == source_episodes[source_id]["episode_seed"] ): raise ValueError("Source and target seed metadata disagree") for path in ["obs/agent/qpos", "obs/agent/qvel", "obs/extra/tcp_pose"]: np.testing.assert_allclose( group[path][0], source_group[path][0], rtol=0, atol=1e-6 ) for camera in ["base_camera", "hand_camera"]: path = f"obs/sensor_data/{camera}/rgb" difference = np.abs( group[path][0].astype(np.int16) - source_group[path][0].astype(np.int16) ) image_differences[camera] = { "bitwise_equal": not bool(difference.any()), "changed_channels": int(np.count_nonzero(difference)), "mean_abs_0_255": float(difference.mean()), "max_abs_0_255": int(difference.max()), } for parameter in ["cam2world_gl", "extrinsic_cv", "intrinsic_cv"]: path = f"obs/sensor_param/{camera}/{parameter}" np.testing.assert_allclose( group[path][0], source_group[path][0], rtol=0, atol=1e-6 ) for category in ["actors", "articulations"]: for entity in source_group[f"env_states/{category}"]: path = f"env_states/{category}/{entity}" np.testing.assert_array_equal( group[path][0], source_group[path][0] ) for field in ["name", "kind"]: np.testing.assert_array_equal( key[field].asstr()[:], source_group[f"keyframes/{field}"].asstr()[:], ) np.testing.assert_array_equal( source_starts, source_group["keyframes/start_action"][:] ) np.testing.assert_array_equal( target, source_group["keyframes/target_pose_world"][:] ) np.testing.assert_array_equal( source_ends, source_group["keyframes/end_action"][:] ) np.testing.assert_array_equal( actions[:, -1], source_group["actions"][:, -1][mapping] ) position_error = np.linalg.norm(actual[:, :3] - target[:, :3], axis=1) quat_a = actual[:, 3:] / np.linalg.norm( actual[:, 3:], axis=1, keepdims=True ) quat_b = target[:, 3:] / np.linalg.norm( target[:, 3:], axis=1, keepdims=True ) rotation_error = 2 * np.arccos( np.clip(np.abs((quat_a * quat_b).sum(1)), 0, 1) ) rows.append( { "episode_id": episode["episode_id"], "seed": episode["episode_seed"], "actions": count, "keyframes": len(ends), "position_error_m": position_error.tolist(), "rotation_error_deg": np.rad2deg(rotation_error).tolist(), "segments": key["name"].asstr()[:].tolist(), "initial_rgb_diagnostics": image_differences, } ) digest = hashlib.sha256() with config.dataset.open("rb") as f: for chunk in iter(lambda: f.read(8 * 1024 * 1024), b""): digest.update(chunk) result = { "status": "passed", "dataset": str(config.dataset), "sha256": digest.hexdigest(), "episodes": len(rows), "dense_actions": sum(r["actions"] for r in rows), "keyframes": sum(r["keyframes"] for r in rows), "source_identity_checked": config.source_dataset is not None, "rgb_bitwise_identity": all( d["bitwise_equal"] for row in rows for d in row["initial_rgb_diagnostics"].values() ) if config.source_dataset is not None else None, "rows": rows, "scope": "record integrity and endpoint error; no learned policy or sparse execution result", } config.output.parent.mkdir(parents=True, exist_ok=True) with config.output.open("x") as f: f.write(json.dumps(result, indent=2) + "\n") return result
if __name__ == "__main__": result = audit_dataset(CliApp.run(AuditConfig)) print({k: v for k, v in result.items() if k != "rows"})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135"""Dense future supervision sharing the decoder; never a deployed control branch."""
import hashlibfrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Any
import torchfrom pydantic import BaseModel, ConfigDict, PositiveIntfrom torch import nnfrom torch.utils.data import Dataset
from lim.action_encoding import controller_to_sixdfrom lim.normalization import ( FitNormalizationConfig, NormalizationConfig, fit_normalization,)
class DenseAuxiliaryHeadConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) primary: nn.Module """Existing action/stop projections, preserving their parameters and output.""" hidden_size: PositiveInt """Native decoder feature width; the experiment retains 256."""
class DenseAuxiliaryHead(nn.Module): def __init__(self, config: DenseAuxiliaryHeadConfig): super().__init__() self.config = config self.primary = config.primary parameter = next(self.primary.parameters()) devices = [parameter.device.index] if parameter.is_cuda else [] with torch.random.fork_rng(devices=devices): self.dense = nn.Linear( config.hidden_size, 10, device=parameter.device, dtype=parameter.dtype ) self.dense_actions = None
def forward(self, features): if features.ndim != 3 or features.shape[-1] != self.config.hidden_size: raise ValueError("Expected native batch x query x hidden decoder features") output = self.primary(features) self.dense_actions = self.dense(features) return output
def read_dense_actions(model): heads = [part for part in model.modules() if isinstance(part, DenseAuxiliaryHead)] if len(heads) != 1 or heads[0].dense_actions is None: raise ValueError( "Expected exactly one dense auxiliary head with a completed forward" ) return heads[0].dense_actions
def primary_state_sha256(model): """Recover the existing stop model's full initial state without the dense head.""" result = hashlib.sha256() for name, value in model.state_dict().items(): if ".action_head.dense." in name: continue name = name.replace(".action_head.primary.", ".action_head.") result.update(name.encode()) result.update(value.detach().cpu().contiguous().numpy().tobytes()) return result.hexdigest()
class DenseAuxiliaryDatasetConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) dataset: Any """Unnormalized current-keypose dataset; its native dataset retains raw control7.""" source: Path """Same H5 used for primary keyposes; no extra demonstration or observation.""" normalization: NormalizationConfig """The original dense action-zscore algorithm, separately fitted from raw actions."""
class DenseAuxiliaryDataset(Dataset): def __init__(self, config: DenseAuxiliaryDatasetConfig): self.config = config self.dataset = config.dataset native = self.dataset.dataset if ( self.dataset.slices != native.slices or self.dataset.num_queries != 30 or not native.delta_control or native.norm_stats is not None or config.normalization.method != "action_zscore" ): raise ValueError( "Dense auxiliary requires all original Q30 raw delta observations" ) self.dense = [ controller_to_sixd(action) for action in native.trajectories["actions"] ] population = SimpleNamespace( delta_control=True, norm_stats=None, trajectories={**native.trajectories, "actions": self.dense}, ) self.dense_statistics = fit_normalization( FitNormalizationConfig( dataset=population, normalization=config.normalization, action_encoding="rotation6d", source=config.source, ) ) self.center = torch.tensor(self.dense_statistics.action.center) self.scale = torch.tensor(self.dense_statistics.action.scale)
def __getattr__(self, name): return getattr(self.dataset, name)
def __len__(self): return len(self.dataset)
def __getitem__(self, index): sample = self.dataset[index] trajectory, step = self.dataset.slices[index] actions = self.dense[trajectory][step : step + self.num_queries] if len(actions) < self.num_queries: # Native delta padding: zero arm motion, retain last continuous gripper. pad = torch.cat([actions.new_zeros(9), actions[-1, -1:]]) actions = torch.cat( [actions, pad.repeat(self.num_queries - len(actions), 1)] ) return {**sample, "dense_actions": (actions - self.center) / self.scale}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205"""Explicit, logged interventions for frozen keypose diagnostics only."""
import hashlibimport jsonfrom pathlib import Pathfrom typing import Any
import gymnasium as gymimport h5pyimport numpy as npimport torchfrom pydantic import BaseModel, ConfigDict, Field
def predict_action_chunk(agent, observation): """Batch-one inference, including the checkpoint's native denormalization.""" with torch.inference_mode(): inputs = { k: torch.as_tensor(v, device="cuda")[None] for k, v in observation.items() } return agent.get_action(inputs)[0].cpu()
def predict_keypose(agent, observation): """The same batch-one/query-zero entrypoint for probes and closed-loop runs.""" return predict_action_chunk(agent, observation)[0]
def first_target_intervention(predicted, *, query, cube_xy=None): """Privileged XY only, on query one only; never mutate raw model output.""" target = predicted.clone() if cube_xy is not None: if query != 1: raise ValueError("First-target diagnostic must not affect later queries") xy = torch.as_tensor(cube_xy, dtype=target.dtype) if xy.shape != (2,) or not torch.isfinite(xy).all(): raise ValueError("Expected finite cube center XY") target[:2] = xy return target
class FirstTargetXYZConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) dataset: Path """Annotated training H5 whose adjacent JSON maps seed to episode_id.""" alpha: float = Field(ge=0, le=1, allow_inf_nan=False) """Retained fraction of first predicted XYZ residual relative to expert XYZ."""
class TrainingFirstTargetXYZ: """First-query oracle intervention; never a phase selector or model input."""
def __init__(self, config: FirstTargetXYZConfig): self.config = config metadata_path = config.dataset.with_suffix(".json") metadata_bytes = metadata_path.read_bytes() metadata = json.loads(metadata_bytes) self.episodes = {e["episode_seed"]: e for e in metadata["episodes"]} if len(self.episodes) != len(metadata["episodes"]): raise ValueError("Ambiguous training scene seeds") with config.dataset.open("rb") as stream: dataset_hash = hashlib.file_digest(stream, "sha256").hexdigest() self.source = { "dataset": str(config.dataset.resolve()), "dataset_sha256": dataset_hash, "metadata": str(metadata_path.resolve()), "metadata_sha256": hashlib.sha256(metadata_bytes).hexdigest(), }
def apply(self, predicted, *, query, seed): if query < 1: raise ValueError("Expected a positive query index") target = predicted.clone() # Later decisions must not read labels, change targets, or choose phases. if query != 1: return target, None if target.shape != (10,) or not torch.isfinite(target).all(): raise ValueError("Expected a finite ten-dimensional keypose prediction") if seed not in self.episodes: raise ValueError(f"No saved training demonstration for seed {seed}") episode = self.episodes[seed] group_name = f"traj_{episode['episode_id']}/keyframes" with h5py.File(self.config.dataset, "r") as data: key = data[group_name] if ( key.attrs.get("pose_frame") != "world" or key["name"].asstr()[0] != "approach" or key["kind"].asstr()[0] != "move" or int(key["start_action"][0]) != 0 or int(key["action_keyframe_index"][0]) != 0 ): raise ValueError("Expected the initial world-frame approach target") expert_pose = np.asarray(key["target_pose_world"][0]) if expert_pose.shape != (7,) or not np.isfinite(expert_pose).all(): raise ValueError("Expected a finite saved world pose7") expert_xyz = torch.as_tensor( expert_pose[:3], dtype=target.dtype, device=target.device ) alpha = self.config.alpha if alpha == 0: target[:3] = expert_xyz elif alpha != 1: target[:3] = expert_xyz + alpha * (predicted[:3] - expert_xyz) # alpha=1 deliberately performs no arithmetic on the executed target. return target, { **self.source, "seed": seed, "episode_id": episode["episode_id"], "h5_target_path": f"{group_name}/target_pose_world", "h5_target_index": 0, "primitive": "approach", "alpha": alpha, "expert_xyz": expert_xyz.tolist(), "predicted_xyz": predicted[:3].tolist(), "executed_xyz": target[:3].tolist(), "residual_before_m": (predicted[:3] - expert_xyz).tolist(), "residual_after_m": (target[:3] - expert_xyz).tolist(), "scope": "Privileged first-query XYZ diagnostic, including alpha=1 identity; not learned-policy performance", }
def nearest_cube_intervention(predicted, *, cubes): """Privileged XY on every query, snapped to the cube the model already chose.
Replaces XY precision ONLY. Height, orientation, continuous gripper and the decision of when to advance stay exactly as predicted, so this isolates localization error from phase advancement. The model's own object choice is preserved by selecting the nearest center; the margin is recorded so that ambiguous cases stay visible instead of being silently attributed. """ target = predicted.clone() if not torch.isfinite(target).all(): raise ValueError("Cannot intervene on a nonfinite prediction") if not cubes: raise ValueError("Expected at least one named cube center") names = sorted(cubes) centers = torch.stack( [torch.as_tensor(cubes[name], dtype=target.dtype).reshape(-1) for name in names] ) if centers.shape != (len(names), 2) or not torch.isfinite(centers).all(): raise ValueError("Expected finite cube center XY per cube") distances = (centers - target[:2]).norm(dim=-1) order = distances.argsort() chosen = int(order[0]) target[:2] = centers[chosen] return target, { "intervened_cube": names[chosen], "correction_mm": float(distances[chosen]) * 1000, "runner_up_cube": names[int(order[1])] if len(names) > 1 else None, "selection_margin_mm": float(distances[int(order[1])] - distances[chosen]) * 1000 if len(names) > 1 else None, "cube_centers_m": {name: centers[i].tolist() for i, name in enumerate(names)}, }
class TrainingResetConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) env: Any """Physical environment before observation, recording and metric wrappers.""" dataset: Path """Saved training trajectories; only initial physical states are restored."""
class TrainingSceneReset(gym.Wrapper): def __init__(self, config: TrainingResetConfig): super().__init__(config.env) self.config = config metadata = json.loads(config.dataset.with_suffix(".json").read_text()) self.episodes = {e["episode_seed"]: e for e in metadata["episodes"]} if len(self.episodes) != len(metadata["episodes"]): raise ValueError("Ambiguous training scene seeds")
def reset(self, *, seed=None, options=None): episode = self.episodes[seed] _, _ = self.env.reset(**episode["reset_kwargs"])
def first(group): return { k: first(v) if isinstance(v, h5py.Group) else v[0] for k, v in group.items() }
with h5py.File(self.config.dataset, "r") as data: group = data[f"traj_{episode['episode_id']}"] state = first(group["env_states"]) base = self.unwrapped base.set_state_dict(state) # Joint targets must start at restored joints, not random reset joints. base.agent.controller.reset() obs = base.get_obs() np.testing.assert_allclose( obs["agent"]["qpos"].cpu()[0], group["obs/agent/qpos"][0], atol=1e-6 ) np.testing.assert_allclose( obs["extra"]["tcp_pose"].cpu()[0], group["obs/extra/tcp_pose"][0], atol=1e-6, ) info = base.get_info() info["diagnostic_training_episode_id"] = episode["episode_id"] return obs, info123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191"""Execute recorded expert keyposes, without using their dense action trajectories.
This is an oracle controller diagnostic on demonstration initial states, NOT alearned-policy evaluation. Saved keypose order and targets are privileged labels."""
import hashlibimport jsonimport timefrom pathlib import Path
import gymnasium as gymimport h5pyimport mani_skill.envs # noqa: F401import numpy as npimport torchfrom mani_skill.utils import commonfrom pydantic import BaseModel, ConfigDict, PositiveIntfrom pydantic_settings import CliApp
from lim.keypose_control import KeyposeControlConfig, encode_keypose, keypose_commandfrom lim.replay_pose import tree_first
class OracleConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) dataset: Path """Annotated pose demonstration H5; only initial state and keypose labels read.""" output_dir: Path """New diagnostic directory; all attempts and step records retained.""" episodes: PositiveInt = 10 """First numerically ordered demonstrations, never a selected successful subset.""" max_steps: PositiveInt = 200 """Same finite episode horizon as policy evaluation.""" event_steps: PositiveInt = 6 """Fixed open/close dwell after measured arrival, matching native expert duration.""" control: KeyposeControlConfig = KeyposeControlConfig() """Frozen TCP tracking parameters, also used by the learned policy transport."""
def run(config: OracleConfig): torch.set_num_threads(4) config.output_dir.mkdir(parents=True, exist_ok=False) metadata = json.loads(config.dataset.with_suffix(".json").read_text()) episodes = sorted(metadata["episodes"], key=lambda e: e["episode_id"])[ : config.episodes ] if len(episodes) != config.episodes: raise ValueError("Insufficient annotated episodes") kwargs = metadata["env_info"]["env_kwargs"] | { "max_episode_steps": config.max_steps } env = gym.make(metadata["env_info"]["env_id"], **kwargs) results = [] started = time.time() try: with ( h5py.File(config.dataset, "r") as data, (config.output_dir / "steps.jsonl").open("x") as steps, ): for episode in episodes: group = data[f"traj_{episode['episode_id']}"] env.reset(**episode["reset_kwargs"]) base = env.unwrapped base.set_state_dict(tree_first(group["env_states"])) obs = base.get_obs() arm = base.agent.controller.controllers["arm"] if ( arm.config.frame != "root_translation:root_aligned_body_rotation" or arm.config.use_target or not arm.config.use_delta or not arm.config.normalize_action or not np.isclose(arm.config.rot_lower, -0.1) ): raise ValueError("Unexpected controller semantics") np.testing.assert_allclose( base.agent.robot.pose.q.cpu(), [[1, 0, 0, 0]], atol=1e-6 ) np.testing.assert_allclose( arm.action_space_high[:3].cpu(), [0.1] * 3, atol=1e-7 ) np.testing.assert_allclose( arm.action_space_low[:3].cpu(), [-0.1] * 3, atol=1e-7 ) key = group["keyframes"] targets = encode_keypose( torch.from_numpy(key["target_pose_world"][:]), torch.from_numpy(key["gripper_command"][:]), ) kinds = key["kind"].asstr()[:] current = torch.as_tensor(obs["extra"]["tcp_pose"]) grip = ( (torch.as_tensor(obs["agent"]["qpos"])[..., 7:9].mean(-1) + 0.01) / 0.05 * 2 - 1 ).clamp(-1, 1) index, dwell, once, end = 0, 0, False, False transitions = [] for step in range(config.max_steps): executed_index = min(index, len(targets) - 1) target = targets[executed_index][None] command, reached, pe, re = keypose_command( current, target, grip, config.control ) before = current.clone() obs, _, _terminated, truncated, info = env.step(command) grip = command[:, -1].clone() current = torch.as_tensor(obs["extra"]["tcp_pose"]) end = bool(info["success"].item()) once |= end reached_before = bool(reached.item()) if index < len(targets): # Once started, an event lasts its fixed six steps even # if contact briefly moves the TCP outside tolerance. dwell = dwell + 1 if (reached_before or dwell > 0) else 0 needed = 1 if kinds[index] == "move" else config.event_steps if dwell >= needed: transitions.append( { "keyframe": index, "after_step": step + 1, "position_error_m": pe.item(), "rotation_error_rad": re.item(), } ) index += 1 dwell = 0 steps.write( json.dumps( { "seed": episode["episode_seed"], "step": step + 1, "target_index_executed": executed_index, "target": target[0].tolist(), "tcp_before": before[0].tolist(), "command": command[0].tolist(), "tcp_after": current[0].tolist(), "position_error_m": pe.item(), "rotation_error_rad": re.item(), "success": end, "cubeA_pose": common.to_numpy(base.cubeA.pose.raw_pose)[ 0 ].tolist(), "cubeB_pose": common.to_numpy(base.cubeB.pose.raw_pose)[ 0 ].tolist(), } ) + "\n" ) if bool(truncated.item()): if step + 1 != config.max_steps: raise ValueError("Unexpected truncation") break row = { "seed": episode["episode_seed"], "episode_id": episode["episode_id"], "success_once": once, "success_at_end": end, "steps": step + 1, "completed_keyframes": index, "keyframes": len(targets), "transitions": transitions, } results.append(row) with (config.output_dir / "episodes.jsonl").open("a") as output: output.write(json.dumps(row) + "\n") print("ORACLE_EPISODE", json.dumps(row), flush=True) finally: env.close() result = { "config": config.model_dump(mode="json"), "episodes": len(results), "success_once": sum(r["success_once"] for r in results), "success_at_end": sum(r["success_at_end"] for r in results), "all_keyframes_completed": sum( r["completed_keyframes"] == r["keyframes"] for r in results ), "started_epoch": started, "ended_epoch": time.time(), "scope": "Privileged annotated goals and ordered stages on demonstration initial states; no learned policy, no heldout task score", } with config.dataset.open("rb") as stream: result["dataset_sha256"] = hashlib.file_digest(stream, "sha256").hexdigest() (config.output_dir / "result.json").write_text(json.dumps(result, indent=2) + "\n") print("KEYPOSE_ORACLE_COMPLETE", json.dumps(result), flush=True)
if __name__ == "__main__": run(CliApp.run(OracleConfig))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475"""Auxiliary primitive classification from the same ACT decoder forward.
Training features include the native CVAE posterior; inference uses its zerolatent prior. Classification accuracy on training forwards is therefore not asubstitute for prior-mode phase accuracy. Phase labels never enter either branchas observations, conditioning, or an execution state machine."""
import torchfrom pydantic import BaseModel, ConfigDictfrom torch import nn
KEYPOSE_PHASE_NAMES = ( "approach", "grasp_pose", "close_gripper", "lift", "place_pose", "open_gripper",)
class KeyposePhaseHeadConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) action_head: nn.Linear """Existing native action projection, reused without reinitialization.""" all_queries: bool = False """Classify every future action; false retains the original query-zero head."""
class KeyposePhaseHead(nn.Module): def __init__(self, config: KeyposePhaseHeadConfig): super().__init__() self.config = config self.action = config.action_head device = self.action.weight.device devices = [device.index] if device.type == "cuda" else [] # The extra head must not perturb later model/EMA construction, dropout, # native posterior sampling, or the training sample-order RNG. with torch.random.fork_rng(devices=devices): self.phase = nn.Linear( self.action.in_features, len(KEYPOSE_PHASE_NAMES), device=device, dtype=self.action.weight.dtype, ) self.phase_logits = None
def forward(self, features): if features.ndim != 3 or features.shape[1] < 1: raise ValueError( "Expected ACT decoder features with shape batch, query, hidden" ) actions = self.action(features) self.phase_logits = self.phase( features if self.config.all_queries else features[:, 0] ) return actions
def read_phase_logits(model): """Return six raw class logits from the latest forward, before/after normalization.
Accept the native agent or any registered model wrapper. Does not invoke the network, sample a latent, detach gradients, or change the action output. """ heads = [part for part in model.modules() if isinstance(part, KeyposePhaseHead)] if len(heads) != 1: raise ValueError("Expected exactly one enabled keypose phase head") logits = heads[0].phase_logits if logits is None: raise RuntimeError("Phase logits require a completed policy forward") return logits123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260"""Next-keypose supervision with optional training-only observation selection."""
import hashlibimport jsonfrom pathlib import Pathfrom typing import Any
import h5pyimport numpy as npimport torchfrom pydantic import BaseModel, ConfigDict, NonNegativeFloatfrom torch.utils.data import Dataset
from lim.keypose_context import CONTEXT_DIM, KeyposeContextModefrom lim.keypose_control import encode_keyposefrom lim.keypose_phase import KEYPOSE_PHASE_NAMES
class KeyposeSamplingConfig(BaseModel, frozen=True): model_config = ConfigDict( extra="forbid", use_attribute_docstrings=True, allow_inf_nan=False ) gripper_initial_only: bool = False """Keep only obs[start] of each close/open primitive; retain original labels.""" motion_endpoint_radius_m: NonNegativeFloat = 0 """Exclude all move observations within this XYZ radius of obs[end]; zero disables."""
@property def active(self): return self.gripper_initial_only or self.motion_endpoint_radius_m > 0
class KeyposeDatasetConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) dataset: Any """Native preprocessed RGB dataset; full observations and sample order retained.""" source: Path """Annotated H5 used to construct the native dataset in numeric trajectory order.""" sampling: KeyposeSamplingConfig = KeyposeSamplingConfig() """Training-only subset; full stored trajectories remain the normalization population.""" phase_supervision: bool = False """Return the six-class primitive index separately from observations/actions.""" context: KeyposeContextMode = "none" """Add completed_target11 without changing state/RGB, actions or selected slices.""" stop_supervision: bool = False """Return final-primitive terminal intent separately from observations/actions."""
class KeyposeDataset(Dataset): def __init__(self, config: KeyposeDatasetConfig): self.config = config self.dataset = config.dataset self.trajectories = {**self.dataset.trajectories, "actions": []} self.phase_labels = [] self.stop_labels = [] self.completed_targets = [] if config.stop_supervision and ( config.context != "previous_target" or config.sampling.active or config.phase_supervision ): raise ValueError( "Stop supervision preserves the full previous-target dataset without phase" ) selected = [] records = [] with h5py.File(config.source, "r") as file: names = sorted(file, key=lambda name: int(name.split("_")[-1]))[ : self.dataset.num_traj ] if len(names) != self.dataset.num_traj: raise ValueError( "Keypose and native datasets select different trajectories" ) for name, dense in zip( names, self.dataset.trajectories["actions"], strict=True ): key = file[name]["keyframes"] indices = torch.from_numpy(key["action_keyframe_index"][:]).long() if config.phase_supervision or config.stop_supervision: if ( "name" not in key or tuple(key["name"].asstr()[:]) != KEYPOSE_PHASE_NAMES or indices.ndim != 1 or not ( (indices >= 0) & (indices < len(KEYPOSE_PHASE_NAMES)) ).all() ): raise ValueError( "Phase supervision requires the canonical six primitive labels" ) if config.phase_supervision: self.phase_labels.append(indices) if config.stop_supervision: self.stop_labels.append( (indices == len(key["name"]) - 1).float() ) poses = torch.from_numpy(key["target_pose_world"][:]) gripper = torch.from_numpy(key["gripper_command"][:]) if len(indices) != len(dense) or dense.shape[-1] != 7: raise ValueError("Expected aligned unencoded dense pose actions") if not torch.equal(gripper[indices], dense[:, -1]): raise ValueError("Keypose event and dense gripper labels disagree") targets = encode_keypose(poses, gripper) self.trajectories["actions"].append(targets[indices]) if config.context != "none": starts = key["start_action"][:] ends = key["end_action"][:] if ( indices.ndim != 1 or len(starts) != len(targets) or len(ends) != len(targets) or not len(starts) or starts[0] != 0 or ends[-1] != len(dense) or np.any(ends <= starts) or not np.array_equal(starts[1:], ends[:-1]) or not np.array_equal( indices.numpy(), np.searchsorted(ends, np.arange(len(dense)), side="right"), ) ): raise ValueError( "Completed-goal context requires contiguous pre-action primitive indices" ) context = targets.new_zeros((len(indices), CONTEXT_DIM)) if config.context == "previous_target": valid = indices > 0 context[valid, :10] = targets[indices[valid] - 1] context[valid, -1] = 1 self.completed_targets.append(context) keep = np.ones(len(dense), dtype=bool) protected_starts = [] if config.sampling.active: starts, ends = key["start_action"][:], key["end_action"][:] kinds = key["kind"].asstr()[:] if ( not len(starts) or len(starts) != len(ends) or len(kinds) != len(starts) or starts[0] != 0 or ends[-1] != len(dense) or np.any(ends <= starts) or not np.array_equal(starts[1:], ends[:-1]) or not np.array_equal( indices.numpy(), np.searchsorted(ends, np.arange(len(dense)), side="right"), ) ): raise ValueError("Invalid primitive boundaries for sampling") tcp = file[name]["obs/extra/tcp_pose"][:].astype(np.float64) if len(tcp) != len(dense) + 1 or not np.isfinite(tcp).all(): raise ValueError( "Expected finite pre-action and terminal TCP observations" ) for start, end, kind in zip(starts, ends, kinds, strict=True): if kind in ("close", "open"): if config.sampling.gripper_initial_only: keep[start + 1 : end] = False elif kind == "move": if config.sampling.motion_endpoint_radius_m > 0: near = ( np.linalg.norm( tcp[start:end, :3] - tcp[end, :3], axis=1 ) <= config.sampling.motion_endpoint_radius_m ) keep[start:end] &= ~near else: raise ValueError(f"Unknown primitive kind: {kind}") protected_starts = starts[~keep[starts]].tolist() keep[starts] = True selected.append(keep) records.append( { "trajectory": name, "original_samples": len(dense), "retained_indices": np.flatnonzero(keep).tolist(), "protected_segment_starts": protected_starts, } ) self.slices = [ (trajectory, step) for trajectory, step in self.dataset.slices if selected[trajectory][step] ] expected = sum(int(mask.sum()) for mask in selected) if len(self.slices) != expected or len(set(self.slices)) != expected: raise ValueError( "Native sample index does not cover each obs_t exactly once" ) encoded_indices = json.dumps(self.slices, separators=(",", ":")).encode() self.sample_selection = { "config": config.sampling.model_dump(mode="json"), "original_samples": sum(len(mask) for mask in selected), "retained_samples": len(self.slices), "normalization_population": "all original unfiltered obs_t and keypose targets", "index_sha256": hashlib.sha256(encoded_indices).hexdigest(), "trajectories": records, } if config.stop_supervision: labels = torch.cat(self.stop_labels) self.stop_label_summary = { "contract": "stop_after_target = original action_keyframe_index equals final primitive index; label only, no terminal observation or success input", "samples": len(labels), "positive": int(labels.sum()), "negative": int((labels == 0).sum()), "labels_sha256": hashlib.sha256(labels.numpy().tobytes()).hexdigest(), "sample_index_sha256": self.sample_selection["index_sha256"], }
def __getattr__(self, name): return getattr(self.dataset, name)
def __len__(self): return len(self.slices)
def __getitem__(self, index): trajectory, step = self.slices[index] observation = { k: v[step] for k, v in self.trajectories["observations"][trajectory].items() } if self.config.context != "none": observation["completed_target"] = self.completed_targets[trajectory][ step ].clone() target = self.trajectories["actions"][trajectory][step] # Preserve the native query embeddings/parameter count and loss averaging. # All queries predict the SAME next primitive target, not future timed deltas. # No terminal padding or future-frame observation is needed for this target. sample = { "observations": observation, "actions": target[None].repeat(self.num_queries, 1), } if self.config.phase_supervision: sample["phase"] = self.phase_labels[trajectory][step] if self.config.stop_supervision: sample["stop_after_target"] = self.stop_labels[trajectory][step] return sample
class FirstKeyposeAgentConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) agent: Any """Frozen ACT whose queries all supervise the next world-frame keypose."""
class FirstKeyposeAgent: def __init__(self, config: FirstKeyposeAgentConfig): self.config = config
def __getattr__(self, name): return getattr(self.config.agent, name)
def get_action(self, obs): return self.config.agent.get_action(obs)[:, :1]12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""Future-timestep keypose supervision from the existing annotated trajectories.
Query i receives the primitive target attached to demonstration time t + i,rather than another copy of time t's primitive target. Observations and optionalphase supervision still describe only time t. Wrap KeyposeDataset before actionnormalization so its original per-timestep population continues to define stats."""
import torchfrom pydantic import BaseModel, ConfigDictfrom torch.utils.data import Dataset
from lim.keypose_policy import KeyposeDataset
class KeyposeSequenceDatasetConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) dataset: KeyposeDataset """Unnormalized keypose dataset owning observations, slices, and full targets."""
class KeyposeSequenceDataset(Dataset): def __init__(self, config: KeyposeSequenceDatasetConfig): self.config = config self.dataset = config.dataset
def __getattr__(self, name): return getattr(self.dataset, name)
def __len__(self): return len(self.dataset)
def __getitem__(self, index): sample = self.dataset[index] trajectory, step = self.dataset.slices[index] targets = self.dataset.trajectories["actions"][trajectory] times = torch.arange( step, step + self.dataset.num_queries, device=targets.device ).clamp_max(len(targets) - 1) # Padding holds the final world keypose and its gripper command. It is # deliberately not the zero-increment stop padding used by dense actions. # Use original physical timesteps, including filtered-out observations; # the selected slice list controls obs_t sampling, not future label time. return {**sample, "actions": targets.index_select(0, times)}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677"""Terminal intent from query-zero features, without changing action10 semantics.
Labels supervise whether to hold after this request completes. They are nevermodel observations or a success signal. Training uses posterior features;inference logits must be read from the latest native zero-latent prior forward."""
import hashlib
import torchfrom pydantic import BaseModel, ConfigDictfrom torch import nn
class KeyposeStopHeadConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) action_head: nn.Linear """Original native action10 projection, reused without reinitialization."""
class KeyposeStopHead(nn.Module): def __init__(self, config: KeyposeStopHeadConfig): super().__init__() self.config = config self.action = config.action_head if self.action.out_features != 10: raise ValueError("Stop intent requires the original keypose10 projection") device = self.action.weight.device devices = [device.index] if device.type == "cuda" else [] # Preserve subsequent context/EMA initialization and sampling/dropout RNG. with torch.random.fork_rng(devices=devices): self.stop = nn.Linear( self.action.in_features, 1, device=device, dtype=self.action.weight.dtype, ) self.stop_logits = None
def forward(self, features): if features.ndim != 3 or features.shape[1] < 1: raise ValueError("Expected ACT decoder features batch x query x hidden") actions = self.action(features) self.stop_logits = self.stop(features[:, 0]).squeeze(-1) return actions
def read_stop_logits(model): """Return batch logits from the latest forward without detaching or rerunning it.""" heads = [part for part in model.modules() if isinstance(part, KeyposeStopHead)] if len(heads) != 1: raise ValueError("Expected exactly one enabled keypose stop head") logits = heads[0].stop_logits if logits is None: raise RuntimeError("Stop logits require a completed policy forward") return logits
def original_state_sha256(model): """Hash original parameters/buffers in native order, excluding only the new head.
The complete state_dict hash intentionally changes when the head is present. Reversing the action wrapper's key prefix permits comparison with precision. """ digest = hashlib.sha256() for name, tensor in model.state_dict().items(): if ".action_head.dense." in name: continue name = name.replace(".action_head.primary.", ".action_head.") if ".action_head.stop." in name: continue original = name.replace(".action_head.action.", ".action_head.") digest.update(original.encode()) digest.update(tensor.detach().cpu().contiguous().numpy().tobytes()) return digest.hexdigest()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071"""Read-only diagnostics around the existing keypose execution boundary."""
import jsonfrom pathlib import Path
import numpy as npimport torchfrom pydantic import BaseModel, ConfigDict
from lim.keypose_control import KeyposeEnv, keypose_command
class KeyposeTraceConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) env: KeyposeEnv """Unmodified observed-state keypose executor.""" path: Path """New JSONL file of pre-action diagnostics, one row per scene and step.""" seed_start: int """First seed in the recorder's consecutive synchronous episode batches."""
class KeyposeTraceEnv: def __init__(self, config: KeyposeTraceConfig): self.config = config self.stream = config.path.open("x") self.batch = 0 self.step_index = 0
def __getattr__(self, name): return getattr(self.config.env, name)
def step(self, target): env = self.config.env target_tensor = torch.as_tensor(target) command, reached, position_error, rotation_error = keypose_command( env.current, target_tensor, env.gripper, env.config.control ) values = { "target": target_tensor, "tcp_before": env.current, "previous_gripper": env.gripper, "recomputed_command": command, "reached": reached, "position_error_m": position_error, "rotation_error_rad": rotation_error, } values = {k: v.detach().cpu().tolist() for k, v in values.items()} result = env.step(target) done = np.asarray(result[2]) | np.asarray(result[3]) if done.any() and not done.all(): raise ValueError("Keypose trace requires synchronous episode batches") for slot in range(env.num_envs): row = {key: value[slot] for key, value in values.items()} row.update( seed=self.config.seed_start + self.batch * env.num_envs + slot, step=self.step_index, done=bool(done[slot]), ) self.stream.write(json.dumps(row, allow_nan=False) + "\n") self.step_index += 1 if done.all(): self.batch += 1 self.step_index = 0 self.stream.flush() return result
def finish(self): self.stream.close()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263"""Training-fitted affine transforms, independent of native delta-control stats."""
import hashlibfrom pathlib import Pathfrom typing import Any, Literal
import torchfrom pydantic import ( BaseModel, ConfigDict, Field, PositiveFloat, PositiveInt, model_validator,)from torch import nnfrom torch.utils.data import Dataset
from lim.action_encoding import ActionEncoding
class NormalizationConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) method: Literal["none", "state_zscore", "action_zscore", "action_quantile"] = "none" """One independent transform; RGB and gripper retain their native treatment.""" state_floor: tuple[PositiveFloat, ...] = ( (0.01,) * 7 + (0.001,) * 2 + (0.01,) * 7 + (0.001,) * 2 + (0.001,) * 3 + (0.01,) * 4 ) """State25 scale floors: joint rad/rad/s .01, finger m/m/s .001, TCP m .001, quaternion .01.""" action_floor: PositiveFloat = 0.01 """Minimum std or quantile half-span in ENCODED action coordinates, not physical units."""
@model_validator(mode="after") def check_layout(self): if len(self.state_floor) != 25: raise ValueError( "State floors must follow qpos9, qvel9, TCP position3/quaternion4" ) return self
class AffineConfig(BaseModel, frozen=True): model_config = ConfigDict( extra="forbid", allow_inf_nan=False, use_attribute_docstrings=True ) center: tuple[float, ...] """Training mean or q01/q99 midpoint, with gripper center fixed to zero.""" scale: tuple[PositiveFloat, ...] """Floored std or half-span, with gripper scale fixed to one."""
@model_validator(mode="after") def check_lengths(self): if not self.center or len(self.center) != len(self.scale): raise ValueError( "Affine center and scale must have matching nonempty shapes" ) return self
class FittedNormalizationConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) config: NormalizationConfig """Exact fitting recipe; compared against the declared policy on reload.""" action_encoding: ActionEncoding """Coordinates in which action statistics were fitted.""" source_sha256: str = Field(pattern=r"^[0-9a-f]{64}$") """Training HDF5 identity, never evaluation data.""" trajectories: PositiveInt """Number of loaded training trajectories used to fit statistics.""" samples: PositiveInt """Number of unpadded encoded targets fitted; default is one per original obs_t.""" state: AffineConfig """State25 transform; identity for action-only candidates.""" action: AffineConfig """Encoded action transform; identity for the state-only candidate."""
@model_validator(mode="after") def check_contract(self): dim = len(self.action.center) if len(self.state.center) != 25 or dim not in ( (10,) if self.action_encoding == "rotation6d" else (4, 7) ): raise ValueError( "Fitted statistics differ from the supported state/action layout" ) if self.config.method == "none": raise ValueError("The unnormalized control must not have fitted statistics") if self.action.center[-1] != 0 or self.action.scale[-1] != 1: raise ValueError("Gripper must remain unchanged") identity = self.action if self.config.method == "state_zscore" else self.state if any(identity.center) or any(s != 1 for s in identity.scale): raise ValueError( "An independent candidate must leave the other modality unchanged" ) return self
class FitNormalizationConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) dataset: Any """Native delta dataset after action encoding, before chunk/padding normalization.""" normalization: NormalizationConfig """Single-factor fitting recipe.""" action_encoding: ActionEncoding """Coordinates of the dataset actions.""" source: Path """Training HDF5 used by this dataset.""" action_samples: Any | None = None """Explicit encoded population for sample-dependent labels; excludes padding."""
def fit_normalization(config: FitNormalizationConfig): if config.normalization.method == "none": return None dataset = config.dataset if not dataset.delta_control or dataset.norm_stats is not None: raise ValueError( "Normalization requires raw native delta-control observations/actions" ) actions, states = [], [] for action, obs in zip( dataset.trajectories["actions"], dataset.trajectories["observations"], strict=True, ): state = obs["state"] if not len(action) or len(state) != len(action) + 1: raise ValueError("Expected one terminal observation per trajectory") actions.append(action.double()) states.append(state[: len(action)].double()) action = torch.cat(actions) if config.action_samples is not None: action = torch.as_tensor(config.action_samples).double() if action.ndim != 2 or not len(action): raise ValueError("Expected nonempty encoded action population") state = torch.cat(states) if not torch.isfinite(action).all() or not torch.isfinite(state).all(): raise ValueError("Nonfinite training data") state_center, state_scale = ( torch.zeros(state.shape[-1]), torch.ones(state.shape[-1]), ) action_center, action_scale = ( torch.zeros(action.shape[-1]), torch.ones(action.shape[-1]), ) method = config.normalization.method if method == "state_zscore": state_center = state.mean(0) state_scale = torch.maximum( state.std(0, correction=0), state.new_tensor(config.normalization.state_floor), ) elif method == "action_zscore": action_center = action.mean(0) action_scale = action.std(0, correction=0).clamp_min( config.normalization.action_floor ) else: low, high = torch.quantile(action, action.new_tensor([0.01, 0.99]), dim=0) action_center = (low + high) / 2 action_scale = ((high - low) / 2).clamp_min(config.normalization.action_floor) action_center[-1], action_scale[-1] = 0, 1 with config.source.open("rb") as stream: source_sha256 = hashlib.file_digest(stream, "sha256").hexdigest() return FittedNormalizationConfig( config=config.normalization, action_encoding=config.action_encoding, source_sha256=source_sha256, trajectories=len(actions), samples=len(action), state=AffineConfig(center=state_center.tolist(), scale=state_scale.tolist()), action=AffineConfig(center=action_center.tolist(), scale=action_scale.tolist()), )
class NormalizedDatasetConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) dataset: Any """Encoded native dataset, still owning physical stop padding.""" statistics: FittedNormalizationConfig """Training-only fitted affine parameters."""
class NormalizedDataset(Dataset): def __init__(self, config: NormalizedDatasetConfig): self.config = config self.dataset = config.dataset self.center = torch.tensor(config.statistics.action.center) self.scale = torch.tensor(config.statistics.action.scale)
def __getattr__(self, name): return getattr(self.dataset, name)
def __len__(self): return len(self.dataset)
def __getitem__(self, index): sample = self.dataset[index] # Native dataset has already padded zero motion and held the last gripper. return {**sample, "actions": (sample["actions"] - self.center) / self.scale}
class NormalizedModelConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) model: Any """Native CVAE; receives normalized labels and the same normalized state in both branches.""" statistics: FittedNormalizationConfig """Checkpoint-owned transforms; these do not consume random initialization draws."""
class NormalizedModel(nn.Module): def __init__(self, config: NormalizedModelConfig): super().__init__() self.config = config self.base = config.model # Saved once as checkpoint metadata, not averaged as EMA parameters/buffers. for name, values in ( ("state_center", config.statistics.state.center), ("state_scale", config.statistics.state.scale), ("action_center", config.statistics.action.center), ("action_scale", config.statistics.action.scale), ): self.register_buffer(name, torch.tensor(values), persistent=False)
def forward(self, obs, actions=None): obs = {**obs, "state": (obs["state"] - self.state_center) / self.state_scale} prediction, latent = self.base(obs, actions) if actions is None: # Invert BEFORE native time ensembling and Rotation6DEnv projection. # No clipping, including predictions outside q01/q99. prediction = prediction * self.action_scale + self.action_center return prediction, latent
def checked_statistics(raw, normalization, encoding): if normalization.method == "none": if raw is not None: raise ValueError( "Unnormalized control unexpectedly contains fitted statistics" ) return None if raw is None: raise ValueError( "Normalized policy requires its training-fitted checkpoint statistics" ) fitted = FittedNormalizationConfig.model_validate(raw) if fitted.config != normalization or fitted.action_encoding != encoding: raise ValueError( "Fitted statistics differ from the policy normalization contract" ) return fitted1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889"""Measured observations shared by all policy variants; no simulator labels."""
import numpy as npfrom pydantic import BaseModel, ConfigDict, PositiveInt
class ObservationConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) points: PositiveInt = 256 """Total points, split equally between visible role colors and context."""
def as_numpy(value): if hasattr(value, "detach"): return value.detach().cpu().numpy() return np.asarray(value)
def sample_points(points: np.ndarray, count: int) -> np.ndarray: if len(points) == 0: return np.zeros((count, 6), dtype=np.float32) # Deterministic sampling; independent of labels, episode seed, and test set. indices = np.linspace(0, len(points) - 1, count).astype(np.int64) return points[indices].astype(np.float32)
def cloud_from_rgbd(obs: dict) -> tuple[np.ndarray, np.ndarray]: """Unproject millimeter optical depth using calibrated CV cameras.""" coordinates, colors = [], [] for name, view in obs["sensor_data"].items(): depth = as_numpy(view["depth"]).squeeze().astype(np.float32) / 1000 rgb = as_numpy(view["rgb"]).reshape(-1, 3) height, width = depth.shape v, u = np.mgrid[:height, :width] pixels = np.stack([u + 0.5, v + 0.5, np.ones_like(u)], axis=-1).reshape(-1, 3) params = obs["sensor_param"][name] intrinsic = as_numpy(params["intrinsic_cv"]).reshape(3, 3) extrinsic = as_numpy(params["extrinsic_cv"]).reshape(3, 4) camera_xyz = (pixels @ np.linalg.inv(intrinsic).T) * depth.reshape(-1, 1) world_xyz = (camera_xyz - extrinsic[:, 3]) @ extrinsic[:, :3] coordinates.append(np.c_[world_xyz, depth.reshape(-1) > 0].astype(np.float32)) colors.append(rgb) return np.concatenate(coordinates), np.concatenate(colors)
def encode_observation(obs: dict, config: ObservationConfig) -> dict[str, np.ndarray]: """Only camera point XYZ/RGB, joint positions/velocities and measured TCP pose.""" if obs.get("sensor_data") and "depth" in next(iter(obs["sensor_data"].values())): xyzw, raw_rgb = cloud_from_rgbd(obs) else: xyzw = as_numpy(obs["pointcloud"]["xyzw"]).reshape(-1, 4) raw_rgb = as_numpy(obs["pointcloud"]["rgb"]).reshape(-1, 3) rgb = raw_rgb.astype(np.float32) / 255 tcp = as_numpy(obs["extra"]["tcp_pose"]).reshape(-1, 7)[0] qpos = as_numpy(obs["agent"]["qpos"]).reshape(-1, 9)[0] qvel = as_numpy(obs["agent"]["qvel"]).reshape(-1, 9)[0] valid = (xyzw[:, 3] > 0) & np.isfinite(xyzw).all(axis=1) xyz = xyzw[:, :3] valid &= (xyz[:, 2] > 0.005) & (xyz[:, 2] < 0.6) valid &= (abs(xyz[:, 0]) < 0.5) & (abs(xyz[:, 1]) < 0.5) xyz, rgb = xyz[valid], rgb[valid] source = ( (rgb[:, 0] > 0.25) & (rgb[:, 0] > 1.8 * rgb[:, 1]) & (rgb[:, 0] > 1.8 * rgb[:, 2]) ) target = ( (rgb[:, 1] > 0.25) & (rgb[:, 1] > 1.8 * rgb[:, 0]) & (rgb[:, 1] > 1.8 * rgb[:, 2]) ) target_center = xyz[target].mean(axis=0) if target.any() else np.zeros(3) points = np.concatenate([(xyz - tcp[:3]) / 0.3, rgb], axis=1) role_count = config.points // 4 selected = np.concatenate( [ sample_points(points[source], role_count), sample_points(points[target], role_count), sample_points(points, config.points - 2 * role_count), ] ) state = np.concatenate([qpos, qvel, tcp, target_center, [float(target.any())]]) return { "points": selected, "state": state.astype(np.float32), "tcp": tcp.astype(np.float32), "target": np.asarray(target_center, dtype=np.float32), "counts": np.array([len(xyzw), len(xyz), int(source.sum()), int(target.sum())]), }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394"""Out-of-distribution StackCube variants for evaluation only.
`StackCubeOOD-v1` is StackCube-v1 with two optional changes:- `ood_position`: both cubes start in a ring outside the training placement box (x in [-0.2, 0.2], y in [-0.3, 0.3]) but inside x in [-0.25, 0.25], y in [-0.35, 0.35] and within `reach_m` of the robot base; draws come from the episode seed, independent of the native sampler.- `cube_scale`: both cube edge lengths scaled; spacing and the success tolerance follow the scaled size exactly as the native task defines them.Everything else (robot, cameras, rotations, success rule) is unchanged."""
import numpy as npimport sapienimport torchfrom mani_skill.envs.tasks.tabletop.stack_cube import StackCubeEnvfrom mani_skill.envs.utils import randomizationfrom mani_skill.utils import commonfrom mani_skill.utils.building import actorsfrom mani_skill.utils.registration import register_envfrom mani_skill.utils.scene_builder.table import TableSceneBuilderfrom mani_skill.utils.structs.pose import Pose
INNER = ((-0.2, 0.2), (-0.3, 0.3))OUTER = ((-0.25, 0.25), (-0.35, 0.35))BASE_XY = np.array([-0.615, 0.0])
def ring_positions(seed, spacing, reach_m=0.8): """Two cube xy positions in the OOD ring, at least `spacing` apart.""" rng = np.random.default_rng([20261005, seed]) chosen = [] while len(chosen) < 2: xy = np.array([rng.uniform(*OUTER[0]), rng.uniform(*OUTER[1])]) inside = INNER[0][0] <= xy[0] <= INNER[0][1] and INNER[1][0] <= xy[1] <= INNER[1][1] if inside or np.linalg.norm(xy - BASE_XY) > reach_m: continue if chosen and np.linalg.norm(xy - chosen[0]) <= spacing: continue chosen.append(xy) return np.stack(chosen)
@register_env("StackCubeOOD-v1", max_episode_steps=50)class StackCubeOODEnv(StackCubeEnv): def __init__(self, *args, ood_position=False, cube_scale=1.0, **kwargs): self.ood_position = ood_position self.cube_scale = float(cube_scale) self.ood_seed = None super().__init__(*args, **kwargs)
def reset(self, seed=None, options=None): self.ood_seed = seed return super().reset(seed=seed, options=options)
def _load_scene(self, options: dict): half = 0.02 * self.cube_scale self.cube_half_size = common.to_tensor([half] * 3, device=self.device) self.table_scene = TableSceneBuilder( env=self, robot_init_qpos_noise=self.robot_init_qpos_noise ) self.table_scene.build() self.cubeA = actors.build_cube(self.scene, half_size=half, color=[1, 0, 0, 1], name="cubeA", initial_pose=sapien.Pose(p=[0, 0, 0.1])) self.cubeB = actors.build_cube(self.scene, half_size=half, color=[0, 1, 0, 1], name="cubeB", initial_pose=sapien.Pose(p=[1, 0, 0.1]))
def _initialize_episode(self, env_idx: torch.Tensor, options: dict): with torch.device(self.device): b = len(env_idx) self.table_scene.initialize(env_idx) half = 0.02 * self.cube_scale radius = torch.linalg.norm(torch.tensor([half, half])) + 0.001 xyz = torch.zeros((b, 3)) xyz[:, 2] = half # Construction resets once without a seed; every evaluated episode # passes its scene seed, which then fixes the OOD placement. if self.ood_position and self.ood_seed is not None: if b != 1: raise ValueError("OOD placement draws one scene per episode seed") placed = torch.as_tensor(ring_positions(self.ood_seed, 2 * float(radius)), dtype=torch.float32) cubeA_xy, cubeB_xy = placed[:1], placed[1:] else: xy = torch.rand((b, 2)) * 0.2 - 0.1 sampler = randomization.UniformPlacementSampler( bounds=[[-0.1, -0.2], [0.1, 0.2]], batch_size=b, device=self.device ) cubeA_xy = xy + sampler.sample(radius, 100) cubeB_xy = xy + sampler.sample(radius, 100, verbose=False) for actor, cube_xy in ((self.cubeA, cubeA_xy), (self.cubeB, cubeB_xy)): xyz[:, :2] = cube_xy qs = randomization.random_quaternions(b, lock_x=True, lock_y=True, lock_z=False) actor.set_pose(Pose.create_from_pq(p=xyz.clone(), q=qs))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370"""Latch a predicted world pose through its path and measured gripper completion."""
from collections import dequefrom typing import Any
import numpy as npimport torchfrom pydantic import ( BaseModel, ConfigDict, NonNegativeInt, PositiveFloat, model_validator,)
from lim.gripper_feedback import ( GripperCompletion, GripperCompletionConfig, GripperMeasurement,)from lim.keypose_control import KeyposeControlConfig, keypose_error
class PlannerConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) env: Any """Single physical Panda environment; only robot state is used by planning.""" joint_velocity_scale: PositiveFloat = 0.9 """Multiplier on MPLib's robot joint velocity limits, matching the expert.""" joint_acceleration_scale: PositiveFloat = 0.9 """Multiplier on joint acceleration limits, matching the expert."""
class MplibKeyposePlanner: def __init__(self, config: PlannerConfig): from mani_skill.examples.motionplanning.panda.motionplanner import ( PandaArmMotionPlanningSolver, )
self.config = config self.last_status = "not_planned" self.solver = PandaArmMotionPlanningSolver( config.env, debug=False, vis=False, base_pose=config.env.unwrapped.agent.robot.pose, visualize_target_grasp_pose=False, print_env_info=False, joint_vel_limits=config.joint_velocity_scale, joint_acc_limits=config.joint_acceleration_scale, )
def plan(self, target): import sapien from mani_skill.utils.geometry.rotation_conversions import matrix_to_quaternion
from lim.action_encoding import sixd_to_matrix
target = torch.as_tensor(target, dtype=torch.float32) if target.shape != (10,) or not torch.isfinite(target).all(): raise ValueError("Expected a finite world keypose10") quaternion = matrix_to_quaternion(sixd_to_matrix(target[3:9])).numpy() pose = sapien.Pose(target[:3].numpy(), quaternion) # Same screw planner and native retry as collection. No object geometry, # expert phase, grasp labels, extra obstacles or fallback goals supplied. result = self.solver.move_to_pose_with_screw(pose, dry_run=True) if isinstance(result, int): self.last_status = "native_planning_failed" return None position = np.asarray(result["position"], dtype=np.float32) if position.ndim == 2 and position.shape == (0, 7): # Native TOPP can sample zero points when duration < one control # interval. There is no trajectory to execute; record a failed plan. self.last_status = "native_empty_trajectory" return None if ( position.ndim != 2 or position.shape[1] != 7 or len(position) == 0 or not np.isfinite(position).all() ): raise ValueError("Invalid planned joint trajectory") self.last_status = "Success" return result
class PlannedExecutorConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) control: KeyposeControlConfig = KeyposeControlConfig() """Original pose tolerances for diagnostics only; they do not block completion.""" gripper_completion: GripperCompletionConfig = GripperCompletionConfig() """Measured finger target/contact stability required before querying again.""" initial_gripper: float = 1.0 """Measured initial finger position mapped to the continuous command range.""" resume_after_incomplete: bool = False """Return to prediction after a gripper timeout or arrest instead of ending the episode. The original contract has no path back from gripper_timeout, so a single unmet gripper command freezes the remaining budget with zero further queries. Default false preserves every previously scored run.""" carry_gripper_feedback: bool = False """Reuse fresh stable feedback from the motion only when the next gripper command is exactly the same executed float32 command after clipping. A changed command retains the original post-path feedback protocol.""" motion_replan_steps: NonNegativeInt = 0 """Actual motion steps between fresh target/plan attempts; zero keeps full paths."""
@model_validator(mode="after") def check_motion_replan(self): if self.motion_replan_steps and ( self.resume_after_incomplete or self.carry_gripper_feedback ): raise ValueError("Motion replanning requires isolated completion semantics") return self
class PlannedKeyposeExecutor: def __init__(self, config: PlannedExecutorConfig): self.config = config self.gripper = float(config.initial_gripper) self.phase = "ready" self.target = None self.path = None self.index = 0 self.completion = None # Cumulative, because resuming clears the phase that used to record it. self.gripper_timeouts = 0 self.gripper_arrests = 0 self.gripper_feedback_carried = 0 self.motion_feedback = deque(maxlen=config.gripper_completion.stable_steps) self.motion_observed_steps = 0 self.motion_command = None self.completed_target = None self.completed_target_query = None self.completed_goals = 0 self.active_query = None self.goal_id = 0 self.path_revision = 0 self.accepted_paths = 0 self.replan_attempts = 0 self.replan_failures = 0 self.goal_replan_attempts = 0 self.motion_steps_since_attempt = 0 self.goal_motion_steps = 0 self.total_motion_steps = 0 self._motion_step_pending = False
@property def needs_prediction(self): return self.phase == "ready"
@property def needs_motion_replan(self): return bool( self.config.motion_replan_steps and self.phase == "trajectory" and self.index < len(self.path) and not self._motion_step_pending and self.motion_steps_since_attempt >= self.config.motion_replan_steps )
@staticmethod def _checked_target(target): target = torch.as_tensor(target, dtype=torch.float32).clone() if target.shape != (10,) or not torch.isfinite(target).all(): raise ValueError("Expected a finite world keypose10") return target
@staticmethod def _checked_path(path): path = np.asarray(path, dtype=np.float32).copy() if ( path.ndim != 2 or path.shape[1] != 7 or not len(path) or not np.isfinite(path).all() ): raise ValueError("Expected a nonempty finite N x 7 planned trajectory") return path
def begin(self, target, path, current_qpos, *, source_query=None): if not self.needs_prediction: raise RuntimeError("Cannot replace an unfinished keypose trajectory") self.target = self._checked_target(target) self.active_query = source_query self.goal_id += 1 self.path_revision = 0 self.goal_replan_attempts = 0 self.motion_steps_since_attempt = 0 self.goal_motion_steps = 0 self._motion_step_pending = False self.index = 0 self.completion = None self.motion_feedback.clear() self.motion_observed_steps = 0 self.motion_command = None if path is None: self.path = np.asarray(current_qpos, dtype=np.float32)[None, :7].copy() self.phase = "planning_failed" else: self.path = self._checked_path(path) self.accepted_paths += 1 self.phase = "trajectory"
def replace_motion_plan(self, target, path, *, source_query): """Resolve one due dry-run attempt without completing the active goal.
None means planner failure: preserve target/path/index/gripper and only reset the retry interval. Invalid numeric output raises before mutation. """ if not self.needs_motion_replan: raise RuntimeError("Motion replanning requires a due unfinished trajectory") candidate = self._checked_target(target) candidate_path = None if path is None else self._checked_path(path) self.replan_attempts += 1 self.goal_replan_attempts += 1 self.motion_steps_since_attempt = 0 if candidate_path is None: self.replan_failures += 1 return False self.target, self.path = candidate, candidate_path self.active_query = source_query self.index = 0 self.path_revision += 1 self.accepted_paths += 1 return True
def observe_motion_step(self): """Acknowledge env.step, never an inference call or merely built command.""" if not self.config.motion_replan_steps or not self._motion_step_pending: raise RuntimeError( "Motion accounting requires one executed pending command" ) self._motion_step_pending = False self.motion_steps_since_attempt += 1 self.goal_motion_steps += 1 self.total_motion_steps += 1
def _publish_completed_target(self): self.completed_target = self.target.clone() self.completed_target_query = self.active_query self.completed_goals += 1
def command(self, current_tcp): if self.needs_prediction: raise RuntimeError("Predict before requesting the next command") if self.config.motion_replan_steps and self._motion_step_pending: raise RuntimeError( "Acknowledge the physical motion step before a new command" ) delta, rotation = keypose_error(torch.as_tensor(current_tcp), self.target) position_error, rotation_error = float(delta.norm()), float(rotation.norm()) reached = ( position_error <= self.config.control.position_tolerance_m and rotation_error <= self.config.control.rotation_tolerance_rad ) if self.phase == "path_complete": self.phase = "gripper" self.gripper = float(self.target[-1].clamp(-1, 1)) self.completion = GripperCompletion(self.config.gripper_completion) phase = self.phase index = self.index if phase == "trajectory" else len(self.path) - 1 command = np.r_[self.path[index], self.gripper].astype(np.float32) if phase == "trajectory": self._motion_step_pending = bool(self.config.motion_replan_steps) self.motion_command = float(command[-1]) self.index += 1 if self.index == len(self.path): self.phase = "path_complete" return command, { "phase": phase, "path_index": index, "path_length": len(self.path), "reached": reached, "position_error_m": position_error, "rotation_error_rad": rotation_error, }
def begin_gripper(self, target, current_qpos, *, source_query=None): """Execute a predicted gripper event while holding the measured arm.
No trajectory step or pose correction precedes the command. Feedback and timeout semantics are exactly the same as the ordinary post-path phase. """ self.begin( target, np.asarray(current_qpos)[None, :7], current_qpos, source_query=source_query, ) self.phase = "gripper" self.gripper = float(self.target[-1].clamp(-1, 1)) self.completion = GripperCompletion(self.config.gripper_completion)
def observe_motion_gripper(self, measured: GripperMeasurement): """Observe one executed path step, without ever interrupting its trajectory.
Replay the most recent stability window through the existing predicate. A fresh monitor makes a previously complete window revocable when contact is lost; it never calls update() on an already ended completion monitor. Motion timeout/arrest cannot prematurely stop the remaining arm path. """ if not self.config.carry_gripper_feedback: raise RuntimeError("Motion feedback carry is not enabled") if self.phase not in ("trajectory", "path_complete") or ( self.motion_observed_steps != self.index - 1 ): raise RuntimeError("Motion feedback requires one newly executed path step") self.motion_observed_steps += 1 if self.motion_feedback and ( self.motion_feedback[-1].targets_m != measured.targets_m ): self.motion_feedback.clear() self.motion_feedback.append(measured) completion_config = self.config.gripper_completion monitor = GripperCompletion( completion_config.model_copy( update={ "timeout_steps": max( completion_config.timeout_steps, completion_config.stable_steps ), "detect_arrest": False, } ) ) for sample in self.motion_feedback: row = monitor.update(sample) # Compare the actual actuator command values, not gripper sign, measured # finger opening, or a tolerance that could erase a real command change. requested = float(np.float32(float(self.target[-1].clamp(-1, 1)))) unchanged = requested == self.motion_command carried = ( self.phase == "path_complete" and unchanged and row["status"] == "complete" ) if carried: self._publish_completed_target() self.phase = "ready" self.gripper_feedback_carried += 1 return { **row, "window_samples": len(self.motion_feedback), "motion_steps_observed": self.motion_observed_steps, "motion_gripper_command": self.motion_command, "target_gripper_command": requested, "same_gripper_command": unchanged, "carried_to_path_completion": carried, }
def observe_gripper(self, measured: GripperMeasurement): """Consume feedback ONLY after a physical gripper command has executed.""" if self.phase != "gripper": raise RuntimeError("Gripper feedback requires an executed gripper step") row = self.completion.update(measured) if row["status"] == "complete": self._publish_completed_target() self.phase = "ready" elif row["status"] in ("timeout", "arrested"): if row["status"] == "timeout": self.gripper_timeouts += 1 else: self.gripper_arrests += 1 # Resuming records the unmet command and keeps the loop alive; it never # claims the gripper reached its target. self.phase = ( "ready" if self.config.resume_after_incomplete else f"gripper_{row['status']}" ) return row12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152"""The identical compact point policy used for all action-coordinate arms."""
import torchfrom pydantic import BaseModel, ConfigDict, PositiveIntfrom torch import nn
class PolicyConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) width: PositiveInt = 128 """Shared point and action feature width.""" horizon: PositiveInt = 8 """Predicted actions; only the first is executed before observing again.""" state_dim: PositiveInt = 29 """Joint position/velocity, TCP pose, observed target centroid and validity.""" use_velocity: bool = True """Include measured joint velocities; disabled only in the registered shortcut diagnostic."""
class PointChunkPolicy(nn.Module): def __init__(self, config: PolicyConfig): super().__init__() self.config = config w = config.width self.point_encoder = nn.Sequential( nn.Linear(6, w), nn.ReLU(), nn.Linear(w, w), nn.ReLU(), nn.Linear(w, w) ) self.state_encoder = nn.Sequential( nn.Linear(config.state_dim, w), nn.ReLU(), nn.Linear(w, w) ) self.query = nn.Parameter(torch.randn(config.horizon, w) * 0.02) self.decoder = nn.TransformerDecoder( nn.TransformerDecoderLayer( w, 4, 4 * w, dropout=0.0, batch_first=True, norm_first=True ), num_layers=2, ) self.output = nn.Linear(w, 10)
def forward(self, points, state): if not self.config.use_velocity: state = torch.cat( [state[:, :9], torch.zeros_like(state[:, 9:18]), state[:, 18:]], dim=-1 ) features = self.point_encoder(points) # Identical global aggregation for the three coordinate arms. memory = torch.stack( [features.amax(dim=1), features.mean(dim=1), self.state_encoder(state)], dim=1, ) queries = self.query[None].expand(points.shape[0], -1, -1) return self.output(self.decoder(queries, memory))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189"""Record selected evaluation episodes without changing policy observations."""
import jsonfrom pathlib import Pathfrom typing import Any
import gymnasium as gymimport imageio.v2 as imageioimport numpy as npimport torchfrom PIL import Image, ImageDraw, ImageFontfrom pydantic import BaseModel, ConfigDict, PositiveInt
class PolicyVideoConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) env: Any """Raw observation environment, inside the visual preprocessing wrapper.""" output_dir: Path """Directory for selected episode videos and per-frame measurements.""" seeds: tuple[int, ...] """Explicit reset seeds to record; unseeded automatic resets are excluded.""" label: str """Policy name displayed on the video.""" max_steps: PositiveInt | None = None """Optional episode budget for display only; the environment owns truncation."""
def as_array(value): if isinstance(value, torch.Tensor): return value.detach().cpu().numpy().copy() return np.asarray(value).copy()
class PolicyVideo(gym.Wrapper): def __init__(self, config: PolicyVideoConfig): super().__init__(config.env) self.config = config self.writer = None self.rows = [] self.seed = None self.step_index = 0 self.success_once = False font_path = Path("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf") self.font = ( ImageFont.truetype(str(font_path), 16) if font_path.exists() else ImageFont.load_default() )
def reset(self, **kwargs): self.finish(complete=False) obs, info = self.env.reset(**kwargs) self.seed = kwargs.get("seed") self.step_index = 0 self.success_once = False self.rows = [] if self.seed in self.config.seeds: self.config.output_dir.mkdir(parents=True, exist_ok=True) path = self.config.output_dir / f"seed{self.seed}.mp4" if path.exists(): raise FileExistsError(path) self.writer = imageio.get_writer( str(path), fps=self.unwrapped.control_freq, codec="libx264", quality=8, macro_block_size=1, ffmpeg_params=["-pix_fmt", "yuv420p", "-movflags", "+faststart"], ) self.capture(obs, info, action=None) return obs, info
def step(self, action): obs, reward, terminated, truncated, info = self.env.step(action) self.step_index += 1 if self.writer is not None: self.capture(obs, info, action=action) if bool(as_array(truncated).item()): self.finish(complete=True) return obs, reward, terminated, truncated, info
def capture(self, obs, info, action): # Copy policy RGB before rendering the independent observer camera. cameras = { name: as_array(data["rgb"])[0] for name, data in obs["sensor_data"].items() } if set(cameras) != {"base_camera", "hand_camera"}: raise ValueError("This video layout requires base and hand RGB cameras") success = bool(as_array(info.get("success", False)).item()) # As in CPUGymWrapper, success_once counts completed actions, not reset. if self.step_index: self.success_once |= success fps = self.unwrapped.control_freq row = { "step": self.step_index, "sim_time_s": self.step_index / fps, "success": success, "success_once": self.success_once, "action": None if action is None else as_array(action).tolist(), "qpos": as_array(obs["agent"]["qpos"]).tolist(), "tcp_pose": as_array(obs["extra"]["tcp_pose"]).tolist(), "cubeA_pose": as_array(self.unwrapped.cubeA.pose.raw_pose).tolist(), "cubeB_pose": as_array(self.unwrapped.cubeB.pose.raw_pose).tolist(), } for key in ("audit_release_once", "audit_release_at_end"): row[key] = bool(as_array(info.get(key, False)).item()) self.rows.append(row) observer = as_array(self.unwrapped.render_rgb_array()) if observer.ndim == 4: observer = observer[0] canvas = Image.new("RGB", (768, 592), (20, 23, 28)) canvas.paste(Image.fromarray(observer).resize((512, 512)), (0, 64)) for index, name in enumerate(("base_camera", "hand_camera")): camera = Image.fromarray(cameras[name]).resize( (256, 256), Image.Resampling.NEAREST ) canvas.paste(camera, (512, 64 + index * 256)) draw = ImageDraw.Draw(canvas) step_label = str(self.step_index) if self.config.max_steps is not None: step_label += f"/{self.config.max_steps}" draw.text( (8, 5), f"{self.config.label} | seed {self.seed} | step {step_label}" f" | t={self.step_index / fps:.2f}s", font=self.font, fill="white", ) draw.text( (8, 27), f"Official success now: {int(success)} | success once: {int(self.success_once)}", font=self.font, fill=(100, 235, 140) if success else (255, 200, 120), ) for x, y, text in ( (8, 68, "Observer view (not a policy input)"), (516, 68, "Policy: base RGB 128x128"), (516, 324, "Policy: wrist RGB 128x128"), ): box = draw.textbbox((x, y), text, font=self.font) draw.rectangle(box, fill=(20, 23, 28)) draw.text((x, y), text, font=self.font, fill="white") self.writer.append_data(np.asarray(canvas))
def finish(self, complete): if self.writer is None: return self.writer.close() self.writer = None stem = self.config.output_dir / f"seed{self.seed}" stem.with_suffix(".jsonl").write_text( "".join(json.dumps(row) + "\n" for row in self.rows) ) stem.with_suffix(".json").write_text( json.dumps( { "seed": self.seed, "policy": self.config.label, "complete": complete, "steps": self.step_index, "max_steps": self.config.max_steps, "frames": len(self.rows), "fps": self.unwrapped.control_freq, "success_once": self.success_once, "success_at_end": self.rows[-1]["success"], "first_success_step": next( (r["step"] for r in self.rows if r["step"] and r["success"]), None, ), "scope": "New recorded rollout; full initial and terminal frames. " "Left: observer only. Right: raw policy RGB enlarged 2x.", }, indent=2, ) + "\n" )
def close(self): self.finish(complete=False) return self.env.close()
def policy_video_wrapper(env, output_dir, seeds, label): return PolicyVideo( PolicyVideoConfig(env=env, output_dir=output_dir, seeds=seeds, label=label) )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122"""Simulator-free, batch-one RGB-D-to-action deployment measurement."""
import jsonimport osimport timefrom pathlib import Path
import numpy as npimport pynvmlimport torchfrom pydantic import BaseModel, ConfigDict, PositiveIntfrom pydantic_settings import CliApp
from lim.action import decode_actionfrom lim.observations import ObservationConfig, encode_observationfrom lim.policy import PointChunkPolicy, PolicyConfig
class ProfileConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) checkpoint: Path """A trained fixed-final-update policy checkpoint.""" observations: Path """Recorded CPU RGB-D arrays with camera calibration and measured proprioception.""" output_dir: Path """New directory for full per-iteration measurements.""" iterations: PositiveInt = 500 """Measured fresh-observation inference iterations after warmup.""" warmup: PositiveInt = 30 """Unmeasured warmup iterations; cold first call is separately recorded."""
def process_gpu_memory(): total = 0 for index in range(pynvml.nvmlDeviceGetCount()): handle = pynvml.nvmlDeviceGetHandleByIndex(index) for process in pynvml.nvmlDeviceGetComputeRunningProcesses(handle): if process.pid == os.getpid(): total += process.usedGpuMemory return total
def run_profile(config: ProfileConfig): config.output_dir.mkdir(parents=True, exist_ok=False) torch.set_num_threads(4) checkpoint = torch.load(config.checkpoint, map_location="cpu", weights_only=False) observations = torch.load( config.observations, map_location="cpu", weights_only=False ) model = PointChunkPolicy(PolicyConfig(**checkpoint["policy_config"])).cuda().eval() model.load_state_dict(checkpoint["state_dict"]) pynvml.nvmlInit() samples = [] peak_process_bytes = 0 cold_ms = None with torch.inference_mode(): for index in range(config.warmup + config.iterations): obs = observations[index % len(observations)] torch.cuda.synchronize() start = time.perf_counter() encoded = encode_observation(obs, ObservationConfig()) prepared = time.perf_counter() points = torch.as_tensor(encoded["points"][None], device="cuda") state = torch.as_tensor(encoded["state"][None], device="cuda") torch.cuda.synchronize() transferred = time.perf_counter() predicted = model(points, state)[0, 0].cpu().numpy() inferred = time.perf_counter() action = decode_action( predicted, encoded["tcp"], encoded["target"], checkpoint["frame"] ) torch.cuda.synchronize() finished = time.perf_counter() if not np.isfinite(action).all(): raise FloatingPointError("Nonfinite deployment action") row = { "preprocess_ms": (prepared - start) * 1000, "transfer_ms": (transferred - prepared) * 1000, "model_ms": (inferred - transferred) * 1000, "action_ms": (finished - inferred) * 1000, "total_ms": (finished - start) * 1000, } if index == 0: cold_ms = row["total_ms"] if index >= config.warmup: samples.append(row) peak_process_bytes = max(peak_process_bytes, process_gpu_memory()) fields = samples[0] percentiles = { key: { str(p): float(np.percentile([row[key] for row in samples], p)) for p in [50, 95, 99] } for key in fields } result = { "config": config.model_dump(mode="json"), "gpu": torch.cuda.get_device_name(), "torch": torch.__version__, "parameters": sum(p.numel() for p in model.parameters()), "observations": len(observations), "cold_ms": cold_ms, "latency_ms": percentiles, "peak_allocated_bytes": torch.cuda.max_memory_allocated(), "peak_reserved_bytes": torch.cuda.max_memory_reserved(), "peak_process_bytes": peak_process_bytes, "median_hz": 1000 / percentiles["total_ms"]["50"], "p95_budget_hz": 1000 / percentiles["total_ms"]["95"], "meets_7GB": 0 < peak_process_bytes <= 7_000_000_000, "meets_20Hz_p95": percentiles["total_ms"]["95"] <= 50, "scope": "two128x128 CPU RGB-D frames + calibration + proprioception to normalized controller action; includes unprojection/filtering/sampling/transfers/encoder/action-head/rotation conversion; camera exposure/network transport and low-level physical controller are external; no simulator imports or cached visual features", } (config.output_dir / "result.json").write_text(json.dumps(result, indent=2)) with (config.output_dir / "iterations.jsonl").open("w") as out: for row in samples: out.write(json.dumps(row) + "\n") print("PROFILE_COMPLETE", json.dumps(result), flush=True) pynvml.nvmlShutdown()
if __name__ == "__main__": run_profile(CliApp.run(ProfileConfig))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855"""Load the pinned official ACT and audit its unmodified evaluation path."""
import hashlibimport importlib.utilimport ioimport jsonimport mathimport sysimport timefrom functools import partialfrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Any, Literal
import gymnasium as gymimport numpy as npimport pynvmlimport torchfrom pydantic import BaseModel, ConfigDict, PositiveInt, model_validatorfrom pydantic_settings import CliApp
from lim.act_policy import ACTPolicyConfig, build_policy, evaluation_transportfrom lim.action_encoding import encoded_dimension, sixd_to_controllerfrom lim.chunk_coordinates import pose_target_contractfrom lim.gripper_execution import GripperExecutionConfigfrom lim.normalization import checked_statisticsfrom lim.profile import process_gpu_memoryfrom lim.tasks import TASKS
PROFILE_SCOPE = ( "batch1 raw CPU RGB/proprioception through official resize, transfers, normalization, " "ResNet, configured policy and native temporal aggregation (with target conversion " "for chunk_relative); simulator-free replay of saved raw " "inputs; excludes camera acquisition/transport and low-level physical control; " "NVML sampled after each iteration")
ACTControlMode = Literal["pd_ee_delta_pos", "pd_ee_delta_pose"]ACTION_DIMENSIONS = {"pd_ee_delta_pos": 4, "pd_ee_delta_pose": 7}
def load_checkpoint(path): raw = path.read_bytes() checkpoint = torch.load(io.BytesIO(raw), map_location="cpu", weights_only=False) if "ema_agent" not in checkpoint or checkpoint["norm_stats"] is not None: raise ValueError("Expected official delta-control EMA checkpoint") return checkpoint, { "checkpoint_sha256": hashlib.sha256(raw).hexdigest(), "loaded_weight_key": "ema_agent", }
def check_policy_checkpoint(checkpoint, config): declared = ACTPolicyConfig.model_validate(checkpoint.get("policy", {})) if ( declared != config.policy or checkpoint.get("num_queries", 30) != config.num_queries or checkpoint.get("control_mode", "pd_ee_delta_pos") != config.control_mode ): raise ValueError( "Checkpoint policy, control mode or prediction horizon differs from evaluation" ) if "ema_agent" in checkpoint: # Metadata alone must not relabel a Q30 network as Q1. Wrappers add # prefixes, but every supported ACT variant owns one query embedding. weights = checkpoint["ema_agent"] queries = [ value for name, value in weights.items() if name.endswith("query_embed.weight") ] if len(queries) != 1 or tuple(queries[0].shape) != ( config.num_queries, config.architecture.hidden_dim, ): raise ValueError( "Checkpoint query embedding disagrees with prediction horizon" ) for name, value in weights.items(): if name.endswith("pos_table") and tuple(value.shape) != ( 1, config.num_queries + 2, config.architecture.hidden_dim, ): raise ValueError( "Checkpoint posterior position table disagrees with prediction horizon" ) checked_statistics( checkpoint.get("normalization"), declared.normalization, declared.action_encoding, ) if declared.method == "chunk_relative" and declared.action_encoding == "rotation6d": # The contract must match the checkpoint's own label frame, so a model is # never evaluated in a frame it was not trained in. expected = pose_target_contract( declared.chunk_anchor, declared.chunk_pose_supervision, declared.chunk_gripper_supervision, declared.chunk_padding, declared.chunk_normalization_population, declared.chunk_label_offset, declared.chunk_waypoint_threshold_m, ) if checkpoint.get("action_target_contract") != expected: raise ValueError( "Checkpoint contract does not match its anchor, pose or gripper supervision" )
def source_provenance(config): declared = json.loads(Path("round2/reference-source.json").read_text()) source = Path("third_party/ManiSkill/examples/baselines/act/train_rgbd.py") if config.source.resolve() != source.resolve(): raise ValueError("Reference source must match the pinned official loader") actual = { p: hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in declared["sha256"] } if actual != declared["sha256"]: raise ValueError("Official source differs from audited hashes") return {"official_source_sha256": actual, "reference_commit": declared["commit"]}
class ACTArchitectureConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) hidden_dim: PositiveInt = 256 """Official ACT transformer hidden width.""" dim_feedforward: PositiveInt = 512 """Official transformer feed-forward width.""" enc_layers: PositiveInt = 2 """Encoder layers in the official architecture.""" dec_layers: PositiveInt = 4 """Decoder layers in the official architecture."""
class ReferenceConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) mode: Literal["witness", "evaluate", "profile"] = "witness" """Environment witness, fixed-checkpoint evaluation, or simulator-free profile.""" source: Path = Path("third_party/ManiSkill/examples/baselines/act/train_rgbd.py") """Pinned, unmodified official implementation containing Agent and preprocessing.""" checkpoint: Path | None = None """Official final checkpoint; evaluation and profile load its ema_agent entry.""" output_dir: Path = Path("artifacts/round2/witness") """New output directory, with raw episode or timing records.""" episodes: PositiveInt = 100 """Fixed number of complete evaluation episodes.""" num_envs: PositiveInt = 10 """CPU physics vector environments; episodes must be divisible by this count.""" seed_start: int = 50000 """Explicit, disjoint per-episode seed block.""" observations: Path | None = None """Folder with saved raw RGB/proprioceptive inputs for profiling.""" iterations: PositiveInt = 500 """Measured warmed profile calls; 30 additional warmup calls precede these.""" demonstration_metadata: Path = Path( "data/official-demos/StackCube-v1/motionplanning/trajectory.rgb.pd_ee_delta_pos.physx_cpu.json" ) """Converted demonstration metadata supplying the evaluation sensor configuration.""" architecture: ACTArchitectureConfig = ACTArchitectureConfig() """Explicit trained model shape; defaults preserve the Round2 small reference.""" policy: ACTPolicyConfig = ACTPolicyConfig() """Trained architecture/input variant; must match checkpoint metadata.""" num_queries: PositiveInt = 30 """Actual trained decoder query count, including one for a single-target model; native evaluation queries fresh observations each control step.""" video_seeds: tuple[int, ...] = () """Optional explicit scene seeds to record, including raw RGB and observer view.""" keypose_trace: bool = False """Record read-only target, TCP error, and arrival-gate diagnostics for keyposes.""" control_mode: ACTControlMode = "pd_ee_delta_pos" """Controller shared by the trained action labels and online environment.""" gripper_execution: GripperExecutionConfig = GripperExecutionConfig() """Optional inference-only gripper intervention and chunk-level diagnostics."""
@model_validator(mode="after") def validate_execution(self): if self.keypose_trace and ( self.mode != "evaluate" or self.policy.keypose is None ): raise ValueError("Keypose diagnostics require keypose evaluation") if self.policy.keypose is not None and ( self.mode != "evaluate" or self.control_mode != "pd_ee_delta_pose" ): raise ValueError( "Keypose transport currently supports pose evaluation only" ) if self.gripper_execution.active and ( self.mode != "evaluate" or self.control_mode != "pd_ee_delta_pose" or self.policy.method != "cvae" or self.policy.action_encoding != "rotation6d" or self.policy.keypose is not None ): raise ValueError( "Gripper execution experiments require CVAE pose6D evaluation" ) return self
def load_official(config): source_provenance(config) # The vendor's act/ is a namespace directory; its setup.find_packages() # does not install it. Match direct train_rgbd.py execution's import root. source_root = str(config.source.resolve().parent) if source_root not in sys.path: sys.path.insert(0, source_root) # Use the file's importable name so forkserver CPU workers can reconstruct # the official observation-wrapper class from the inherited sys.path. spec = importlib.util.spec_from_file_location(config.source.stem, config.source) module = importlib.util.module_from_spec(spec) sys.modules[spec.name] = module spec.loader.exec_module(module) # Agent and Dataset reference the script's module-global args at runtime. module.args = module.Args( **config.architecture.model_dump(), include_depth=False, env_id="StackCube-v1", control_mode=config.control_mode, max_episode_steps=200, sim_backend="physx_cpu", temporal_agg=True, num_queries=config.num_queries, ) return module
class AuditConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) env: Any """Official environment, before visual preprocessing and CPU metric wrappers.""" snapshots: Path """Raw policy-input snapshots, saved only from the first vector slot.""" stride: int """Number of vector slots for deterministic snapshot ownership.""" seed_start: int """First held-out seed, used only for snapshot ownership."""
class ReleasedSupportAudit(gym.Wrapper): def __init__(self, config: AuditConfig): super().__init__(config.env) self.config = config self.streak = 0 self.once = False self.explicit_seed = None self.step_index = 0
def snapshot(self, obs): if ( self.explicit_seed is None or (self.explicit_seed - self.config.seed_start) % self.config.stride ): return if self.step_index not in (0, 10, 30, 70, 120, 199): return folder = self.config.snapshots folder.mkdir(parents=True, exist_ok=True) if len(list(folder.glob("*.pt"))) >= 12: return
def cpu(value): if isinstance(value, dict): return {k: cpu(v) for k, v in value.items()} return value.detach().cpu().clone() if torch.is_tensor(value) else value
torch.save( cpu(obs), folder / f"seed{self.explicit_seed}_step{self.step_index}.pt" )
def reset(self, **kwargs): obs, info = self.env.reset(**kwargs) self.streak, self.once, self.step_index = 0, False, 0 self.explicit_seed = kwargs.get("seed") self.snapshot(obs) return obs, info
def step(self, action): obs, reward, terminated, truncated, info = self.env.step(action) base = self.env.unwrapped if base.spec.id != "StackCube-v1": # The released-support audit is StackCube's cube-on-cube rule; other # tasks only need the observation snapshots. self.step_index += 1 self.snapshot(obs) return obs, reward, terminated, truncated, info source, target = base.cubeA, base.cubeB support_force = base.scene.get_pairwise_contact_forces(source, target) contact = 0.0 for link in base.agent.robot.get_links(): contact = max( contact, float( torch.linalg.norm( base.scene.get_pairwise_contact_forces(source, link), dim=-1 ).item() ), ) strict = ( abs(float(support_force[0, 2])) > 0.1 and float((source.pose.p - target.pose.p)[0, 2]) > 0.025 and bool(source.is_static(lin_thresh=1e-2, ang_thresh=0.5).item()) and contact < 0.01 and bool((base.agent.robot.get_qpos()[0, -2:] >= 0.035).all()) ) self.streak = self.streak + 1 if strict else 0 self.once = self.once or self.streak >= 20 info["audit_release_once"] = self.once info["audit_release_at_end"] = self.streak >= 20 info["audit_robot_contact"] = contact self.step_index += 1 self.snapshot(obs) return obs, reward, terminated, truncated, info
def audit_wrapper(env, snapshots, stride, seed_start): return ReleasedSupportAudit( AuditConfig(env=env, snapshots=snapshots, stride=stride, seed_start=seed_start) )
class RecorderConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) env: Any """Official CPU vector environment with SAME_STEP autoreset semantics.""" run: ReferenceConfig """Declared seed block and output destination."""
class SeededRecorder: """Record official metrics, explicitly seed each new batch, preserve ACT evaluation."""
def __init__(self, config: RecorderConfig): self.config = config self.rows = [] self.calls = 0 self.seed_batch = 0 self.model_queries = 0 self.previous_model_queries = 0 self.batch_steps = 0
def count_inference(self, module, inputs): self.model_queries += 1
def __getattr__(self, name): return getattr(self.config.env, name)
def reset(self): start = self.config.run.seed_start + self.seed_batch * self.num_envs return self.config.env.reset(seed=list(range(start, start + self.num_envs)))
def step(self, action): obs, reward, terminated, truncated, info = self.config.env.step(action) self.calls += 1 self.batch_steps += 1 if truncated.any(): assert truncated.all() for slot, final in enumerate(info["final_info"]): row = {k: np.asarray(v).item() for k, v in final["episode"].items()} row.update( seed=self.config.run.seed_start + self.seed_batch * self.num_envs + slot, audit_release_once=bool(final["audit_release_once"]), audit_release_at_end=bool(final["audit_release_at_end"]), steps=self.batch_steps, policy_calls=self.model_queries - self.previous_model_queries, ) self.rows.append(row) with (self.config.run.output_dir / "episodes.jsonl").open("a") as f: f.write(json.dumps(row) + "\n") print( json.dumps( { "completed": len(self.rows), "success_once": sum(r["success_once"] for r in self.rows), "success_at_end": sum(r["success_at_end"] for r in self.rows), } ), flush=True, ) self.seed_batch += 1 self.previous_model_queries = self.model_queries self.batch_steps = 0 if len(self.rows) < self.config.run.episodes: # SAME_STEP already performed an unseeded reset. Replace that # initial state before any policy action, keeping final_info intact. obs, _ = self.reset() return obs, reward, terminated, truncated, info
def create_env(module, config, count): metadata = json.loads(config.demonstration_metadata.read_text()) info = metadata["env_info"] if info["env_id"] not in TASKS: raise ValueError("Demonstration metadata task mismatch") sensor_configs = info["env_kwargs"]["sensor_configs"] if info["env_kwargs"].get("control_mode") != config.control_mode: raise ValueError("Demonstration metadata and evaluation controller differ") if config.policy.method == "chunk_relative" and config.control_mode != ( "pd_ee_delta_pose" if config.policy.action_encoding == "rotation6d" else "pd_ee_delta_pos" ): raise ValueError( "Chunk-relative action encoding and physical source controller disagree" ) wrappers = [ partial( audit_wrapper, snapshots=config.output_dir / "raw_observations", stride=count, seed_start=config.seed_start, ), ] if config.video_seeds: from lim.policy_video import policy_video_wrapper
wrappers.append( partial( policy_video_wrapper, output_dir=config.output_dir / "videos", seeds=config.video_seeds, label="keypose" if config.policy.keypose is not None else config.policy.method, ) ) wrappers.append(partial(module.FlattenRGBDObservationWrapper, depth=False)) return module.make_eval_envs( info["env_id"], count, "physx_cpu", { "control_mode": config.control_mode, "reward_mode": "sparse", "obs_mode": "rgb", "render_mode": "rgb_array", "max_episode_steps": 200, "sensor_configs": sensor_configs, }, None, wrappers=wrappers, )
def evaluate(config): if config.episodes % config.num_envs: raise ValueError("Episode count must be divisible by vector environment count") config.output_dir.mkdir(parents=True, exist_ok=False) module = load_official(config) official_evaluate = module.evaluate env = create_env(module, config, config.num_envs) gripper_trace = None keypose_trace = None try: ck, provenance = load_checkpoint(config.checkpoint) check_policy_checkpoint(ck, config) agent = build_policy( module, env, module.args, config.policy, ck.get("normalization") ).cuda() agent.load_state_dict(ck["ema_agent"]) recorder = SeededRecorder(RecorderConfig(env=env, run=config)) query_hook = agent.model.register_forward_pre_hook(recorder.count_inference) kwargs = { "stats": ck["norm_stats"], "num_queries": 1 if config.policy.keypose is not None else config.num_queries, "temporal_agg": True, "max_timesteps": 200, "device": torch.device("cuda"), "sim_backend": "physx_cpu", } start = time.monotonic() physical_env = recorder if config.gripper_execution.active: from lim.action_objective import BinaryGripperEnv, BinaryGripperEnvConfig from lim.gripper_execution import ( GripperAgent, GripperBoundaryConfig, GripperDecisionEnv, GripperPhysicalEnv, GripperTrace, GripperTraceConfig, )
gripper_trace = GripperTrace( GripperTraceConfig( execution=config.gripper_execution, output_dir=config.output_dir, num_envs=config.num_envs, horizon=config.num_queries, seed_start=config.seed_start, bce=config.policy.action_loss.method == "gripper_bce", ) ) physical_env = GripperPhysicalEnv( GripperBoundaryConfig( wrapped=recorder, trace=gripper_trace, ) ) if config.gripper_execution.binary and not gripper_trace.config.bce: physical_env = BinaryGripperEnv( BinaryGripperEnvConfig(env=physical_env) ) evaluation_agent, evaluation_env = evaluation_transport( agent, physical_env, config.policy ) if config.keypose_trace: from lim.keypose_trace import KeyposeTraceConfig, KeyposeTraceEnv
keypose_trace = KeyposeTraceEnv( KeyposeTraceConfig( env=evaluation_env, path=config.output_dir / "keypose_trace.jsonl", seed_start=config.seed_start, ) ) evaluation_env = keypose_trace if gripper_trace is not None: evaluation_agent = GripperAgent( GripperBoundaryConfig( wrapped=evaluation_agent, trace=gripper_trace, ) ) evaluation_env = GripperDecisionEnv( GripperBoundaryConfig( wrapped=evaluation_env, trace=gripper_trace, ) ) metrics = official_evaluate( config.episodes, evaluation_agent, evaluation_env, kwargs ) query_hook.remove() assert recorder.model_queries == recorder.calls for name in ("success_once", "success_at_end"): assert int(np.asarray(metrics[name]).sum()) == sum( r[name] for r in recorder.rows ) result = { "provenance": provenance | source_provenance(config), "sensor_configs": json.loads(config.demonstration_metadata.read_text())[ "env_info" ]["env_kwargs"]["sensor_configs"], "config": config.model_dump(mode="json"), "episodes": len(recorder.rows), "counts": { key: sum(r[key] for r in recorder.rows) for key in ( "success_once", "success_at_end", "audit_release_once", "audit_release_at_end", ) }, "policy_vector_calls": recorder.model_queries, "environment_vector_steps": recorder.calls, "expected_policy_vector_calls": config.episodes // config.num_envs * 200, "feedback_hz": 20, "parameters": sum(p.numel() for p in agent.parameters()), "wall_s": time.monotonic() - start, "gpu": torch.cuda.get_device_name(), "checkpoint_rule": "official final update EMA; no test checkpoint selection", } if config.policy.keypose is not None: result["action_execution"] = ( "Newest first query world keypose; no temporal averaging; observed TCP controller with arrival-gated continuous gripper. No oracle stages or object states." ) if config.policy.action_loss.method == "gripper_bce": result["gripper_execution"] = evaluation_env.diagnostics() if config.gripper_execution.aggregation == "latest": result["gripper_execution"]["rule"] = ( "newest chunk first-step p(open); >=0.5 opens; no hysteresis" ) if gripper_trace is not None: result["gripper_intervention"] = gripper_trace.diagnostics() (config.output_dir / "result.json").write_text(json.dumps(result, indent=2)) print("REFERENCE_EVAL_COMPLETE", json.dumps(result), flush=True) finally: if keypose_trace is not None: keypose_trace.finish() if gripper_trace is not None: gripper_trace.close() env.close()
def witness(config): config.output_dir.mkdir(parents=True, exist_ok=True) torch.manual_seed(0) module = load_official(config) env = create_env(module, config, 1) try: obs, _ = env.reset(seed=123456) base = env.envs[0].unwrapped agent = build_policy(module, env, module.args, config.policy).cuda() state_shape, rgb_shape = list(obs["state"].shape), list(obs["rgb"].shape) with torch.inference_mode(): pred = agent.get_action( {k: torch.as_tensor(v, device="cuda") for k, v in obs.items()} ) assert ( pred.shape == ( 1, config.num_queries, encoded_dimension( ACTION_DIMENSIONS[config.control_mode], config.policy.action_encoding, ), ) and torch.isfinite(pred).all() ) assert base.control_freq == 20 command = ( sixd_to_controller(pred[:, 0]) if config.policy.action_encoding == "rotation6d" else pred[:, 0] ) if config.policy.action_loss.method == "gripper_bce": _, execution_env = evaluation_transport(agent, env, config.policy) execution_env.step(pred[:, 0].cpu().numpy()) else: env.step(command.cpu().numpy()) result = { "status": "PASS", "actual_sensor_shader_packs": { k: v.config.shader_pack for k, v in base._sensors.items() }, "gymnasium": gym.__version__, "torch": torch.__version__, "control_hz": base.control_freq, "control_mode": base.control_mode, "sim_hz": base.sim_freq, "robot": base.agent.uid, "state_shape": state_shape, "rgb_shape": rgb_shape, "action_shape": list(pred.shape), "controller_action_shape": list(command.shape), "action_encoding": config.policy.action_encoding, "parameters": sum(p.numel() for p in agent.parameters()), "gpu": torch.cuda.get_device_name(), } (config.output_dir / "result.json").write_text(json.dumps(result, indent=2)) print("REFERENCE_WITNESS", json.dumps(result), flush=True) finally: env.close()
class ReplayConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) module: Any """Pinned official module, supplying the exact RGB observation transformation.""" observations: list """Raw CPU camera and proprioceptive observations; no encoded visual features."""
class SensorReplay: """Feed real raw inputs through official evaluate() without a physics environment."""
def __init__(self, config: ReplayConfig): self.config = config self.processor = SimpleNamespace( include_rgb=True, include_depth=False, include_state=True, transforms=config.module.T.Compose( [config.module.T.Resize((224, 224), antialias=True)] ), ) example = self.prepare(0) self.single_observation_space = gym.spaces.Dict( { "state": gym.spaces.Box( -np.inf, np.inf, shape=example["state"].shape[1:], dtype=np.float32 ), "rgb": gym.spaces.Box( 0, 255, shape=example["rgb"].shape[1:], dtype=np.uint8 ), } ) action_dim = ACTION_DIMENSIONS[config.module.args.control_mode] self.single_action_space = gym.spaces.Box( -1, 1, (action_dim,), dtype=np.float32 ) self.action_space = gym.spaces.Box(-1, 1, (1, action_dim), dtype=np.float32) self.num_envs = 1 self.calls = 0 self.started = None self.rows = []
def prepare(self, index): # The official transform pops top-level keys only; preserve the raw record. raw = dict(self.config.observations[index % len(self.config.observations)]) return self.config.module.FlattenRGBDObservationWrapper.observation( self.processor, raw )
def next_observation(self): torch.cuda.synchronize() self.started = time.perf_counter() return self.prepare(self.calls)
def reset(self): return self.next_observation(), {}
def step(self, action): torch.cuda.synchronize() elapsed = (time.perf_counter() - self.started) * 1000 if not np.isfinite(action).all(): raise FloatingPointError("Nonfinite reference policy action") self.rows.append( { "index": self.calls, "total_ms": elapsed, "sampled_process_bytes": process_gpu_memory(), } ) self.calls += 1 truncated = np.array([self.calls % 200 == 0]) # Required vector episode bookkeeping, deliberately containing no task score. info = ( {"final_info": [{"episode": {"measurement_episode": self.calls // 200}}]} if truncated[0] else {} ) return ( self.next_observation(), np.array([0.0]), np.array([False]), truncated, info, )
def profile(config): if config.checkpoint is None or config.observations is None: raise ValueError("Profile requires checkpoint and raw observations") config.output_dir.mkdir(parents=True, exist_ok=False) module = load_official(config) paths = sorted(config.observations.glob("*.pt")) if not paths: raise ValueError("No raw observations for profile") raw_inputs = {p.name: p.read_bytes() for p in paths} replay = SensorReplay( ReplayConfig( module=module, observations=[ torch.load(io.BytesIO(raw), map_location="cpu", weights_only=False) for raw in raw_inputs.values() ], ) ) checkpoint, provenance = load_checkpoint(config.checkpoint) check_policy_checkpoint(checkpoint, config) agent = build_policy( module, replay, module.args, config.policy, checkpoint.get("normalization") ).cuda() agent.load_state_dict(checkpoint["ema_agent"]) pynvml.nvmlInit() model_queries = 0
def count_query(module, inputs): nonlocal model_queries model_queries += 1
query_hook = agent.model.register_forward_pre_hook(count_query) # Complete full 200-step official evaluator episodes. Measure exactly the # declared 500 calls after 30 warmup; trailing padding calls are separate. total_episodes = math.ceil((30 + config.iterations) / 200) evaluation_agent, evaluation_env = evaluation_transport( agent, replay, config.policy ) module.evaluate( total_episodes, evaluation_agent, evaluation_env, { "stats": checkpoint["norm_stats"], "num_queries": config.num_queries, "temporal_agg": True, "max_timesteps": 200, "device": torch.device("cuda"), "sim_backend": "physx_cpu", }, ) query_hook.remove() assert model_queries == replay.calls measured = replay.rows[30 : 30 + config.iterations] assert len(measured) == config.iterations timings = [row["total_ms"] for row in measured] result = { "provenance": provenance | source_provenance(config) | { "raw_observations_sha256": { name: hashlib.sha256(raw).hexdigest() for name, raw in raw_inputs.items() } }, "config": config.model_dump(mode="json"), "gpu": torch.cuda.get_device_name(), "parameters": sum(p.numel() for p in agent.parameters()), "raw_observations": len(paths), "warmup_calls": 30, "measured_calls": len(measured), "total_official_evaluator_calls": replay.calls, "actual_model_queries": model_queries, "trailing_unmeasured_calls": replay.calls - 30 - len(measured), "cold_ms": replay.rows[0]["total_ms"], "latency_ms": { str(p): float(np.percentile(timings, p)) for p in (50, 95, 99, 100) }, "sampled_peak_process_bytes": max( row["sampled_process_bytes"] for row in replay.rows ), "peak_allocated_bytes": torch.cuda.max_memory_allocated(), "peak_reserved_bytes": torch.cuda.max_memory_reserved(), "scope": PROFILE_SCOPE, } with (config.output_dir / "iterations.jsonl").open("w") as out: for row in replay.rows: out.write( json.dumps( row | {"measured": 30 <= row["index"] < 30 + config.iterations} ) + "\n" ) (config.output_dir / "result.json").write_text(json.dumps(result, indent=2)) print("REFERENCE_PROFILE_COMPLETE", json.dumps(result), flush=True)
def run(config: ReferenceConfig): torch.set_num_threads(4) if config.mode == "witness": witness(config) elif config.mode == "evaluate": if config.checkpoint is None: raise ValueError("Evaluation requires a checkpoint") evaluate(config) else: profile(config)
if __name__ == "__main__": run(CliApp.run(ReferenceConfig))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247"""Replay original joint-space demonstrations with explicit episode boundaries.
Keep ManiSkill's position conversion, and invert its actual CPU Euler controllerfor pose conversion. Only initial states are restored; all subsequent observationsare generated by executed actions. Each successful record carries its source ID."""
import copyimport hashlibimport jsonfrom collections.abc import Callablefrom pathlib import Pathfrom typing import Any
import gymnasium as gymimport h5pyimport mani_skill.envs # noqa: F401import numpy as npimport torchfrom mani_skill.trajectory.utils.actions.conversion import from_pd_joint_posfrom mani_skill.utils import commonfrom mani_skill.utils.geometry.rotation_conversions import ( matrix_to_euler_angles, quaternion_to_matrix,)from mani_skill.utils.structs.pose import Posefrom mani_skill.utils.wrappers.record import RecordEpisodefrom pydantic import BaseModel, ConfigDict, PositiveIntfrom pydantic_settings import CliApp
from lim.reference_act import ACTION_DIMENSIONS, ACTControlMode
class PoseReplayConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) source: Path """Original joint-position H5, with matching source metadata JSON.""" output_dir: Path """New directory; existing data is never overwritten.""" control_mode: ACTControlMode = "pd_ee_delta_pose" """Target controller, with all camera settings retained from the source.""" source_ids: tuple[int, ...] """Explicit original episode IDs attempted in this declared order.""" max_substeps: PositiveInt = 4 """Maximum target-control steps per source action, matching official replay.""" save_video: bool = False """Save observer videos for the pilot; formal data need not record videos."""
class TargetReplayConfig(BaseModel, frozen=True): model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid") original: Any """Original joint-control environment.""" target: Any """Target pose environment, optionally wrapped for recording.""" actions: Any """Original joint-position demonstration actions.""" max_substeps: PositiveInt = 4 """Bounded target-action retries for clipped commands.""" on_target_step: Callable[[int], None] | None = None """Optional observer called after each executed target step with its source action index."""
def pose_target_command(controller, goal_world): """Return a bounded command and whether the requested delta was clipped.""" if ( controller.config.frame != "root_translation:root_aligned_body_rotation" or not controller.config.use_delta or controller.config.use_target or not controller.config.normalize_action ): raise ValueError("Expected current-pose-relative normalized root-frame control") previous = controller.ee_pose_at_base goal = controller.root_link.pose.inv() * goal_world low, high = controller.action_space_low[:3], controller.action_space_high[:3] pos = 2 * (goal.p - previous.p - low) / (high - low) - 1 # CPU ManiSkill 3.0.1 applies Euler XYZ *negative* rot_lower, then left-composes. delta_rotation = goal.q from mani_skill.utils.geometry.rotation_conversions import ( quaternion_invert, quaternion_multiply, )
delta_rotation = quaternion_multiply(delta_rotation, quaternion_invert(previous.q)) angles = matrix_to_euler_angles(quaternion_to_matrix(delta_rotation), "XYZ") rot = angles / controller.config.rot_lower norm = torch.linalg.norm(rot, dim=-1, keepdim=True) clipped = bool((pos.abs() > 1).any() or (norm > 1).any()) return torch.cat([pos.clamp(-1, 1), rot / norm.clamp(min=1)], dim=-1), clipped
def replay_targets(config: TargetReplayConfig): original = config.original.unwrapped.agent.controller target = config.target.unwrapped.agent.controller ori_arm, arm = original.controllers["arm"], target.controllers["arm"] pin = original.articulation.create_pinocchio_model() info = {} for source_index, action in enumerate(config.actions): action = common.to_tensor(action, device=config.original.unwrapped.device) parts = original.to_action_dict(action) config.original.step(action) qpos = original.articulation.get_qpos().clone() qpos[:, ori_arm.active_joint_indices] = ori_arm._target_qpos pin.compute_forward_kinematics(qpos.cpu().numpy()[0]) goal = Pose.create( original.articulation.pose.sp * pin.get_link_pose(arm.ee_link.index) ) for _ in range(config.max_substeps): command, clipped = pose_target_command(arm, goal) out = {**parts, "arm": command[0]} _, _, _, _, info = config.target.step(target.from_action_dict(out)) if config.on_target_step is not None: config.on_target_step(source_index) if not clipped: break return info
def tree_first(group): return { k: tree_first(v) if isinstance(v, h5py.Group) else v[0] for k, v in group.items() }
def replace_last(destination, source): if isinstance(destination, dict): for key in destination: replace_last(destination[key], source[key]) else: destination[-1] = source[-1]
def run(config: PoseReplayConfig): torch.set_num_threads(4) config.output_dir.mkdir(parents=True, exist_ok=False) metadata = json.loads(config.source.with_suffix(".json").read_text()) episodes = {e["episode_id"]: e for e in metadata["episodes"]} if len(set(config.source_ids)) != len(config.source_ids): raise ValueError("Duplicate source IDs") env_info = metadata["env_info"] kwargs = copy.deepcopy(env_info["env_kwargs"]) kwargs.update(sim_backend="physx_cpu", num_envs=1, max_episode_steps=200) original = gym.make(env_info["env_id"], **kwargs) kwargs.update(obs_mode="rgb", control_mode=config.control_mode) target = RecordEpisode( gym.make(env_info["env_id"], **kwargs), output_dir=str(config.output_dir), trajectory_name="trajectory", save_trajectory=True, save_video=config.save_video, save_on_reset=False, info_on_video=True, video_fps=20, ) records = [] try: with h5py.File(config.source) as source: for source_id in config.source_ids: episode = episodes[source_id] if episode["control_mode"] != "pd_joint_pos": raise ValueError("Source must use joint-position expert actions") group = source[f"traj_{source_id}"] reset = copy.deepcopy(episode["reset_kwargs"]) # Explicitly clear even FAILED attempts before another reset. if target._trajectory_buffer is not None: target.flush_trajectory(save=False) if config.save_video: target.flush_video(save=False) original.reset(**reset) target.reset(**reset) initial = tree_first(group["env_states"]) original.unwrapped.set_state_dict(initial) target.unwrapped.set_state_dict(initial) initial_obs = target.unwrapped.get_obs() replace_last(target._trajectory_buffer.state, common.batch(initial)) replace_last( target._trajectory_buffer.observation, common.to_numpy(common.batch(initial_obs)), ) if config.save_video: target.render_images = [] if config.control_mode == "pd_ee_delta_pos": info = from_pd_joint_pos( config.control_mode, group["actions"][:], original, target ) else: info = replay_targets( TargetReplayConfig( original=original, target=target, actions=group["actions"][:], max_substeps=config.max_substeps, ) ) success = bool(common.to_numpy(info["success"]).item()) buffer = target._trajectory_buffer count = len(buffer.action) - 1 assert buffer.action.shape[-1] == ACTION_DIMENSIONS[config.control_mode] assert len(buffer.observation["extra"]["tcp_pose"]) == count + 1 record = { "source_episode_id": source_id, "source_episode_seed": episode["episode_seed"], "source_steps": len(group["actions"]), "target_steps": count, "success": success, "output_episode_id": target._episode_id + 1 if success else None, "max_abs_rotation_action": float( np.abs(buffer.action[1:, :, 3:6]).max() ) if config.control_mode == "pd_ee_delta_pose" else None, } target.flush_trajectory(save=success) if success: target._json_data["episodes"][-1].update( source_episode_id=source_id, source_episode_seed=episode["episode_seed"], ) if config.save_video: target.flush_video(name=f"source{source_id}", save=success) records.append(record) with (config.output_dir / "attempts.jsonl").open("a") as f: f.write(json.dumps(record) + "\n") print("REPLAY_EPISODE", json.dumps(record), flush=True) finally: # Successful data were flushed deliberately; never save residual failures. if target._trajectory_buffer is not None: target.flush_trajectory(save=False) target.close() original.close() result = { "config": config.model_dump(mode="json"), "source_sha256": hashlib.sha256(config.source.read_bytes()).hexdigest(), "attempted": len(records), "successful": sum(r["success"] for r in records), "records": records, "rotation_encoding": "CPU Euler XYZ inverse including rot_lower sign; radial clipping", "state_restoration": "source state0 only; saved initial state and observation repaired before actions", "episode_boundary": "flush failed and successful attempts independently", } (config.output_dir / "result.json").write_text(json.dumps(result, indent=2) + "\n") print("REPLAY_COMPLETE", json.dumps(result), flush=True)
if __name__ == "__main__": run(CliApp.run(PoseReplayConfig))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194"""Run a declared finite experiment sequence when its assigned GPU is free."""
import fcntlimport hashlibimport jsonimport osimport signalimport subprocessimport timefrom pathlib import Path
from pydantic import BaseModel, ConfigDict, NonNegativeInt, PositiveIntfrom pydantic_settings import CliApp
from lim.job import JobConfig, run_job
class SequenceConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) jobs: tuple[Path, ...] """Ordered immutable JobConfig specifications; any failure stops successors.""" output_dir: Path """New sequence state directory; never resume an interrupted sequence implicitly.""" gpu: NonNegativeInt """One preselected physical GPU, matching every job's assignment.""" max_wait_s: PositiveInt = 172800 """Maximum time waiting for shared GPU availability before stopping.""" poll_s: PositiveInt = 30 """Availability interval; no model or renderer is created while waiting.""" free_memory_mib: PositiveInt = 500 """Maximum existing GPU allocation permitted before launching a job.""" required_files: dict[Path, str] = {} """Exact SHA256 for asynchronously copied inputs; checked before any GPU work.""" prerequisite_sequence: Path | None = None """Existing sequence state.json that must complete before taking the GPU lock."""
class SequenceCLIConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) spec: Path """Complete JSON SequenceConfig, including input dependencies and assigned GPU."""
def run(config: SequenceConfig): jobs = [JobConfig.model_validate_json(p.read_text()) for p in config.jobs] if not jobs or any(j.gpu != config.gpu for j in jobs): raise ValueError("Sequence must be nonempty and use exactly its assigned GPU") config.output_dir.mkdir(parents=True, exist_ok=False) record = { "status": "waiting", "config": config.model_dump(mode="json"), "jobs": [j.model_dump(mode="json") for j in jobs], "completed_jobs": [], "started_epoch": time.time(), } path = config.output_dir / "state.json"
def write(): tmp = path.with_suffix(".tmp") tmp.write_text(json.dumps(record, indent=2) + "\n") tmp.replace(path)
def interrupted(signum, frame): raise KeyboardInterrupt(f"Sequence received signal {signum}")
signal.signal(signal.SIGTERM, interrupted) write() remaining_wait = config.max_wait_s try: input_wait_started = time.monotonic() while missing := [str(p) for p in config.required_files if not p.is_file()]: record.update( status="waiting_for_inputs", missing_files=missing, checked_epoch=time.time(), ) write() if time.monotonic() - input_wait_started >= remaining_wait: raise TimeoutError("Input transfer did not complete") time.sleep(config.poll_s) for p, expected in config.required_files.items(): with p.open("rb") as stream: actual = hashlib.file_digest(stream, "sha256").hexdigest() if actual != expected: raise ValueError(f"Input digest mismatch: {p}") remaining_wait -= time.monotonic() - input_wait_started record.pop("missing_files", None) record["inputs_verified"] = True write() dependency_started = time.monotonic() if config.prerequisite_sequence is not None: while True: dependency = json.loads(config.prerequisite_sequence.read_text()) status = dependency["status"] if status == "complete": record["prerequisite_complete"] = str(config.prerequisite_sequence) break if status in ("failed", "interrupted"): raise RuntimeError( f"Prerequisite sequence {status}; successors stopped" ) record.update( status="waiting_for_prerequisite", checked_epoch=time.time() ) write() if time.monotonic() - dependency_started >= remaining_wait: raise TimeoutError("Prerequisite sequence did not complete") time.sleep(config.poll_s) remaining_wait -= time.monotonic() - dependency_started # Cooperating project workers cannot race for the same physical device. with Path(f"/tmp/lim-gpu-{os.getuid()}-{config.gpu}.lock").open("a") as lock: lock_started = time.monotonic() while True: try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) break except BlockingIOError: record.update(status="waiting_for_lock", checked_epoch=time.time()) write() if time.monotonic() - lock_started >= remaining_wait: raise TimeoutError( "Assigned GPU remained reserved by another sequence" ) time.sleep(config.poll_s) remaining_wait -= time.monotonic() - lock_started for spec, job in zip(config.jobs, jobs, strict=True): wait_started = time.monotonic() deadline = wait_started + remaining_wait record.update(status="waiting", current_job=str(spec)) while True: query = subprocess.run( [ "nvidia-smi", f"--id={config.gpu}", "--query-gpu=memory.used,utilization.gpu", "--format=csv,noheader,nounits", ], capture_output=True, text=True, check=True, timeout=20, ) memory, utilization = [ int(x.strip()) for x in query.stdout.split(",") ] record.update( gpu_memory_mib=memory, gpu_utilization_pct=utilization, checked_epoch=time.time(), ) write() if memory <= config.free_memory_mib and utilization <= 10: break if time.monotonic() >= deadline: raise TimeoutError("Assigned GPU remained occupied") time.sleep(config.poll_s) if JobConfig.model_validate_json(spec.read_text()) != job: raise ValueError("Job specification changed while waiting") remaining_wait -= time.monotonic() - wait_started record.update(status="running") write() run_job(job) result = json.loads((job.output_dir / "result.json").read_text()) if result["status"] != "complete" or result["exit_code"] != 0: raise RuntimeError("Job did not complete successfully") record["completed_jobs"].append(str(spec)) signal.signal(signal.SIGTERM, interrupted) record.update(status="complete", ended_epoch=time.time()) except BaseException as error: current_result = ( jobs[len(record["completed_jobs"])].output_dir / "result.json" if len(record["completed_jobs"]) < len(jobs) else None ) child_interrupted = ( current_result is not None and current_result.exists() and json.loads(current_result.read_text()).get("status") == "interrupted" ) record.update( status="interrupted" if isinstance(error, KeyboardInterrupt) or child_interrupted else "failed", error=f"{type(error).__name__}: {error}", ended_epoch=time.time(), ) raise finally: write()
if __name__ == "__main__": cli = CliApp.run(SequenceCLIConfig) run(SequenceConfig.model_validate_json(cli.spec.read_text()))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879"""Exercise CUDA, physical stepping, and measured camera observations."""
import jsonfrom pathlib import Path
import gymnasium as gymimport imageio.v3 as iioimport mani_skill.envs # noqa: F401import torchfrom pydantic import BaseModel, ConfigDictfrom pydantic_settings import CliApp
class SmokeConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
output_dir: Path = Path("artifacts/smoke") """Directory for a rendered scene and the observed environment witness."""
device: str = "cuda:0" """CUDA device used for the seeded kernel witness."""
seed: int = 0 """Seed for both the kernel and environment reset."""
def run_smoke(config: SmokeConfig) -> dict: torch.manual_seed(config.seed) x = torch.randn(32, 32, device=config.device) witness = (x @ x.T).diagonal().sum().item() assert witness > 0 and torch.isfinite(x).all() env = gym.make( "StackCube-v1", obs_mode="pointcloud", control_mode="pd_ee_delta_pose", sim_backend="cpu", render_mode="rgb_array", robot_uids="panda", max_episode_steps=200, ) try: obs, _ = env.reset(seed=config.seed) cloud = obs["pointcloud"] valid = cloud["xyzw"][..., 3] > 0 assert valid.any() and torch.isfinite(cloud["xyzw"]).all() action = env.action_space.sample() * 0 _, _, _, _, info = env.step(action) frame = env.render() if hasattr(frame, "cpu"): frame = frame.cpu().numpy() if frame.ndim == 4: frame = frame[0] assert frame.ndim == 3 and frame.shape[-1] == 3 and frame.max() > 0 config.output_dir.mkdir(parents=True, exist_ok=True) iio.imwrite(config.output_dir / "stackcube.png", frame) result = { "status": "PASS", "scope": "CUDA, physical stepping, and rendering only; no learned policy", "gpu": torch.cuda.get_device_name(config.device), "torch": torch.__version__, "cuda": torch.version.cuda, "seed": config.seed, "kernel_witness": witness, "valid_depth_points": int(valid.sum()), "image_shape": list(frame.shape), "initial_step_success": info["success"].tolist(), "available_extra_keys": sorted(obs["extra"]), } (config.output_dir / "witness.json").write_text( json.dumps(result, indent=2) + "\n" ) print("ENV_WITNESS", json.dumps(result), flush=True) return result finally: env.close()
if __name__ == "__main__": run_smoke(CliApp.run(SmokeConfig))12345678910111213141516171819202122"""Tasks with an annotated native Panda motion-planning expert.
Each entry names the ManiSkill expert solution module and the actors whoseposes are logged during evaluation. All three tasks use panda_wristcam withthe same state25 (qpos9, qvel9, TCP7) and two-camera RGB layout."""
TASKS = { "StackCube-v1": ("stack_cube", ("cubeA", "cubeB")), "StackPyramid-v1": ("stack_pyramid", ("cubeA", "cubeB", "cubeC")), "PegInsertionSide-v1": ("peg_insertion_side", ("peg", "box")),}
def expert_module(env_id): import importlib
if env_id not in TASKS: raise ValueError(f"No annotated expert for {env_id}") return importlib.import_module( f"mani_skill.examples.motionplanning.panda.solutions.{TASKS[env_id][0]}" )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716"""Train pinned ACT on recorded demonstrations; run simulator evaluation separately.
The upstream Agent only reads observation/action shapes from its ``env`` argument.Here those shapes come from a recorded real environment witness. No environment,reset, step, reward, or success result is synthesized by this training entrypoint."""
import hashlibimport importlib.metadataimport jsonimport randomimport signalimport sysimport timefrom dataclasses import asdictfrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Literal
import numpy as npimport torchimport tyrofrom diffusers.training_utils import EMAModelfrom pydantic import BaseModel, ConfigDict, Field, PositiveInt, model_validatorfrom pydantic_settings import CliAppfrom torch.utils.data import BatchSampler, DataLoader, RandomSampler
from lim.act_optimization import ACTOptimizationConfig, ACTTrainingObjectivefrom lim.act_policy import ( ACTPolicyConfig, ChunkDatasetConfig, ChunkRelativeDataset, build_policy, policy_loss,)from lim.action_encoding import encode_dataset_actions, encoded_dimensionfrom lim.action_objective import validate_binary_gripperfrom lim.keypose_dense import ( DenseAuxiliaryDataset, DenseAuxiliaryDatasetConfig, primary_state_sha256,)from lim.keypose_policy import ( KeyposeDataset, KeyposeDatasetConfig, KeyposeSamplingConfig,)from lim.keypose_sequence import KeyposeSequenceDataset, KeyposeSequenceDatasetConfigfrom lim.keypose_stop import original_state_sha256from lim.normalization import ( FitNormalizationConfig, NormalizedDataset, NormalizedDatasetConfig, checked_statistics, fit_normalization,)from lim.reference_act import ( ACTION_DIMENSIONS, ReferenceConfig, load_official, source_provenance,)from lim.tasks import TASKSfrom lim.train_resume import ( VOLATILE_LEDGER_KEYS, StopRequest, TrainingParts, advance, capture, check_rebuild, check_replay, hold_workdir, load_snapshot, restore, resumable_ledger, same_metrics, save_snapshot, split_metrics,)
class FrozenNormalizationConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) training_ledger: Path """Completed training ledger owning the exact fitted normalization to reuse.""" sha256: str = Field(pattern=r"^[0-9a-f]{64}$") """Pinned ledger identity; its original population and horizon remain recorded."""
class OfflineTrainConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) workdir: Path """New training directory, separate from all prior attempts.""" official_arguments: list[str] """Native official Args, retained verbatim for recipe comparison.""" witness: Path """Recorded successful real RGB/environment/ACT witness supplying model shapes.""" witness_sha256: str = Field(pattern=r"^[0-9a-f]{64}$") """Pinned witness identity; shape descriptors are never guessed.""" optimization: ACTOptimizationConfig = ACTOptimizationConfig() """Training-only single-method intervention; control retains the native objective.""" policy: ACTPolicyConfig = ACTPolicyConfig() """Policy architecture/input intervention, shared with evaluation and profiling.""" sampler_seed: int | None = None """Optional private batch order RNG for matched new cohorts; None retains legacy order.""" keypose_sampling: KeyposeSamplingConfig = KeyposeSamplingConfig() """Training-only sample selection; does not alter the policy or inference ABI.""" frozen_normalization: FrozenNormalizationConfig | None = None """Reuse completed same-data statistics, e.g. Q30 scales for a Q1 comparison.""" precision: Literal["fp32", "fp16"] = "fp32" """Training arithmetic. fp16 adds CUDA autocast with dynamic loss scaling; parameters, optimizer, EMA, checkpoints and evaluation remain fp32.""" snapshot_every: PositiveInt | None = None """Updates between full training snapshots for exact resumption; SIGTERM also snapshots the current update. None keeps the single-attempt run unchanged."""
@model_validator(mode="after") def validate_keypose_sampling(self): if self.keypose_sampling.active and self.policy.keypose is None: raise ValueError("Keypose sample selection requires a keypose policy") if self.keypose_sampling.active and self.policy.keypose_context != "none": raise ValueError( "Completed-goal context screen preserves every original training observation" ) compact = ( self.policy.chunk_label_offset > 0 or self.policy.chunk_pose_supervision == "phase_segments" or self.policy.chunk_switch_head ) if compact and self.frozen_normalization is None: raise ValueError( "Compact endpoint outputs reuse completed Q30 statistics; never refit" ) queries = self.official_arguments declared = ( int(queries[queries.index("--num-queries") + 1]) if "--num-queries" in queries else 30 ) if (self.policy.chunk_pose_supervision == "phase_segments") != (declared == 2): raise ValueError("Phase segments use exactly two queries, and only they do") return self
def load_frozen_normalization(config: OfflineTrainConfig): """Validate reuse without refitting a different horizon's label population.""" frozen = config.frozen_normalization if frozen is None: raise ValueError("No frozen normalization source was declared") raw = frozen.training_ledger.read_bytes() if hashlib.sha256(raw).hexdigest() != frozen.sha256: raise ValueError("Frozen normalization training ledger identity mismatch") source = json.loads(raw) if source["status"] != "complete": raise ValueError("Frozen normalization requires completed source training") original = ACTPolicyConfig.model_validate(source["config"]["policy"]) # Pose supervision may intentionally differ, but encoded coordinates may not. # Other policy changes do not alter the affine transform's physical meaning. for field in ( "method", "action_encoding", "chunk_anchor", "chunk_normalization_population", "keypose", ): if getattr(original, field) != getattr(config.policy, field): raise ValueError(f"Frozen normalization representation differs: {field}") statistics = checked_statistics( source["normalization"], config.policy.normalization, config.policy.action_encoding, ) if statistics is None: raise ValueError("Frozen normalization source has no fitted statistics") args = config.official_arguments demo = Path(args[args.index("--demo-path") + 1]) count = int(args[args.index("--num-demos") + 1]) with demo.open("rb") as stream: source_sha = hashlib.file_digest(stream, "sha256").hexdigest() if statistics.source_sha256 != source_sha: raise ValueError("Frozen normalization demonstration identity mismatch") if statistics.trajectories != count or source["source_demonstrations"] != count: raise ValueError("Frozen normalization demonstration count differs") return statistics, { "mode": "frozen_completed_training", **frozen.model_dump(mode="json"), "source_num_queries": source["official_args"]["num_queries"], "source_samples": statistics.samples, "source_pose_supervision": original.chunk_pose_supervision, }
def optimizer_step(loss, optimizer, scaler): """One backward and update; False when fp16 loss scaling found inf/NaN gradients and skipped the update. A disabled scaler is exactly backward then step.""" optimizer.zero_grad() scaler.scale(loss).backward() scale = scaler.get_scale() scaler.step(optimizer) scaler.update() return scaler.get_scale() >= scale
class OfflineTrainCLI(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) spec: Path """JSON declaring the offline invocation and native recipe.""" resume: bool = False """Continue the unfinished run in the spec's workdir from its latest snapshot."""
def policy_spaces(config: OfflineTrainConfig): raw = config.witness.read_bytes() if hashlib.sha256(raw).hexdigest() != config.witness_sha256: raise ValueError("Real environment witness identity mismatch") witness = json.loads(raw) if witness["status"] != "PASS" or witness["robot"] != "panda_wristcam": raise ValueError("Expected a successful real panda_wristcam witness") state, rgb, actions = ( witness["state_shape"], witness["rgb_shape"], witness["action_shape"], ) control_mode = witness.get("control_mode", "pd_ee_delta_pos") encoding = witness.get("action_encoding", "controller") if ( state != [1, 25] or rgb != [1, 2, 3, 224, 224] or control_mode not in ACTION_DIMENSIONS or encoding != config.policy.action_encoding # The witness proves sensor and per-action dimensions. Its recorded # prediction horizon is not a physical environment dimension and need # not equal the new model's query count (e.g. a true single-target head). or len(actions) != 3 or actions[0] != 1 or not isinstance(actions[1], int) or isinstance(actions[1], bool) or actions[1] < 1 or actions[2] != encoded_dimension(ACTION_DIMENSIONS[control_mode], encoding) or witness.get("controller_action_shape", [1, ACTION_DIMENSIONS[control_mode]]) != [1, ACTION_DIMENSIONS[control_mode]] ): raise ValueError("Witness differs from the audited StackCube RGB contract") return SimpleNamespace( single_observation_space={ "state": SimpleNamespace(shape=tuple(state[1:])), "rgb": SimpleNamespace(shape=tuple(rgb[1:])), }, single_action_space=SimpleNamespace(shape=(ACTION_DIMENSIONS[control_mode],)), )
def run(config: OfflineTrainConfig, resume: bool = False): if resume and config.snapshot_every is None: raise ValueError("Only a run declared with snapshots can resume") reference = ReferenceConfig() provenance = source_provenance(reference) native = load_official(reference) args = tyro.cli(native.Args, args=config.official_arguments) native.args = args if ( args.env_id not in TASKS or args.control_mode not in ACTION_DIMENSIONS or args.sim_backend != "physx_cpu" or args.include_depth or args.num_queries not in (1, 2, 10, 20, 30, 50) or args.num_dataload_workers != 0 or args.num_eval_envs != 10 or not args.cuda or args.track or not args.exp_name or args.total_iters < 2 or args.num_demos is None or args.num_demos < 1 or args.save_freq != args.total_iters - 1 ): raise ValueError("Offline entrypoint supports only the declared RGB ACT recipe") if ( config.policy.method != "cvae" or config.policy.normalization.method != "none" or config.policy.state_input != "full" or config.policy.action_loss.method != "native" ) and config.optimization.method != "control": raise ValueError( "Screen policy interventions independently of training-only changes" ) if config.policy.method == "chunk_relative" and args.control_mode != ( "pd_ee_delta_pose" if config.policy.action_encoding == "rotation6d" else "pd_ee_delta_pos" ): raise ValueError( "Chunk-relative action encoding and physical source controller disagree" ) metadata = json.loads(Path(args.demo_path).with_suffix(".json").read_text()) demo_control = metadata["env_info"]["env_kwargs"].get( "control_mode", metadata["episodes"][0].get("control_mode") ) if demo_control != args.control_mode: raise ValueError("Demonstration control mode differs from the training recipe") spaces = policy_spaces(config) if spaces.single_action_space.shape != (ACTION_DIMENSIONS[args.control_mode],): raise ValueError("Witness and training control dimensions differ") config.workdir.mkdir(parents=True, exist_ok=True) ledger_path = config.workdir / "offline-training.json" # Kept open (and locked) until this process exits. lock = hold_workdir(config.workdir) if config.snapshot_every else None # noqa: F841 previous = None if resume: previous = resumable_ledger(ledger_path, config.model_dump(mode="json")) elif ledger_path.exists(): raise ValueError( "Offline training already launched; use a new attempt directory" ) ledger = { "status": "running", "started_epoch": time.time(), "config": config.model_dump(mode="json"), "official_args": asdict(args), "provenance": provenance, "entrypoint_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "evaluation": "disabled here; real simulator evaluation is a separate job", "success_metrics": None, "resume": resume, "software_versions": { "python": sys.version.split()[0], **{ name: importlib.metadata.version(name) for name in ( "torch", "torchvision", "numpy", "diffusers", "gymnasium", "mani-skill", ) }, }, } if previous is None: ledger_path.write_text(json.dumps(ledger, indent=2))
# Same ordering as the pinned native trainer, including both Agent instances. random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) torch.backends.cudnn.deterministic = args.torch_deterministic dataset = native.SmallDemoDataset_ACTPolicy( args.demo_path, args.num_queries, num_traj=args.num_demos, include_depth=args.include_depth, ) if config.policy.method == "chunk_relative": dataset = ChunkRelativeDataset( ChunkDatasetConfig( dataset=dataset, action_encoding=config.policy.action_encoding, source=Path(args.demo_path), chunk_anchor=config.policy.chunk_anchor, phase_supervision=config.policy.has_chunk_phase_head, chunk_pose_supervision=config.policy.chunk_pose_supervision, chunk_gripper_supervision=config.policy.chunk_gripper_supervision, chunk_padding=config.policy.chunk_padding, chunk_normalization_population=config.policy.chunk_normalization_population, chunk_label_offset=config.policy.chunk_label_offset, chunk_waypoint_threshold_m=config.policy.chunk_waypoint_threshold_m, switch_supervision=config.policy.chunk_switch_head, ) ) if config.policy.action_encoding == "rotation6d": ledger["action_target_contract"] = dataset.target_contract if hasattr(dataset, "supervision_audit"): ledger["supervision_audit"] = dataset.supervision_audit elif config.policy.keypose is not None: dataset = KeyposeDataset( KeyposeDatasetConfig( dataset=dataset, source=Path(args.demo_path), sampling=config.keypose_sampling, phase_supervision=config.policy.keypose_phase_weight > 0, context=config.policy.keypose_context, stop_supervision=config.policy.keypose_stop_head, ) ) (config.workdir / "sample-selection.json").write_text( json.dumps(dataset.sample_selection, indent=2) + "\n" ) ledger["sample_selection"] = { k: v for k, v in dataset.sample_selection.items() if k != "trajectories" } if config.policy.keypose_stop_head: ledger["stop_supervision"] = dataset.stop_label_summary if config.policy.keypose_target_sequence == "future": dataset = KeyposeSequenceDataset( KeyposeSequenceDatasetConfig(dataset=dataset) ) if config.policy.keypose_dense_head: dataset = DenseAuxiliaryDataset( DenseAuxiliaryDatasetConfig( dataset=dataset, source=Path(args.demo_path), normalization=config.policy.normalization, ) ) ledger["dense_aux_normalization"] = dataset.dense_statistics.model_dump( mode="json" ) else: dataset = encode_dataset_actions(dataset, config.policy.action_encoding) if config.policy.action_loss.method == "gripper_bce": validate_binary_gripper(dataset) if config.frozen_normalization is not None: normalization, ledger["normalization_source"] = load_frozen_normalization( config ) else: normalization = fit_normalization( FitNormalizationConfig( dataset=dataset, normalization=config.policy.normalization, action_encoding=config.policy.action_encoding, source=Path(args.demo_path), action_samples=dataset.normalization_actions if config.policy.method == "chunk_relative" and config.policy.action_encoding == "rotation6d" else None, ) ) if normalization is not None: (config.workdir / "normalization.json").write_text( normalization.model_dump_json(indent=2) + "\n" ) dataset = NormalizedDataset( NormalizedDatasetConfig( dataset=dataset, statistics=normalization, ) ) if dataset.num_traj != args.num_demos or len(dataset) < args.batch_size: raise ValueError("Incomplete demonstration count or no complete training batch") sample = dataset[0] if ( tuple(sample["observations"]["state"].shape) != spaces.single_observation_space["state"].shape or tuple(sample["observations"]["rgb"].shape) != spaces.single_observation_space["rgb"].shape or tuple(sample["actions"].shape) != ( args.num_queries, encoded_dimension( spaces.single_action_space.shape[-1], config.policy.action_encoding ), ) ): raise ValueError( "Real demonstration tensors disagree with the witnessed spaces" ) generator = None if config.sampler_seed is not None: generator = torch.Generator().manual_seed(config.sampler_seed) sampler = RandomSampler(dataset, replacement=False, generator=generator) batches = BatchSampler(sampler, batch_size=args.batch_size, drop_last=True) batches = native.IterationBasedBatchSampler(batches, args.total_iters) loader = DataLoader(dataset, batch_sampler=batches, num_workers=0) agent = build_policy(native, spaces, args, config.policy, normalization).cuda() parameter_groups = [ { "params": [ p for n, p in agent.named_parameters() if "backbone" not in n and p.requires_grad ] }, { "params": [ p for n, p in agent.named_parameters() if "backbone" in n and p.requires_grad ], "lr": args.lr_backbone, }, ] optimizer = torch.optim.AdamW(parameter_groups, lr=args.lr, weight_decay=1e-4) scheduler = torch.optim.lr_scheduler.StepLR( optimizer, int((2 / 3) * args.total_iters) ) ema = EMAModel(parameters=agent.parameters(), power=0.75) ema_agent = build_policy(native, spaces, args, config.policy, normalization).cuda() agent.train() objective = ACTTrainingObjective(config.optimization) checkpoint_dir = config.workdir / "runs" / args.exp_name / "checkpoints" checkpoint_dir.mkdir(parents=True, exist_ok=resume) initial_hash = hashlib.sha256() for name, tensor in agent.state_dict().items(): initial_hash.update(name.encode()) initial_hash.update(tensor.detach().cpu().contiguous().numpy().tobytes()) ledger.update( initial_state_sha256=initial_hash.hexdigest(), parameters=sum(p.numel() for p in agent.parameters()), source_demonstrations=dataset.num_traj, samples=len(dataset), gpu=torch.cuda.get_device_name(), normalization=normalization.model_dump(mode="json") if normalization else None, ) if config.policy.keypose_stop_head: ledger.update( initial_original_state_sha256=original_state_sha256(agent), initial_ema_original_state_sha256=original_state_sha256(ema_agent), initial_torch_rng_sha256=hashlib.sha256( torch.get_rng_state().numpy().tobytes() ).hexdigest(), ) if config.policy.keypose_dense_head: ledger["initial_primary_state_sha256"] = primary_state_sha256(agent) ledger["initial_ema_primary_state_sha256"] = primary_state_sha256(ema_agent) if previous is None: ledger_path.write_text(json.dumps(ledger, indent=2)) print("OFFLINE_TRAIN_START", json.dumps(ledger), flush=True) else: check_rebuild(previous, ledger) half = config.precision == "fp16" scaler = torch.amp.GradScaler("cuda", enabled=half) skipped = 0 parts = TrainingParts( agent=agent, optimizer=optimizer, scheduler=scheduler, ema=ema, scaler=scaler, sampler=generator, objective=objective, cuda=True, ) metrics_path = config.workdir / "metrics.jsonl" snapshot_dir = config.workdir / "resume" iterator = iter(loader) start, elapsed, replayed = 0, 0.0, {} if previous is not None: snapshot = load_snapshot(previous["resume_snapshot"]) start = snapshot["iteration"] + 1 advance(iterator, start) check_replay(parts, snapshot) restore(parts, snapshot) skipped, elapsed = snapshot["skipped"], snapshot["elapsed_s"] del snapshot resumes = previous.get("resumes", []) replayed = split_metrics(metrics_path, start) # Rebuilt values equal the stored ones but keep their Python types, so # records embedded in checkpoints pickle exactly as in the original run. rebuilt = {k: v for k, v in ledger.items() if k not in VOLATILE_LEDGER_KEYS} ledger = previous | rebuilt | { "status": "running", "resume": True, "resumes": resumes + [ { "from_updates": start, "snapshot_sha256": previous["resume_snapshot"]["sha256"], "started_epoch": time.time(), "replayed_metric_rows": len(replayed), "identical_metric_rows": 0, } ], } ledger_path.write_text(json.dumps(ledger, indent=2)) print("OFFLINE_TRAIN_RESUME", json.dumps(ledger["resumes"][-1]), flush=True) stop = StopRequest() if config.snapshot_every else None started = time.monotonic() - elapsed with metrics_path.open("a" if resume else "x") as metrics: for iteration, data in enumerate(iterator, start=start): obs = { k: v.cuda(non_blocking=True) for k, v in data["observations"].items() } actions = data["actions"].cuda(non_blocking=True) phase_labels = ( data["phase"].cuda(non_blocking=True) if "phase" in data else None ) stop_labels = ( data["stop_after_target"].cuda(non_blocking=True) if "stop_after_target" in data else None ) dense_labels = ( data["dense_actions"].cuda(non_blocking=True) if "dense_actions" in data else None ) switch_labels = ( data["switch"].cuda(non_blocking=True) if "switch" in data else None ) with torch.autocast("cuda", dtype=torch.float16, enabled=half): losses = policy_loss( agent, native, obs, actions, config.policy, objective, phase_labels, stop_labels, dense_labels, switch_labels, ) loss = losses["loss"] if not torch.isfinite(loss): raise FloatingPointError(f"Nonfinite training loss at {iteration}") skipped += not optimizer_step(loss, optimizer, scaler) if iteration == 0: # Gradients survive the step; the next zero_grad releases them. ledger["parameters_with_gradient"] = sum( p.numel() for p in agent.parameters() if p.grad is not None ) scheduler.step() ema.step(agent.parameters()) if iteration % args.log_freq == 0 or iteration == args.total_iters - 1: record = { "iteration": iteration, "updates": iteration + 1, "loss": loss.item(), **{ key: value.item() for key, value in losses.items() if key != "loss" }, "elapsed_s": time.monotonic() - started, "epoch": time.time(), "lr": optimizer.param_groups[0]["lr"], **( {"loss_scale": scaler.get_scale(), "skipped_updates": skipped} if half else {} ), } if iteration in replayed: ledger["resumes"][-1]["identical_metric_rows"] += same_metrics( record, replayed[iteration] ) metrics.write(json.dumps(record) + "\n") metrics.flush() print("OFFLINE_UPDATE", json.dumps(record), flush=True) if iteration % args.save_freq == 0: ema.copy_to(ema_agent.parameters()) torch.save( { "norm_stats": dataset.norm_stats, "agent": agent.state_dict(), "ema_agent": ema_agent.state_dict(), "policy": config.policy.model_dump(mode="json"), "num_queries": args.num_queries, "control_mode": args.control_mode, "normalization": normalization.model_dump(mode="json") if normalization else None, "normalization_source": ledger.get("normalization_source"), "training_sample_selection": ledger.get("sample_selection"), "action_target_contract": ledger.get("action_target_contract"), "supervision_audit": ledger.get("supervision_audit"), **( {"stop_supervision": ledger["stop_supervision"]} if config.policy.keypose_stop_head else {} ), **({"training_precision": "fp16"} if half else {}), **( { "dense_aux_normalization": ledger[ "dense_aux_normalization" ] } if config.policy.keypose_dense_head else {} ), }, checkpoint_dir / f"{iteration}.pt", ) if stop is None or iteration == args.total_iters - 1: continue stopping = stop.requested # Read once: a later signal waits one update. if stopping or (iteration + 1) % config.snapshot_every == 0: old = ledger.get("resume_snapshot") ledger["resume_snapshot"] = save_snapshot( snapshot_dir, capture(parts, iteration, skipped, time.monotonic() - started), ) ledger_path.write_text(json.dumps(ledger, indent=2)) if old is not None and old["path"] != ledger["resume_snapshot"]["path"]: Path(old["path"]).unlink() if stopping: ledger.update(status="interrupted", interrupted_epoch=time.time()) ledger_path.write_text(json.dumps(ledger, indent=2)) print("OFFLINE_TRAIN_INTERRUPTED", json.dumps(ledger["resume_snapshot"]), flush=True) raise SystemExit(128 + signal.SIGTERM) if iteration != args.total_iters - 1: raise RuntimeError("Native sampler did not complete the declared update budget") final = checkpoint_dir / f"{iteration}.pt" ledger.update( status="complete", ended_epoch=time.time(), updates=iteration + 1, final_checkpoint=str(final), final_checkpoint_sha256=hashlib.sha256(final.read_bytes()).hexdigest(), **({"skipped_updates": skipped} if half else {}), ) if "resume_snapshot" in ledger: # Only an unfinished run can use it; the record stays in the ledger. ledger["resume_snapshot"]["removed_at_completion"] = True ledger_path.write_text(json.dumps(ledger, indent=2)) if "resume_snapshot" in ledger: Path(ledger["resume_snapshot"]["path"]).unlink() print("OFFLINE_TRAIN_COMPLETE", json.dumps(ledger), flush=True)
if __name__ == "__main__": cli = CliApp.run(OfflineTrainCLI) run(OfflineTrainConfig.model_validate_json(cli.spec.read_text()), cli.resume)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219"""Exact resumption of offline ACT training from a full training snapshot.
A snapshot holds every state the update loop mutates: model, optimizer,scheduler, EMA, fp16 loss scaler, the skipped-update count and all RNG streams.The batch sampler's position lives in generator frames that cannot be saved, soa resume rebuilds the loader exactly as the original run did, replays only thebatch indices of the completed updates, checks that the replay landed where theoriginal stopped, and then restores the saved state. Capturing a snapshot readsbut never draws from any RNG, so continuous training is unchanged."""
import fcntlimport hashlibimport jsonimport randomimport signalfrom pathlib import Pathfrom typing import Any
import numpy as npimport torchfrom pydantic import BaseModel, ConfigDictfrom torch.utils.data.dataloader import _SingleProcessDataLoaderIter
SNAPSHOT_VERSION = 1VOLATILE_LEDGER_KEYS = ("status", "started_epoch", "resume")"""Ledger fields that legitimately differ between the original and resumed setup."""WALL_CLOCK_METRICS = ("elapsed_s", "epoch")
class TrainingParts(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) agent: torch.nn.Module optimizer: torch.optim.Optimizer scheduler: Any """Learning-rate scheduler with state_dict/load_state_dict.""" ema: Any """diffusers EMAModel tracking the agent parameters.""" scaler: torch.amp.GradScaler sampler: torch.Generator | None """Private batch-order generator; None for the legacy global-RNG order.""" objective: Any """Training objective; its lazily created private generator is saved too.""" cuda: bool """Save the CUDA RNG of the current device (dropout and CVAE noise)."""
def file_sha256(path): with Path(path).open("rb") as stream: return hashlib.file_digest(stream, "sha256").hexdigest()
def rng_state(parts: TrainingParts): generator = parts.objective.generator return { "python": random.getstate(), "numpy": np.random.get_state(), "torch": torch.get_rng_state(), "cuda": torch.cuda.get_rng_state() if parts.cuda else None, "sampler": None if parts.sampler is None else parts.sampler.get_state(), "objective": None if generator is None else {"device": str(generator.device), "state": generator.get_state()}, }
def set_rng_state(parts: TrainingParts, state): random.setstate(state["python"]) np.random.set_state(state["numpy"]) torch.set_rng_state(state["torch"]) if parts.cuda: torch.cuda.set_rng_state(state["cuda"]) if parts.sampler is not None: parts.sampler.set_state(state["sampler"]) if state["objective"] is not None: generator = torch.Generator(device=state["objective"]["device"]) generator.set_state(state["objective"]["state"]) parts.objective.generator = generator
def capture(parts: TrainingParts, iteration, skipped, elapsed_s): """State after update ``iteration``, before the loader fetches the next batch.""" return { "version": SNAPSHOT_VERSION, "iteration": iteration, "skipped": skipped, "elapsed_s": elapsed_s, "agent": parts.agent.state_dict(), "optimizer": parts.optimizer.state_dict(), "scheduler": parts.scheduler.state_dict(), "ema": parts.ema.state_dict(), "scaler": parts.scaler.state_dict(), "rng": rng_state(parts), }
def save_snapshot(directory: Path, state): """Atomic write; the returned record is what the ledger pins.""" directory.mkdir(exist_ok=True) updates = state["iteration"] + 1 path = directory / f"{updates}.pt" partial = path.with_suffix(".partial") torch.save(state, partial) partial.replace(path) return {"updates": updates, "path": str(path), "sha256": file_sha256(path)}
def load_snapshot(record): if file_sha256(record["path"]) != record["sha256"]: raise ValueError("Training snapshot identity differs from the ledger record") state = torch.load(record["path"], map_location="cpu", weights_only=False) if state["version"] != SNAPSHOT_VERSION or state["iteration"] + 1 != record["updates"]: raise ValueError("Training snapshot does not match its ledger record") return state
def advance(iterator, batches): """Consume the batch indices of completed updates without loading samples.""" if type(iterator) is not _SingleProcessDataLoaderIter: raise ValueError("Replay supports the single-process loader only") for _ in range(batches): iterator._next_index()
def check_replay(parts: TrainingParts, state): """The replayed batch order must stand exactly where the original run stopped.""" rng = state["rng"] if parts.sampler is not None: if not torch.equal(parts.sampler.get_state(), rng["sampler"]): raise ValueError("Replayed batch sampler differs from the snapshot") elif not torch.equal(torch.get_rng_state(), rng["torch"]): # Legacy order draws each epoch's seed from the global RNG; equal state # proves the loop drew from it nothing but those seeds. raise ValueError( "Legacy batch order shares the global RNG with the update loop; " "this run cannot be resumed exactly" )
def restore(parts: TrainingParts, state): parts.agent.load_state_dict(state["agent"]) parts.optimizer.load_state_dict(state["optimizer"]) parts.scheduler.load_state_dict(state["scheduler"]) parts.ema.load_state_dict(state["ema"]) parts.ema.to(device=next(parts.agent.parameters()).device) parts.scaler.load_state_dict(state["scaler"]) set_rng_state(parts, state["rng"])
class StopRequest: """SIGTERM asks the loop to snapshot the current update and exit."""
def __init__(self): self.requested = False signal.signal(signal.SIGTERM, self.request)
def request(self, signum, frame): self.requested = True
def hold_workdir(workdir: Path): """Exclusive for the process lifetime, so a resume cannot race a live attempt.""" lock = (workdir / "training.lock").open("a") try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: lock.close() raise ValueError("Another process is training in this directory") from None return lock
def resumable_ledger(path: Path, config): """The unfinished original ledger, if it may continue under ``config``.""" ledger = json.loads(path.read_text()) if ledger["status"] not in ("running", "interrupted"): raise ValueError("Only an unfinished training can resume") if ledger["config"] != config: raise ValueError("Resume requires the identical training specification") if "resume_snapshot" not in ledger: raise ValueError("No completed snapshot; launch a new attempt directory") return ledger
def check_rebuild(previous, fresh): """Every deterministic setup record must reproduce before state is restored.""" for key, value in fresh.items(): if key not in VOLATILE_LEDGER_KEYS and json.loads(json.dumps(value)) != previous.get(key): raise ValueError(f"Resumed setup differs from the original run: {key}")
def split_metrics(path: Path, updates): """Keep rows of completed updates; set aside rows the resume recomputes.
Every attempt's original file is preserved under the next free number. A final line cut off by a hard kill is dropped. """ lines = path.read_text().splitlines() rows = [] for number, line in enumerate(lines): try: rows.append((line, json.loads(line))) except json.JSONDecodeError: if number != len(lines) - 1: raise attempt = len(list(path.parent.glob("metrics-before-resume*.jsonl"))) path.rename(path.with_name(f"metrics-before-resume{attempt}.jsonl")) path.write_text("".join(line + "\n" for line, row in rows if row["iteration"] < updates)) return {row["iteration"]: row for _, row in rows if row["iteration"] >= updates}
def same_metrics(record, old): """Recomputed values equal the interrupted attempt's, wall clock aside."""
def strip(row): return {k: v for k, v in row.items() if k not in WALL_CLOCK_METRICS}
return strip(record) == strip(old)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283"""AWE-style waypoint selection on dense controller targets.
Shi et al. (CoRL 2023) choose the fewest waypoints such that linearinterpolation between consecutive waypoints stays within a distance thresholdof every intermediate state, by dynamic programming. Here the states are thedense controller target positions of one demonstration; gripper commandchanges are forced waypoints so no interpolated segment spans a gripper event."""
from itertools import pairwise
import numpy as np
def segment_error(points: np.ndarray, start: int, end: int) -> float: """Largest distance from points[start+1:end] to the segment start->end.""" if end - start < 2: return 0.0 a, b = points[start], points[end] inner = points[start + 1 : end] direction = b - a length = float(direction @ direction) if length == 0.0: return float(np.linalg.norm(inner - a, axis=1).max()) t = np.clip((inner - a) @ direction / length, 0.0, 1.0) return float(np.linalg.norm(inner - (a + t[:, None] * direction), axis=1).max())
def _piece(points, start, end, threshold): """Fewest waypoints in (start, end] covering points[start..end].""" cost = {start: 0} previous = {} for i in range(start + 1, end + 1): best = None for j in range(i - 1, start - 1, -1): if j not in cost or segment_error(points, j, i) > threshold: continue if best is None or cost[j] + 1 < best[0]: best = (cost[j] + 1, j) # Adjacent points are always a valid segment, so best exists. cost[i], previous[i] = best chosen, i = [], end while i != start: chosen.append(i) i = previous[i] return sorted(chosen)
def select_waypoints(positions, threshold: float, gripper=None) -> np.ndarray: """Waypoint indices into positions (n x d), always including n-1.
Index 0 is the start anchor, not a waypoint. Where the gripper command changes between i-1 and i, both i-1 and i are forced waypoints. """ points = np.asarray(positions, dtype=np.float64) if points.ndim != 2 or len(points) < 1 or not np.isfinite(points).all(): raise ValueError("Expected a finite n x d position array") if threshold <= 0: raise ValueError("Waypoint threshold must be positive") n = len(points) anchors = {0, n - 1} if gripper is not None: command = np.asarray(gripper) if command.shape != (n,): raise ValueError("Gripper commands must align with positions") for i in np.flatnonzero(command[1:] != command[:-1]) + 1: anchors.update((int(i) - 1, int(i))) anchors = sorted(anchors) if n == 1: return np.array([0], dtype=np.int64) chosen = set(anchors[1:]) for start, end in pairwise(anchors): chosen.update(_piece(points, start, end, threshold)) return np.array(sorted(chosen), dtype=np.int64)
def next_waypoint(length: int, waypoints) -> np.ndarray: """For each action time t, the first waypoint strictly after t (last maps to itself).""" points = np.asarray(waypoints, dtype=np.int64) if len(points) == 0 or points[-1] != length - 1 or np.any(np.diff(points) <= 0): raise ValueError("Waypoints must be increasing and end at the last action") index = np.searchsorted(points, np.arange(length), side="right") return points[np.minimum(index, len(points) - 1)]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192{ "mode": "evaluate", "source": "third_party/ManiSkill/examples/baselines/act/train_rgbd.py", "checkpoint": "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/runs/dense-q50-u90k-n100-s106/train/runs/fair-dense-q50-u90k-n100-s106/checkpoints/89999.pt", "output_dir": "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/runs/dense-q50-u90k-n100-s106/unused", "episodes": 60, "num_envs": 10, "seed_start": 54000, "observations": null, "iterations": 500, "demonstration_metadata": "/home/ghz/Work/Research/lim/artifacts/keypose-data/main/pose/trajectory.json", "architecture": { "hidden_dim": 256, "dim_feedforward": 512, "enc_layers": 2, "dec_layers": 4 }, "policy": { "method": "chunk_relative", "action_encoding": "rotation6d", "chunk_anchor": "chunk_start_tcp", "chunk_pose_supervision": "dense", "chunk_gripper_supervision": "future", "chunk_padding": "terminal", "chunk_normalization_population": "dense", "chunk_label_offset": 0, "chunk_waypoint_threshold_m": null, "chunk_switch_head": false, "chunk_switch_weight": 1.0, "flow_steps": 8, "inference_seed": 20260916, "normalization": { "method": "action_zscore", "state_floor": [ 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.001, 0.001, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.001, 0.001, 0.001, 0.001, 0.001, 0.01, 0.01, 0.01, 0.01 ], "action_floor": 0.01 }, "state_input": "full", "action_loss": { "method": "group_balanced", "position_axis_weights": [ 1.0, 1.0, 1.0 ] }, "keypose": null, "keypose_phase_weight": 0.0, "keypose_target_sequence": "current", "keypose_context": "none", "keypose_stop_head": false, "keypose_stop_weight": 0.1, "keypose_dense_head": false, "keypose_dense_weight": 1.0, "chunk_phase_head": true, "chunk_phase_weight": 0.0 }, "num_queries": 50, "video_seeds": [], "keypose_trace": false, "control_mode": "pd_ee_delta_pose", "gripper_execution": { "aggregation": "native", "binary": false, "trace": false }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120{ "workdir": "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/runs/dense-q50-u90k-n100-s106/train", "official_arguments": [ "--env-id", "StackCube-v1", "--no-include-depth", "--demo-path", "/home/ghz/Work/Research/lim/artifacts/keypose-data/main/pose/trajectory.h5", "--control-mode", "pd_ee_delta_pose", "--sim-backend", "physx_cpu", "--num-demos", "100", "--max-episode-steps", "200", "--total-iters", "90000", "--batch-size", "256", "--log-freq", "100", "--eval-freq", "90000", "--save-freq", "89999", "--num-eval-envs", "10", "--num-eval-episodes", "10", "--no-capture-video", "--exp-name", "fair-dense-q50-u90k-n100-s106", "--seed", "106", "--num-queries", "50" ], "witness": "/home/ghz/Work/Research/lim/artifacts/round5/witness-pose6d-local/result.json", "witness_sha256": "ebb2a1aab3175148531078878759ab081a55fc1838899b5fc4c36a54e0bbdfec", "optimization": { "method": "control", "shift_pixels": 4, "horizon_decay": 10.0, "augmentation_seed": 20260915 }, "policy": { "method": "chunk_relative", "action_encoding": "rotation6d", "chunk_anchor": "chunk_start_tcp", "chunk_pose_supervision": "dense", "chunk_gripper_supervision": "future", "chunk_padding": "terminal", "chunk_normalization_population": "dense", "chunk_label_offset": 0, "chunk_waypoint_threshold_m": null, "chunk_switch_head": false, "chunk_switch_weight": 1.0, "flow_steps": 8, "inference_seed": 20260916, "normalization": { "method": "action_zscore", "state_floor": [ 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.001, 0.001, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.001, 0.001, 0.001, 0.001, 0.001, 0.01, 0.01, 0.01, 0.01 ], "action_floor": 0.01 }, "state_input": "full", "action_loss": { "method": "group_balanced", "position_axis_weights": [ 1.0, 1.0, 1.0 ] }, "keypose": null, "keypose_phase_weight": 0.0, "keypose_target_sequence": "current", "keypose_context": "none", "keypose_stop_head": false, "keypose_stop_weight": 0.1, "keypose_dense_head": false, "keypose_dense_weight": 1.0, "chunk_phase_head": true, "chunk_phase_weight": 0.0 }, "sampler_seed": 106, "keypose_sampling": { "gripper_initial_only": false, "motion_endpoint_radius_m": 0.0 }, "frozen_normalization": null, "precision": "fp32", "snapshot_every": null}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119{ "config": { "method": "action_zscore", "state_floor": [ 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.001, 0.001, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.001, 0.001, 0.001, 0.001, 0.001, 0.01, 0.01, 0.01, 0.01 ], "action_floor": 0.01 }, "action_encoding": "rotation6d", "source_sha256": "308b8042624e38d90f6f2ff8514969b77f1957664a8a428f7193d2e0c39869c6", "trajectories": 100, "samples": 400550, "state": { "center": [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ], "scale": [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ] }, "action": { "center": [ -0.004949780361602022, 0.004639906655222552, -0.12922898915920078, -0.13325346216609632, 0.03898425036614412, -0.03896381559442273, -0.1325829996941852, 0.00260910681402844, 0.0023130242248227072, 0.0 ], "scale": [ 0.44801397774716467, 0.8087009447432236, 0.6006344842088875, 0.389626565324268, 1.5741173426631996, 1.5734545784924043, 0.38858051118501624, 0.1350035278051045, 0.06101708565776789, 1.0 ] }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343{ "status": "complete", "started_epoch": 1791303610.9474032, "config": { "workdir": "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/runs/dense-q50-u90k-n100-s106/train", "official_arguments": [ "--env-id", "StackCube-v1", "--no-include-depth", "--demo-path", "/home/ghz/Work/Research/lim/artifacts/keypose-data/main/pose/trajectory.h5", "--control-mode", "pd_ee_delta_pose", "--sim-backend", "physx_cpu", "--num-demos", "100", "--max-episode-steps", "200", "--total-iters", "90000", "--batch-size", "256", "--log-freq", "100", "--eval-freq", "90000", "--save-freq", "89999", "--num-eval-envs", "10", "--num-eval-episodes", "10", "--no-capture-video", "--exp-name", "fair-dense-q50-u90k-n100-s106", "--seed", "106", "--num-queries", "50" ], "witness": "/home/ghz/Work/Research/lim/artifacts/round5/witness-pose6d-local/result.json", "witness_sha256": "ebb2a1aab3175148531078878759ab081a55fc1838899b5fc4c36a54e0bbdfec", "optimization": { "method": "control", "shift_pixels": 4, "horizon_decay": 10.0, "augmentation_seed": 20260915 }, "policy": { "method": "chunk_relative", "action_encoding": "rotation6d", "chunk_anchor": "chunk_start_tcp", "chunk_pose_supervision": "dense", "chunk_gripper_supervision": "future", "chunk_padding": "terminal", "chunk_normalization_population": "dense", "chunk_label_offset": 0, "chunk_waypoint_threshold_m": null, "chunk_switch_head": false, "chunk_switch_weight": 1.0, "flow_steps": 8, "inference_seed": 20260916, "normalization": { "method": "action_zscore", "state_floor": [ 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.001, 0.001, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.001, 0.001, 0.001, 0.001, 0.001, 0.01, 0.01, 0.01, 0.01 ], "action_floor": 0.01 }, "state_input": "full", "action_loss": { "method": "group_balanced", "position_axis_weights": [ 1.0, 1.0, 1.0 ] }, "keypose": null, "keypose_phase_weight": 0.0, "keypose_target_sequence": "current", "keypose_context": "none", "keypose_stop_head": false, "keypose_stop_weight": 0.1, "keypose_dense_head": false, "keypose_dense_weight": 1.0, "chunk_phase_head": true, "chunk_phase_weight": 0.0 }, "sampler_seed": 106, "keypose_sampling": { "gripper_initial_only": false, "motion_endpoint_radius_m": 0.0 }, "frozen_normalization": null, "precision": "fp32", "snapshot_every": null }, "official_args": { "exp_name": "fair-dense-q50-u90k-n100-s106", "seed": 106, "torch_deterministic": true, "cuda": true, "track": false, "wandb_project_name": "ManiSkill", "wandb_entity": null, "capture_video": false, "env_id": "StackCube-v1", "demo_path": "/home/ghz/Work/Research/lim/artifacts/keypose-data/main/pose/trajectory.h5", "num_demos": 100, "total_iters": 90000, "batch_size": 256, "lr": 0.0001, "kl_weight": 10, "temporal_agg": true, "position_embedding": "sine", "backbone": "resnet18", "lr_backbone": 1e-05, "masks": false, "dilation": false, "include_depth": false, "enc_layers": 2, "dec_layers": 4, "dim_feedforward": 512, "hidden_dim": 256, "dropout": 0.1, "nheads": 8, "num_queries": 50, "pre_norm": false, "max_episode_steps": 200, "log_freq": 100, "eval_freq": 90000, "save_freq": 89999, "num_eval_episodes": 10, "num_eval_envs": 10, "sim_backend": "physx_cpu", "num_dataload_workers": 0, "control_mode": "pd_ee_delta_pose", "demo_type": null }, "provenance": { "official_source_sha256": { "third_party/ManiSkill/examples/baselines/act/act/detr/backbone.py": "2c890315cbf19567a4cf104d30da20daca3dcdb5ae5fc965c500674ae9707b12", "third_party/ManiSkill/examples/baselines/act/act/detr/detr_vae.py": "ed8b83c498172c486594c58f5e078dd4392de8983685ee87a99166825a468b37", "third_party/ManiSkill/examples/baselines/act/act/detr/position_encoding.py": "6461b7da106498df00f3e8db6edc7cd020ea86060861fc4983dba4fd163e6bf9", "third_party/ManiSkill/examples/baselines/act/act/detr/transformer.py": "5bc6700b6be400e7c974592ffc8a2b92d1f6f2cf4831198f7cb8f1de4a59bd4c", "third_party/ManiSkill/examples/baselines/act/act/evaluate.py": "dd0b733b3624d63d683918e64ccc217c019e3a5dddcc514a0f42628a1be87cbb", "third_party/ManiSkill/examples/baselines/act/act/make_env.py": "b588b119e86b9b23c08ef9f11a52294a168cbe0d3af4cac4b2c2eb2e26d196fe", "third_party/ManiSkill/examples/baselines/act/act/utils.py": "780c30ff8ac377f08e6b85e402ee0963eb0446ac120c2d3fa560789b948df900", "third_party/ManiSkill/examples/baselines/act/setup.py": "c5b1b1d8a1c4328c911a9caf2934c8ff4d5e01d7a1885645c2061eb7ae13df4b", "third_party/ManiSkill/examples/baselines/act/train.py": "de4b056adcd3c4ca1228d7e7c957a7b747550ef228f963d4cabae1e00e700346", "third_party/ManiSkill/examples/baselines/act/train_rgbd.py": "6ee91a2a7c853eae3b776ea7a4dbccf0cc94ec40ca41147d04b94ef389243654" }, "reference_commit": "a4a4f9272ad64b1564035874b605ceb687b63ed8" }, "entrypoint_sha256": "02d501edc65edb4bec51b3f6cd94a11c75536aa8a5382afcbdf33259b75ede2f", "evaluation": "disabled here; real simulator evaluation is a separate job", "success_metrics": null, "resume": false, "software_versions": { "python": "3.11.16", "torch": "2.5.1", "torchvision": "0.20.1", "numpy": "1.26.4", "diffusers": "0.32.2", "gymnasium": "0.29.1", "mani-skill": "3.0.1" }, "action_target_contract": { "version": "chunk_start_pose6d_v1", "position": "(world_command_target - observed_chunk_start_tcp) / 0.1", "rotation": "scaled6d(R_world_command_target @ R_chunk_start_tcp.T)", "gripper": "original continuous command, not a relative offset", "target_source": "each saved pre-action TCP composed with its own controller command", "padding": "terminal measured TCP pose and last gripper command", "normalization_population": "all valid anchor/future-target pairs, no terminal padding" }, "supervision_audit": { "pose_supervision": "dense", "gripper_supervision": "future", "samples": 10461, "normalization_samples": 400550, "sample_indices_sha256": "9b876226a5160a25f5ec9635d036d62fad97c63aac129eeab5aa502a6b040ae4", "pose_labels_sha256": "e89d8eefe620fe064c5d0b14baa03f859794a2276645a760c667253638a941b4", "gripper_labels_sha256": "5f2ac7286e101ce5f40d3195e7607e0b345ad5e88dd907b0aea4d318b5bdcdfa", "normalization_population_sha256": "bad4b0ba918457a00018da61f74a7c32afe9e0bac07ef19c1ad4837f8e56c6de", "phase_labels_sha256": "0e0985cfe1c3cf93a5068a9b6a7e7d31908cad23b92ac65c198edcf8277326d7" }, "initial_state_sha256": "ef7a20924fd444ec0fa30caeb2dda651b37a1f4b061be4416496fe5a61217a20", "parameters": 16629008, "source_demonstrations": 100, "samples": 10461, "gpu": "NVIDIA H200", "normalization": { "config": { "method": "action_zscore", "state_floor": [ 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.001, 0.001, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.001, 0.001, 0.001, 0.001, 0.001, 0.01, 0.01, 0.01, 0.01 ], "action_floor": 0.01 }, "action_encoding": "rotation6d", "source_sha256": "308b8042624e38d90f6f2ff8514969b77f1957664a8a428f7193d2e0c39869c6", "trajectories": 100, "samples": 400550, "state": { "center": [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ], "scale": [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ] }, "action": { "center": [ -0.004949780361602022, 0.004639906655222552, -0.12922898915920078, -0.13325346216609632, 0.03898425036614412, -0.03896381559442273, -0.1325829996941852, 0.00260910681402844, 0.0023130242248227072, 0.0 ], "scale": [ 0.44801397774716467, 0.8087009447432236, 0.6006344842088875, 0.389626565324268, 1.5741173426631996, 1.5734545784924043, 0.38858051118501624, 0.1350035278051045, 0.06101708565776789, 1.0 ] } }, "parameters_with_gradient": 16627466, "ended_epoch": 1791314224.616868, "updates": 90000, "final_checkpoint": "/home/ghz/Work/Research/lim/artifacts/fair-comparison/bext-v1/runs/dense-q50-u90k-n100-s106/train/runs/fair-dense-q50-u90k-n100-s106/checkpoints/89999.pt", "final_checkpoint_sha256": "a172b673b5cc28a47877fb9e53ed62d5c3fe768fb445954763d779cc2de98a88"}123version https://git-lfs.github.com/spec/v1oid sha256:a172b673b5cc28a47877fb9e53ed62d5c3fe768fb445954763d779cc2de98a88size 133454874123456789101112131415161718192021{ "status": "PASS", "mode": "training", "updates": 90000, "checkpoint_sha256": "a172b673b5cc28a47877fb9e53ed62d5c3fe768fb445954763d779cc2de98a88", "initial_state_sha256": "ef7a20924fd444ec0fa30caeb2dda651b37a1f4b061be4416496fe5a61217a20", "target_contract": "chunk_start_pose6d_v1", "final_loss": 0.013539742678403854, "reference": null, "frozen_normalization": null, "num_queries": 50, "demonstrations": 100, "samples": 10461, "seed": 106, "parameters": 16629008, "parameters_with_gradient": 16627466, "precision": "fp32", "skipped_updates": 0, "snapshot_every": null, "resumes": []}fair-comparison/bext-v1/CODE_SNAPSHOT.jsonAdded+283
fair-comparison/bext-v1/code/lim/__init__.pyAdded+1
fair-comparison/bext-v1/code/lim/act_optimization.pyAdded+81
fair-comparison/bext-v1/code/lim/act_policy.pyAdded+1123
fair-comparison/bext-v1/code/lim/action.pyAdded+77
fair-comparison/bext-v1/code/lim/action_encoding.pyAdded+120
fair-comparison/bext-v1/code/lim/action_objective.pyAdded+159
fair-comparison/bext-v1/code/lim/chunk_coordinates.pyAdded+236
fair-comparison/bext-v1/code/lim/chunk_endpoint.pyAdded+69
fair-comparison/bext-v1/code/lim/chunk_phase.pyAdded+32
fair-comparison/bext-v1/code/lim/chunk_switch.pyAdded+60
fair-comparison/bext-v1/code/lim/collect_keyposes.pyAdded+564
fair-comparison/bext-v1/code/lim/evaluate_phase_chunk.pyAdded+327
fair-comparison/bext-v1/code/lim/evaluate_planned_keypose.pyAdded+1210
fair-comparison/bext-v1/code/lim/gripper_execution.pyAdded+228
fair-comparison/bext-v1/code/lim/gripper_feedback.pyAdded+213
fair-comparison/bext-v1/code/lim/job.pyAdded+102
fair-comparison/bext-v1/code/lim/keypose_context.pyAdded+156
fair-comparison/bext-v1/code/lim/keypose_control.pyAdded+139
fair-comparison/bext-v1/code/lim/keypose_data.pyAdded+317
fair-comparison/bext-v1/code/lim/keypose_dense.pyAdded+135
fair-comparison/bext-v1/code/lim/keypose_diagnostics.pyAdded+205
fair-comparison/bext-v1/code/lim/keypose_oracle.pyAdded+191
fair-comparison/bext-v1/code/lim/keypose_phase.pyAdded+75
fair-comparison/bext-v1/code/lim/keypose_policy.pyAdded+260
fair-comparison/bext-v1/code/lim/keypose_sequence.pyAdded+46
fair-comparison/bext-v1/code/lim/keypose_stop.pyAdded+77
fair-comparison/bext-v1/code/lim/keypose_trace.pyAdded+71
fair-comparison/bext-v1/code/lim/normalization.pyAdded+263
fair-comparison/bext-v1/code/lim/observations.pyAdded+89
fair-comparison/bext-v1/code/lim/ood_env.pyAdded+94
fair-comparison/bext-v1/code/lim/planned_keypose.pyAdded+370
fair-comparison/bext-v1/code/lim/policy.pyAdded+52
fair-comparison/bext-v1/code/lim/policy_video.pyAdded+189
fair-comparison/bext-v1/code/lim/profile.pyAdded+122
fair-comparison/bext-v1/code/lim/reference_act.pyAdded+855
fair-comparison/bext-v1/code/lim/replay_pose.pyAdded+247
fair-comparison/bext-v1/code/lim/run_sequence.pyAdded+194
fair-comparison/bext-v1/code/lim/smoke.pyAdded+79
fair-comparison/bext-v1/code/lim/tasks.pyAdded+22
fair-comparison/bext-v1/code/lim/train_offline.pyAdded+716
fair-comparison/bext-v1/code/lim/train_resume.pyAdded+219
fair-comparison/bext-v1/code/lim/waypoints.pyAdded+83
fair-comparison/bext-v1/runs/dense-q50-u90k-n100-s106/reference.jsonAdded+92
fair-comparison/bext-v1/runs/dense-q50-u90k-n100-s106/train-spec.jsonAdded+120
fair-comparison/bext-v1/runs/dense-q50-u90k-n100-s106/train/metrics.jsonlAdded
fair-comparison/bext-v1/runs/dense-q50-u90k-n100-s106/train/normalization.jsonAdded+119
fair-comparison/bext-v1/runs/dense-q50-u90k-n100-s106/train/offline-training.jsonAdded+343
fair-comparison/bext-v1/runs/dense-q50-u90k-n100-s106/train/runs/fair-dense-q50-u90k-n100-s106/checkpoints/89999.ptAdded+3
fair-comparison/bext-v1/runs/dense-q50-u90k-n100-s106/train/verification.jsonAdded+21