Add fair-comparison/p3x-liftslow-v1
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- fair-comparison/p3x-liftslow-v1/CODE_SNAPSHOT.json +250 -0
- fair-comparison/p3x-liftslow-v1/code/lim/__init__.py +1 -0
- fair-comparison/p3x-liftslow-v1/code/lim/act_optimization.py +81 -0
- fair-comparison/p3x-liftslow-v1/code/lim/act_policy.py +1123 -0
- fair-comparison/p3x-liftslow-v1/code/lim/action.py +77 -0
- fair-comparison/p3x-liftslow-v1/code/lim/action_encoding.py +120 -0
- fair-comparison/p3x-liftslow-v1/code/lim/action_objective.py +159 -0
- fair-comparison/p3x-liftslow-v1/code/lim/chunk_coordinates.py +236 -0
- fair-comparison/p3x-liftslow-v1/code/lim/chunk_endpoint.py +69 -0
- fair-comparison/p3x-liftslow-v1/code/lim/chunk_phase.py +32 -0
- fair-comparison/p3x-liftslow-v1/code/lim/chunk_switch.py +60 -0
- fair-comparison/p3x-liftslow-v1/code/lim/collect_keyposes.py +592 -0
- fair-comparison/p3x-liftslow-v1/code/lim/evaluate_phase_chunk.py +327 -0
- fair-comparison/p3x-liftslow-v1/code/lim/evaluate_planned_keypose.py +1210 -0
- fair-comparison/p3x-liftslow-v1/code/lim/expert_stack_pyramid.py +129 -0
- fair-comparison/p3x-liftslow-v1/code/lim/expert_stack_pyramid_pick.py +133 -0
- fair-comparison/p3x-liftslow-v1/code/lim/gripper_execution.py +228 -0
- fair-comparison/p3x-liftslow-v1/code/lim/gripper_feedback.py +213 -0
- fair-comparison/p3x-liftslow-v1/code/lim/job.py +102 -0
- fair-comparison/p3x-liftslow-v1/code/lim/keypose_context.py +156 -0
- fair-comparison/p3x-liftslow-v1/code/lim/keypose_control.py +139 -0
- fair-comparison/p3x-liftslow-v1/code/lim/keypose_data.py +333 -0
- fair-comparison/p3x-liftslow-v1/code/lim/keypose_dense.py +135 -0
- fair-comparison/p3x-liftslow-v1/code/lim/keypose_diagnostics.py +205 -0
- fair-comparison/p3x-liftslow-v1/code/lim/keypose_oracle.py +191 -0
- fair-comparison/p3x-liftslow-v1/code/lim/keypose_phase.py +75 -0
- fair-comparison/p3x-liftslow-v1/code/lim/keypose_policy.py +260 -0
- fair-comparison/p3x-liftslow-v1/code/lim/keypose_sequence.py +46 -0
- fair-comparison/p3x-liftslow-v1/code/lim/keypose_stop.py +77 -0
- fair-comparison/p3x-liftslow-v1/code/lim/keypose_trace.py +71 -0
- fair-comparison/p3x-liftslow-v1/code/lim/lift_peg_env.py +19 -0
- fair-comparison/p3x-liftslow-v1/code/lim/normalization.py +263 -0
- fair-comparison/p3x-liftslow-v1/code/lim/observations.py +89 -0
- fair-comparison/p3x-liftslow-v1/code/lim/ood_env.py +94 -0
- fair-comparison/p3x-liftslow-v1/code/lim/planned_keypose.py +370 -0
- fair-comparison/p3x-liftslow-v1/code/lim/policy.py +52 -0
- fair-comparison/p3x-liftslow-v1/code/lim/policy_video.py +189 -0
- fair-comparison/p3x-liftslow-v1/code/lim/profile.py +122 -0
- fair-comparison/p3x-liftslow-v1/code/lim/reference_act.py +855 -0
- fair-comparison/p3x-liftslow-v1/code/lim/replay_pose.py +247 -0
- fair-comparison/p3x-liftslow-v1/code/lim/run_sequence.py +194 -0
- fair-comparison/p3x-liftslow-v1/code/lim/smoke.py +79 -0
- fair-comparison/p3x-liftslow-v1/code/lim/tasks.py +27 -0
- fair-comparison/p3x-liftslow-v1/code/lim/train_offline.py +716 -0
- fair-comparison/p3x-liftslow-v1/code/lim/train_resume.py +219 -0
- fair-comparison/p3x-liftslow-v1/code/lim/waypoints.py +83 -0
- fair-comparison/p3x-liftslow-v1/runs/dense-q50-u90k-n100_liftslow-s100/reference.json +92 -0
- fair-comparison/p3x-liftslow-v1/runs/dense-q50-u90k-n100_liftslow-s100/train-spec.json +120 -0
- fair-comparison/p3x-liftslow-v1/runs/dense-q50-u90k-n100_liftslow-s100/train/metrics.jsonl +0 -0
- fair-comparison/p3x-liftslow-v1/runs/dense-q50-u90k-n100_liftslow-s100/train/normalization.json +119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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"artifact": "/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1",
|
| 3 |
+
"files": {
|
| 4 |
+
"/home/ghz/Work/Research/lim/pixi.toml": "c4646961cd9519cb1ec640821b29b2a12a230a807db21b6e7914b5f59c7cb6e9",
|
| 5 |
+
"/home/ghz/Work/Research/lim/pixi.lock": "d99598c608997b2284003d1bfb3ac4dc25cd3c5436765b4728ee8e36500d19d8",
|
| 6 |
+
"/home/ghz/Work/Research/lim/round2/reference-source.json": "a73f863463cce7b3672dc8e8a1f012042579349cf1296af55b02520a5f34fbdc",
|
| 7 |
+
"/home/ghz/Work/Research/lim/experiments/keypose-mechanism/essence-h800/specs/fendpoint_fg-main-train.json": "5bc2a32c0592bd041c04da4557fcd84d980776e6ce43316e30f55a69215405eb",
|
| 8 |
+
"/home/ghz/Work/Research/lim/experiments/keypose-mechanism/essence-h800/specs/fendpoint_fg-main-eval.json": "1404828d20e9f10e26c9f7f32e2894428a3d282a159d46067459af194534cbcf",
|
| 9 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/witness/LiftPegUprightWristcam-v1/result.json": "37b2bc44653bcabd4d7c13e1ea695b0ba76618472411f87ed1840d6ac3684c22",
|
| 10 |
+
"/home/ghz/Work/Research/lim/artifacts/keypose-data/LiftPegUprightWristcam-slow/pose/trajectory.h5": "dfb7b1a424a12a219648e9f24cde45c3dcc099897ecad5171948317907f7c0d3",
|
| 11 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/caps/liftslow-n100.json": "02ff37ea3c9865ff30377df273dbf41d7a0dfddd7917034f6c47444e14fec86a",
|
| 12 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/__init__.py": "0cc163c61e6ea84e2d0707efb92d5a97f63007460dc3fab12583ee531a1fbf1d",
|
| 13 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/act_optimization.py": "45122bf568e42e20fcff5b39ed68c8e238a11dde07c413ae87078b7d6c554af8",
|
| 14 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/act_policy.py": "931e7fe53bbb93c93e5bc1fda0efe23293f2057feb16f0cd3e2cd0cc4945c3da",
|
| 15 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/action.py": "d787ae6e63b633b38db7d83182c607ce65d4720e0f4f2005a0ff3798ff476bf0",
|
| 16 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/action_encoding.py": "178cab172b0afc168bf015599775278240f2126d243c25e9be4a5a7650966a13",
|
| 17 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/action_objective.py": "8ed428059d407627d42978a136d5059de4ee686fe805d3edc372e6d628673a55",
|
| 18 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/chunk_coordinates.py": "9ae44c42103ba1e286cb4487c20b4df8b414ed28c450fca2493bcd5d47c8a8b0",
|
| 19 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/chunk_endpoint.py": "64a86d99276874fdc3be5d63e8abd4b5cf34308f9c77cc0ce859eb76ca802ba8",
|
| 20 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/chunk_phase.py": "7cdb66ed1fc09458f8c19119f20f4ce33287d88b9a7bd2d1a610938116494572",
|
| 21 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/chunk_switch.py": "72cd6201e69cbb21b065be5a58da8f7ffeccd1b671aa42c1944adba40513d5b9",
|
| 22 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/collect_keyposes.py": "82f8019a691cee5a402122b87762fd2a62af5358b060708d7f899da045e51686",
|
| 23 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/evaluate_phase_chunk.py": "f8d62d1f62a49415ab774210df2da7888952d9007d5d7a166e1bf227e94ba997",
|
| 24 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/evaluate_planned_keypose.py": "a38bc26b814adeb2d5e9108c83dfcdb999a45877018254c61abe68c8ad1da45e",
|
| 25 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/expert_stack_pyramid.py": "178a4fb07b2e9063215087c6a6cfc2056acf5bc18485253266b1cc9aa346f3ca",
|
| 26 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/expert_stack_pyramid_pick.py": "fe3b0679d448c3e8efaa7b161f10ea2ae7e9133b3bee5f10eded964ac9992a6c",
|
| 27 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/gripper_execution.py": "ea0f64a596c6695c8863d12a55a835d11bebd7080f0055a64919b54b4bc944c8",
|
| 28 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/gripper_feedback.py": "d61c8edca56f663bbc9a28c381b663efa800661afae26a14a0f127102ff077ac",
|
| 29 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/job.py": "66d337f158e7f88717fd4aba1cd83f730778c53e911aee26038a4d9969583729",
|
| 30 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/keypose_context.py": "c1d3e9e410b8743ac05791eb82d24e3557fd4de6c020c7614ef5ab28454a1a07",
|
| 31 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/keypose_control.py": "c976047a23a831a44e2b6056c3337483c892facc27976b70fcaebea5cb3d8730",
|
| 32 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/keypose_data.py": "5791fff2c56009b0a26a4269b24fa0879c4c1b34d69c0f399f17b0e32da80c5b",
|
| 33 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/keypose_dense.py": "2eaf0cfb30735491613a9431d58e75832196b9578dff611b9e8d74374a77f9cd",
|
| 34 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/keypose_diagnostics.py": "5e6fc13c3192970547c858cff8dc230b1573c8e06f2385cb537f2a850b4c2b23",
|
| 35 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/keypose_oracle.py": "4a0c5beded686c42289f9dac8b42633033f5d4028c77be659a6c615e6521963f",
|
| 36 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/keypose_phase.py": "5381954388521c9e45de1046a99be81fc6967268e9fa37cc7a492eef422e33c2",
|
| 37 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/keypose_policy.py": "f0dc4b64217f3014fc91416c2a4e3adebe37a4f598457488511cb630ff7fdbe8",
|
| 38 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/keypose_sequence.py": "7f3c8abb456c317bcf30ecd380bf4f2de18adbc90847a7ffc25398a48fd285bd",
|
| 39 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/keypose_stop.py": "9e2192abf01d0033250d1235a3fbaf90bd690375687bb18257e30d00631d575e",
|
| 40 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/keypose_trace.py": "fce7d06ace6db293a973c6c13529a7e0655996df814f0a4a6cc2dfb860dcd1a3",
|
| 41 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/lift_peg_env.py": "94a5c36cf95d4e45fcefad1ec7ce385fc28fe51c8984fa437aa933b794991edb",
|
| 42 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/normalization.py": "5fce9ca04e286f980b5d4f3e06f011b529cb70fb9080b1d2994637d13abe5083",
|
| 43 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/observations.py": "b83243c45bff96db3d653164fbe5c49801b07e6ba7ed6d394f6e18a1fd7dde1d",
|
| 44 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/ood_env.py": "5a2131cea9ca1da648919b3790fd214cca245be6016195561115d0597321513b",
|
| 45 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/planned_keypose.py": "bf5e177084c008619845c21d6a90a1ad3c1d6242ea89dea2134fa5ae2c924cec",
|
| 46 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/policy.py": "f440e9fc39bfe81d57b334e1f807a3c219253bc185fb141ef932de715d999b24",
|
| 47 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/policy_video.py": "88ab77abcc7d5c6b67bf110ab25f36aff88af6ea43e3bfc4284e980df109735d",
|
| 48 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/profile.py": "f51d6c88cad12794445d5342972fe76e7378300c77be9252c59a67444ae89e2d",
|
| 49 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/reference_act.py": "2be8bddc5c2e800e8b6d9dbb517f1b79fe903a19dca1f9c903b40f3059ec042e",
|
| 50 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/replay_pose.py": "e81ee3cfad6cc21286e2ff4505faae031040d68562e69ab784df611f93e24b9f",
|
| 51 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/run_sequence.py": "44a4b3c21590bf82e4dfd319f872b77a43a084e07dbf43a9e102163c6ade60ad",
|
| 52 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/smoke.py": "c41e00fa8a8290ab80a11996d3ceb6eb0e54c3e36172e59f90ae8f294c5315a1",
|
| 53 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/tasks.py": "40a5d3790131e8c2abe999b8cf144fe129800192c551f08d0945dd447e8f07f8",
|
| 54 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/train_offline.py": "02d501edc65edb4bec51b3f6cd94a11c75536aa8a5382afcbdf33259b75ede2f",
|
| 55 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/train_resume.py": "3fc973bce5c64415f326afdcd208a5731570c03f6fee326fa250ec36b0803ac2",
|
| 56 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/code/lim/waypoints.py": "c7a72725174850b2bcc631cc86740306adbfbdfae6bdec0e61b4f8d6b78aca99",
|
| 57 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/tools/check_executor_data.py": "60a61cacef810b79bb928e029a9f33842c7ef0e97d2417f63f7603e3ba2eab3f",
|
| 58 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/tools/check_factor.py": "3c3638c6a0bcae83fa57464e1af511e90c6fef9439a40df519b5e9342e7cc534",
|
| 59 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/tools/check_training.py": "3a14790143bb8773b4b1fb504c8b4f048777fc245c6703a3f71b0db58094770e",
|
| 60 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/tools/collect_executor.py": "aa50531d75a85672a6491a368f4977e7abd9e0a8c364f0fb8a7c301e02178b1b",
|
| 61 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/tools/collect_online.py": "ca5c35260c1e266d97930e51c093059db4ce755c39416cc63fe7c43d7b3b94c7",
|
| 62 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/tools/expert_ceiling.py": "1b7a40ba482b471dec4e9513b50bb0046a3606a4758271fb072db9150be316f6",
|
| 63 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/tools/factor_evaluate.py": "8ee8d1e7b21767b832b0da509214927cd23addb43d5b243e90a206aa0ea3f75b",
|
| 64 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/tools/job_queue.py": "f2eeec8471050d5e5fcef3ca6b92ac94684c7eb88298709ff2b4e44fbbc76836",
|
| 65 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/tools/merge_datasets.py": "2894c877be16f90b3d100216722d9d365ee986e365428d0185c0c4147edc6045",
|
| 66 |
+
"/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/tools/speed_cap.py": "62983f3f05db3736caad416ae70320cf2dbefa75c00ea2b3642a2c27f2dc6f30"
|
| 67 |
+
},
|
| 68 |
+
"jobs": 32,
|
| 69 |
+
"restart": "forbidden; failures keep their terminal ledger",
|
| 70 |
+
"stage": "p3x",
|
| 71 |
+
"selection": {
|
| 72 |
+
"rule": "PLAN.md \u00a71",
|
| 73 |
+
"base": {
|
| 74 |
+
"dense": {
|
| 75 |
+
"30000": {
|
| 76 |
+
"queries": 50,
|
| 77 |
+
"execution": "seq_n8_cap95",
|
| 78 |
+
"mean": 47.5
|
| 79 |
+
},
|
| 80 |
+
"90000": {
|
| 81 |
+
"queries": 50,
|
| 82 |
+
"execution": "seq_n8",
|
| 83 |
+
"mean": 49.5
|
| 84 |
+
}
|
| 85 |
+
},
|
| 86 |
+
"keypose": {
|
| 87 |
+
"30000": {
|
| 88 |
+
"queries": 50,
|
| 89 |
+
"execution": "seq_n8_cap95",
|
| 90 |
+
"mean": 47.0
|
| 91 |
+
},
|
| 92 |
+
"90000": {
|
| 93 |
+
"queries": 50,
|
| 94 |
+
"execution": "seq_n8_cap95",
|
| 95 |
+
"mean": 52.0
|
| 96 |
+
}
|
| 97 |
+
}
|
| 98 |
+
},
|
| 99 |
+
"best_updates": {
|
| 100 |
+
"dense": 90000,
|
| 101 |
+
"keypose": 90000
|
| 102 |
+
},
|
| 103 |
+
"shared_before_extension": 90000,
|
| 104 |
+
"extension_needed": true,
|
| 105 |
+
"extended": {
|
| 106 |
+
"dense": {
|
| 107 |
+
"queries": 50,
|
| 108 |
+
"execution": "seq_n8",
|
| 109 |
+
"mean": 49.5
|
| 110 |
+
},
|
| 111 |
+
"keypose": {
|
| 112 |
+
"queries": 50,
|
| 113 |
+
"execution": "seq_n8_cap95",
|
| 114 |
+
"mean": 50.0
|
| 115 |
+
}
|
| 116 |
+
},
|
| 117 |
+
"extension_gained": false,
|
| 118 |
+
"updates": 90000,
|
| 119 |
+
"dense": {
|
| 120 |
+
"queries": 50,
|
| 121 |
+
"execution": "seq_n8",
|
| 122 |
+
"mean": 49.5
|
| 123 |
+
},
|
| 124 |
+
"keypose": {
|
| 125 |
+
"queries": 50,
|
| 126 |
+
"execution": "seq_n8_cap95",
|
| 127 |
+
"mean": 52.0
|
| 128 |
+
}
|
| 129 |
+
},
|
| 130 |
+
"tags": [
|
| 131 |
+
"liftslow"
|
| 132 |
+
],
|
| 133 |
+
"horizons": {
|
| 134 |
+
"liftslow": 350
|
| 135 |
+
},
|
| 136 |
+
"runs": [
|
| 137 |
+
{
|
| 138 |
+
"mode": "dense",
|
| 139 |
+
"queries": 50,
|
| 140 |
+
"updates": 90000,
|
| 141 |
+
"seed": 100,
|
| 142 |
+
"dataset": "/home/ghz/Work/Research/lim/artifacts/keypose-data/LiftPegUprightWristcam-slow/pose/trajectory.h5",
|
| 143 |
+
"demos": 100,
|
| 144 |
+
"samples": null,
|
| 145 |
+
"data": "liftslow",
|
| 146 |
+
"env_id": "LiftPegUprightWristcam-v1",
|
| 147 |
+
"state_input": "full",
|
| 148 |
+
"witness": "/home/ghz/Work/Research/lim/artifacts/fair-comparison/witness/LiftPegUprightWristcam-v1/result.json",
|
| 149 |
+
"phase_head": false
|
| 150 |
+
},
|
| 151 |
+
{
|
| 152 |
+
"mode": "dense",
|
| 153 |
+
"queries": 50,
|
| 154 |
+
"updates": 90000,
|
| 155 |
+
"seed": 101,
|
| 156 |
+
"dataset": "/home/ghz/Work/Research/lim/artifacts/keypose-data/LiftPegUprightWristcam-slow/pose/trajectory.h5",
|
| 157 |
+
"demos": 100,
|
| 158 |
+
"samples": null,
|
| 159 |
+
"data": "liftslow",
|
| 160 |
+
"env_id": "LiftPegUprightWristcam-v1",
|
| 161 |
+
"state_input": "full",
|
| 162 |
+
"witness": "/home/ghz/Work/Research/lim/artifacts/fair-comparison/witness/LiftPegUprightWristcam-v1/result.json",
|
| 163 |
+
"phase_head": false
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"mode": "dense",
|
| 167 |
+
"queries": 50,
|
| 168 |
+
"updates": 90000,
|
| 169 |
+
"seed": 102,
|
| 170 |
+
"dataset": "/home/ghz/Work/Research/lim/artifacts/keypose-data/LiftPegUprightWristcam-slow/pose/trajectory.h5",
|
| 171 |
+
"demos": 100,
|
| 172 |
+
"samples": null,
|
| 173 |
+
"data": "liftslow",
|
| 174 |
+
"env_id": "LiftPegUprightWristcam-v1",
|
| 175 |
+
"state_input": "full",
|
| 176 |
+
"witness": "/home/ghz/Work/Research/lim/artifacts/fair-comparison/witness/LiftPegUprightWristcam-v1/result.json",
|
| 177 |
+
"phase_head": false
|
| 178 |
+
},
|
| 179 |
+
{
|
| 180 |
+
"mode": "dense",
|
| 181 |
+
"queries": 50,
|
| 182 |
+
"updates": 90000,
|
| 183 |
+
"seed": 103,
|
| 184 |
+
"dataset": "/home/ghz/Work/Research/lim/artifacts/keypose-data/LiftPegUprightWristcam-slow/pose/trajectory.h5",
|
| 185 |
+
"demos": 100,
|
| 186 |
+
"samples": null,
|
| 187 |
+
"data": "liftslow",
|
| 188 |
+
"env_id": "LiftPegUprightWristcam-v1",
|
| 189 |
+
"state_input": "full",
|
| 190 |
+
"witness": "/home/ghz/Work/Research/lim/artifacts/fair-comparison/witness/LiftPegUprightWristcam-v1/result.json",
|
| 191 |
+
"phase_head": false
|
| 192 |
+
},
|
| 193 |
+
{
|
| 194 |
+
"mode": "keypose",
|
| 195 |
+
"queries": 50,
|
| 196 |
+
"updates": 90000,
|
| 197 |
+
"seed": 100,
|
| 198 |
+
"dataset": "/home/ghz/Work/Research/lim/artifacts/keypose-data/LiftPegUprightWristcam-slow/pose/trajectory.h5",
|
| 199 |
+
"demos": 100,
|
| 200 |
+
"samples": null,
|
| 201 |
+
"data": "liftslow",
|
| 202 |
+
"env_id": "LiftPegUprightWristcam-v1",
|
| 203 |
+
"state_input": "full",
|
| 204 |
+
"witness": "/home/ghz/Work/Research/lim/artifacts/fair-comparison/witness/LiftPegUprightWristcam-v1/result.json",
|
| 205 |
+
"phase_head": false
|
| 206 |
+
},
|
| 207 |
+
{
|
| 208 |
+
"mode": "keypose",
|
| 209 |
+
"queries": 50,
|
| 210 |
+
"updates": 90000,
|
| 211 |
+
"seed": 101,
|
| 212 |
+
"dataset": "/home/ghz/Work/Research/lim/artifacts/keypose-data/LiftPegUprightWristcam-slow/pose/trajectory.h5",
|
| 213 |
+
"demos": 100,
|
| 214 |
+
"samples": null,
|
| 215 |
+
"data": "liftslow",
|
| 216 |
+
"env_id": "LiftPegUprightWristcam-v1",
|
| 217 |
+
"state_input": "full",
|
| 218 |
+
"witness": "/home/ghz/Work/Research/lim/artifacts/fair-comparison/witness/LiftPegUprightWristcam-v1/result.json",
|
| 219 |
+
"phase_head": false
|
| 220 |
+
},
|
| 221 |
+
{
|
| 222 |
+
"mode": "keypose",
|
| 223 |
+
"queries": 50,
|
| 224 |
+
"updates": 90000,
|
| 225 |
+
"seed": 102,
|
| 226 |
+
"dataset": "/home/ghz/Work/Research/lim/artifacts/keypose-data/LiftPegUprightWristcam-slow/pose/trajectory.h5",
|
| 227 |
+
"demos": 100,
|
| 228 |
+
"samples": null,
|
| 229 |
+
"data": "liftslow",
|
| 230 |
+
"env_id": "LiftPegUprightWristcam-v1",
|
| 231 |
+
"state_input": "full",
|
| 232 |
+
"witness": "/home/ghz/Work/Research/lim/artifacts/fair-comparison/witness/LiftPegUprightWristcam-v1/result.json",
|
| 233 |
+
"phase_head": false
|
| 234 |
+
},
|
| 235 |
+
{
|
| 236 |
+
"mode": "keypose",
|
| 237 |
+
"queries": 50,
|
| 238 |
+
"updates": 90000,
|
| 239 |
+
"seed": 103,
|
| 240 |
+
"dataset": "/home/ghz/Work/Research/lim/artifacts/keypose-data/LiftPegUprightWristcam-slow/pose/trajectory.h5",
|
| 241 |
+
"demos": 100,
|
| 242 |
+
"samples": null,
|
| 243 |
+
"data": "liftslow",
|
| 244 |
+
"env_id": "LiftPegUprightWristcam-v1",
|
| 245 |
+
"state_input": "full",
|
| 246 |
+
"witness": "/home/ghz/Work/Research/lim/artifacts/fair-comparison/witness/LiftPegUprightWristcam-v1/result.json",
|
| 247 |
+
"phase_head": false
|
| 248 |
+
}
|
| 249 |
+
]
|
| 250 |
+
}
|
fair-comparison/p3x-liftslow-v1/code/lim/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Compact manipulation policy experiments."""
|
fair-comparison/p3x-liftslow-v1/code/lim/act_optimization.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Isolated training-only ACT candidates; inference stays on the native path."""
|
| 2 |
+
|
| 3 |
+
from typing import Literal
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from pydantic import BaseModel, ConfigDict, NonNegativeInt, PositiveFloat
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class ACTOptimizationConfig(BaseModel, frozen=True):
|
| 11 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 12 |
+
method: Literal["control", "random_shift", "near_action", "deterministic"] = (
|
| 13 |
+
"control"
|
| 14 |
+
)
|
| 15 |
+
"""One isolated candidate; methods are not combined during screening."""
|
| 16 |
+
shift_pixels: NonNegativeInt = 4
|
| 17 |
+
"""Symmetric replicated-image padding before integer random cropping."""
|
| 18 |
+
horizon_decay: PositiveFloat = 10.0
|
| 19 |
+
"""Exponential L1 weighting time scale, in predicted actions."""
|
| 20 |
+
augmentation_seed: NonNegativeInt = 20260915
|
| 21 |
+
"""Private augmentation RNG, independent of sampling and native dropout/latent RNG."""
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def shift_rgb(rgb, pad, generator):
|
| 25 |
+
"""Translate each sample/camera equally across channels, without interpolation."""
|
| 26 |
+
if pad == 0:
|
| 27 |
+
return rgb
|
| 28 |
+
batch, cameras, channels, height, width = rgb.shape
|
| 29 |
+
flat = rgb.reshape(batch * cameras, channels, height, width)
|
| 30 |
+
padded = F.pad(flat, (pad, pad, pad, pad), mode="replicate")
|
| 31 |
+
shifts = torch.randint(
|
| 32 |
+
2 * pad + 1, (batch * cameras, 2), device=rgb.device, generator=generator
|
| 33 |
+
)
|
| 34 |
+
ys = (
|
| 35 |
+
torch.arange(height, device=rgb.device)[None, :, None]
|
| 36 |
+
+ shifts[:, 0, None, None]
|
| 37 |
+
)
|
| 38 |
+
xs = (
|
| 39 |
+
torch.arange(width, device=rgb.device)[None, None, :] + shifts[:, 1, None, None]
|
| 40 |
+
)
|
| 41 |
+
indices = torch.arange(batch * cameras, device=rgb.device)[:, None, None]
|
| 42 |
+
# NHWC indexing keeps all channels at the same spatial displacement.
|
| 43 |
+
return (
|
| 44 |
+
padded.permute(0, 2, 3, 1)[indices, ys, xs]
|
| 45 |
+
.permute(0, 3, 1, 2)
|
| 46 |
+
.reshape(batch, cameras, channels, height, width)
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class ACTTrainingObjective:
|
| 51 |
+
def __init__(self, config: ACTOptimizationConfig):
|
| 52 |
+
self.config = config
|
| 53 |
+
self.generator = None
|
| 54 |
+
|
| 55 |
+
def compute_loss(self, agent, native, obs, actions):
|
| 56 |
+
method = self.config.method
|
| 57 |
+
if method == "control":
|
| 58 |
+
return agent.compute_loss(obs=obs, action_seq=actions)
|
| 59 |
+
if method == "random_shift":
|
| 60 |
+
if self.generator is None:
|
| 61 |
+
self.generator = torch.Generator(device=obs["rgb"].device)
|
| 62 |
+
self.generator.manual_seed(self.config.augmentation_seed)
|
| 63 |
+
obs = dict(obs)
|
| 64 |
+
obs["rgb"] = shift_rgb(obs["rgb"], self.config.shift_pixels, self.generator)
|
| 65 |
+
return agent.compute_loss(obs=obs, action_seq=actions)
|
| 66 |
+
obs = dict(obs)
|
| 67 |
+
obs["rgb"] = agent.normalize(obs["rgb"].float() / 255.0)
|
| 68 |
+
if method == "deterministic":
|
| 69 |
+
prediction, _ = agent.model(obs) # Same zero latent used during deployment.
|
| 70 |
+
l1 = F.l1_loss(prediction, actions)
|
| 71 |
+
return {"loss": l1, "l1": l1, "kl": l1.new_zeros(())}
|
| 72 |
+
prediction, (mu, logvar) = agent.model(obs, actions)
|
| 73 |
+
error = F.l1_loss(prediction, actions, reduction="none")
|
| 74 |
+
weights = torch.exp(
|
| 75 |
+
-torch.arange(actions.shape[1], device=actions.device, dtype=error.dtype)
|
| 76 |
+
/ self.config.horizon_decay
|
| 77 |
+
)
|
| 78 |
+
weights = weights / weights.mean()
|
| 79 |
+
l1 = (error * weights[None, :, None]).mean()
|
| 80 |
+
kl = native.kl_divergence(mu, logvar)[0][0]
|
| 81 |
+
return {"loss": l1 + agent.kl_weight * kl, "l1": l1, "kl": kl}
|
fair-comparison/p3x-liftslow-v1/code/lim/act_policy.py
ADDED
|
@@ -0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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small ACT policy variants sharing the pinned visual and transformer components."""
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import math
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from types import SimpleNamespace
|
| 7 |
+
from typing import Any, Literal
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
from pydantic import (
|
| 13 |
+
BaseModel,
|
| 14 |
+
ConfigDict,
|
| 15 |
+
Field,
|
| 16 |
+
NonNegativeFloat,
|
| 17 |
+
NonNegativeInt,
|
| 18 |
+
PositiveFloat,
|
| 19 |
+
PositiveInt,
|
| 20 |
+
model_validator,
|
| 21 |
+
)
|
| 22 |
+
from torch import nn
|
| 23 |
+
from torch.utils.data import Dataset
|
| 24 |
+
|
| 25 |
+
from lim.action_encoding import (
|
| 26 |
+
ActionEncoding,
|
| 27 |
+
EncodedEnvConfig,
|
| 28 |
+
Rotation6DEnv,
|
| 29 |
+
encoded_dimension,
|
| 30 |
+
sixd_to_controller,
|
| 31 |
+
)
|
| 32 |
+
from lim.action_objective import (
|
| 33 |
+
ActionLossConfig,
|
| 34 |
+
BinaryGripperEnv,
|
| 35 |
+
BinaryGripperEnvConfig,
|
| 36 |
+
BinaryGripperModel,
|
| 37 |
+
BinaryGripperModelConfig,
|
| 38 |
+
pose_reconstruction,
|
| 39 |
+
)
|
| 40 |
+
from lim.chunk_coordinates import (
|
| 41 |
+
ChunkAnchor,
|
| 42 |
+
ChunkGripperSupervision,
|
| 43 |
+
ChunkPadding,
|
| 44 |
+
ChunkPoseSupervision,
|
| 45 |
+
chunk_relative_to_world,
|
| 46 |
+
controller_pose_targets,
|
| 47 |
+
pose_target_contract,
|
| 48 |
+
resolve_anchor,
|
| 49 |
+
world_to_chunk_relative,
|
| 50 |
+
)
|
| 51 |
+
from lim.keypose_context import (
|
| 52 |
+
KeyposeContextMode,
|
| 53 |
+
KeyposeContextModel,
|
| 54 |
+
KeyposeContextModelConfig,
|
| 55 |
+
)
|
| 56 |
+
from lim.keypose_control import (
|
| 57 |
+
KeyposeControlConfig,
|
| 58 |
+
KeyposeEnv,
|
| 59 |
+
KeyposeEnvConfig,
|
| 60 |
+
encode_keypose,
|
| 61 |
+
)
|
| 62 |
+
from lim.keypose_dense import (
|
| 63 |
+
DenseAuxiliaryHead,
|
| 64 |
+
DenseAuxiliaryHeadConfig,
|
| 65 |
+
read_dense_actions,
|
| 66 |
+
)
|
| 67 |
+
from lim.keypose_phase import (
|
| 68 |
+
KeyposePhaseHead,
|
| 69 |
+
KeyposePhaseHeadConfig,
|
| 70 |
+
read_phase_logits,
|
| 71 |
+
)
|
| 72 |
+
from lim.keypose_policy import FirstKeyposeAgent, FirstKeyposeAgentConfig
|
| 73 |
+
from lim.keypose_stop import KeyposeStopHead, KeyposeStopHeadConfig, read_stop_logits
|
| 74 |
+
from lim.chunk_switch import (
|
| 75 |
+
SWITCH_HORIZON,
|
| 76 |
+
ChunkSwitchHead,
|
| 77 |
+
ChunkSwitchHeadConfig,
|
| 78 |
+
read_switch_fraction,
|
| 79 |
+
)
|
| 80 |
+
from lim.normalization import (
|
| 81 |
+
NormalizationConfig,
|
| 82 |
+
NormalizedModel,
|
| 83 |
+
NormalizedModelConfig,
|
| 84 |
+
checked_statistics,
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class ACTPolicyConfig(BaseModel, frozen=True):
|
| 89 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 90 |
+
method: Literal["cvae", "state_free", "flow", "chunk_relative"] = "cvae"
|
| 91 |
+
"""One independent policy intervention; cvae preserves the native agent."""
|
| 92 |
+
action_encoding: ActionEncoding = "controller"
|
| 93 |
+
"""Rotation6D learns ten-dimensional labels and decodes only after ensembling."""
|
| 94 |
+
chunk_anchor: ChunkAnchor = "chunk_start_tcp"
|
| 95 |
+
"""Chunk label frame. Identity isolates the anchor: targets become absolute
|
| 96 |
+
world poses while the controller boundary still converts against real TCP."""
|
| 97 |
+
chunk_pose_supervision: ChunkPoseSupervision = "dense"
|
| 98 |
+
"""Replace only valid-slot pose labels; padding and dense normalization stay
|
| 99 |
+
shared. Endpoint inference needs no prefix."""
|
| 100 |
+
chunk_gripper_supervision: ChunkGripperSupervision = "future"
|
| 101 |
+
"""Future commands, or current command repeated in valid slots; independent of
|
| 102 |
+
pose and phase labels, with terminal padding and fitted scales preserved."""
|
| 103 |
+
chunk_padding: ChunkPadding = "terminal"
|
| 104 |
+
"""Out-of-range slots keep measured terminal targets, or repeat the current
|
| 105 |
+
complete endpoint target. Valid labels and normalization are unchanged."""
|
| 106 |
+
chunk_normalization_population: Literal["dense", "supervised"] = "dense"
|
| 107 |
+
"""Action statistics use dense valid pairs, or one complete current target per
|
| 108 |
+
observation for the repeated current-target recipe."""
|
| 109 |
+
chunk_label_offset: NonNegativeInt = 0
|
| 110 |
+
"""Slot i supervises time t+offset+i; zero preserves every existing recipe."""
|
| 111 |
+
chunk_waypoint_threshold_m: PositiveFloat | None = None
|
| 112 |
+
"""AWE distance threshold (metres) for future_waypoint labels; None otherwise."""
|
| 113 |
+
chunk_switch_head: bool = False
|
| 114 |
+
"""Regress the current phase's remaining steps from decoder query zero."""
|
| 115 |
+
chunk_switch_weight: NonNegativeFloat = Field(default=1.0, allow_inf_nan=False)
|
| 116 |
+
"""L1 weight on the remaining-steps fraction when the switch head exists."""
|
| 117 |
+
flow_steps: PositiveInt = 8
|
| 118 |
+
"""Euler evaluations per fresh observation for the conditional flow head."""
|
| 119 |
+
inference_seed: NonNegativeInt = 20260916
|
| 120 |
+
"""Private flow inference noise stream, independent of the training RNG."""
|
| 121 |
+
normalization: NormalizationConfig = NormalizationConfig()
|
| 122 |
+
"""Independent training-fitted scaling; none preserves existing policies."""
|
| 123 |
+
state_input: Literal["full", "no_velocity", "tcp_only", "no_state"] = "full"
|
| 124 |
+
"""State25 information subset, masked in both CVAE branches with capacity fixed;
|
| 125 |
+
no_state masks all 25 values, leaving the images as the only observation."""
|
| 126 |
+
action_loss: ActionLossConfig = ActionLossConfig()
|
| 127 |
+
"""Action objective and linked inference semantics, persisted with the policy."""
|
| 128 |
+
keypose: KeyposeControlConfig | None = None
|
| 129 |
+
"""When set, learn next world keypose on all queries; execute the first at 20Hz."""
|
| 130 |
+
keypose_phase_weight: NonNegativeFloat = Field(default=0.0, allow_inf_nan=False)
|
| 131 |
+
"""Weight on six-class primitive CE from query-zero features; zero preserves
|
| 132 |
+
the native action-only model. Labels are supervision only, never inputs."""
|
| 133 |
+
keypose_target_sequence: Literal["current", "future"] = "current"
|
| 134 |
+
"""Repeat the current primitive goal, or supervise each future time's goal;
|
| 135 |
+
both variants still execute query zero with the same keypose controller."""
|
| 136 |
+
keypose_context: KeyposeContextMode = "none"
|
| 137 |
+
"""Optional completed-target11 input shared by prior and posterior state
|
| 138 |
+
projections; zero and previous_target have identical trainable structure."""
|
| 139 |
+
keypose_stop_head: bool = False
|
| 140 |
+
"""Add independent terminal-intent logits from decoder query zero."""
|
| 141 |
+
keypose_stop_weight: NonNegativeFloat = Field(default=0.1, allow_inf_nan=False)
|
| 142 |
+
"""BCE weight when the stop head exists; zero retains the same head for controls."""
|
| 143 |
+
keypose_dense_head: bool = False
|
| 144 |
+
"""Add a dense30 auxiliary decoder projection; never executed at inference."""
|
| 145 |
+
keypose_dense_weight: NonNegativeFloat = Field(default=1.0, allow_inf_nan=False)
|
| 146 |
+
"""Dense group-balanced reconstruction weight; zero is the matched head control."""
|
| 147 |
+
chunk_phase_head: bool = False
|
| 148 |
+
"""Retain the per-query phase head even when its auxiliary loss is zero."""
|
| 149 |
+
chunk_phase_weight: NonNegativeFloat = Field(default=0.0, allow_inf_nan=False)
|
| 150 |
+
"""Per-query phase CE weight. Positive values also enable the head, preserving
|
| 151 |
+
the architecture of existing checkpoints with no explicit head field."""
|
| 152 |
+
|
| 153 |
+
@property
|
| 154 |
+
def has_chunk_phase_head(self):
|
| 155 |
+
"""Whether model construction and diagnostic labels include a phase head."""
|
| 156 |
+
return self.chunk_phase_head or self.chunk_phase_weight > 0
|
| 157 |
+
|
| 158 |
+
@model_validator(mode="after")
|
| 159 |
+
def check_normalization(self):
|
| 160 |
+
compact = (
|
| 161 |
+
self.chunk_label_offset > 0
|
| 162 |
+
or self.chunk_pose_supervision == "phase_segments"
|
| 163 |
+
or self.chunk_switch_head
|
| 164 |
+
)
|
| 165 |
+
# A Q30 future-endpoint switch arm keeps its template's zero-weight phase
|
| 166 |
+
# head, so it differs from that template only by the switch head.
|
| 167 |
+
phase_head_allowed = (
|
| 168 |
+
self.chunk_pose_supervision == "future_endpoint"
|
| 169 |
+
and not self.chunk_label_offset
|
| 170 |
+
and self.chunk_phase_weight == 0
|
| 171 |
+
)
|
| 172 |
+
if compact and (
|
| 173 |
+
self.method != "chunk_relative"
|
| 174 |
+
or self.action_encoding != "rotation6d"
|
| 175 |
+
or self.chunk_anchor != "chunk_start_tcp"
|
| 176 |
+
or self.chunk_gripper_supervision != "future"
|
| 177 |
+
or self.chunk_padding != "terminal"
|
| 178 |
+
or self.chunk_normalization_population != "dense"
|
| 179 |
+
or (self.has_chunk_phase_head and not phase_head_allowed)
|
| 180 |
+
):
|
| 181 |
+
raise ValueError(
|
| 182 |
+
"Compact endpoint outputs use TCP-anchored pose6D, own gripper labels, no phase head"
|
| 183 |
+
)
|
| 184 |
+
if self.chunk_label_offset > 0 and self.chunk_pose_supervision != "future_endpoint":
|
| 185 |
+
raise ValueError("Lookahead labels shift future-time endpoint supervision only")
|
| 186 |
+
if (self.chunk_pose_supervision == "future_waypoint") != (
|
| 187 |
+
self.chunk_waypoint_threshold_m is not None
|
| 188 |
+
):
|
| 189 |
+
raise ValueError("Exactly the waypoint supervision carries a waypoint threshold")
|
| 190 |
+
if self.chunk_pose_supervision == "phase_segments" and not self.chunk_switch_head:
|
| 191 |
+
raise ValueError("Phase segments always carry the switch head (weight may be zero)")
|
| 192 |
+
if self.chunk_switch_head and (
|
| 193 |
+
self.chunk_pose_supervision not in ("phase_segments", "future_endpoint")
|
| 194 |
+
or self.chunk_label_offset
|
| 195 |
+
):
|
| 196 |
+
raise ValueError("The switch head supervises unshifted endpoint recipes only")
|
| 197 |
+
if self.chunk_pose_supervision == "phase_segments" and self.chunk_label_offset:
|
| 198 |
+
raise ValueError("Phase segments are indexed by phase, not by time offset")
|
| 199 |
+
if self.chunk_padding == "current_target" and (
|
| 200 |
+
self.chunk_pose_supervision != "current_endpoint"
|
| 201 |
+
or self.chunk_gripper_supervision != "current"
|
| 202 |
+
):
|
| 203 |
+
raise ValueError(
|
| 204 |
+
"Current-target padding requires current endpoint and gripper"
|
| 205 |
+
)
|
| 206 |
+
if self.chunk_gripper_supervision != "future" and (
|
| 207 |
+
self.method != "chunk_relative" or self.action_encoding != "rotation6d"
|
| 208 |
+
):
|
| 209 |
+
raise ValueError("Chunk gripper supervision requires chunk-relative pose6D")
|
| 210 |
+
if self.chunk_pose_supervision != "dense" and (
|
| 211 |
+
self.method != "chunk_relative"
|
| 212 |
+
or self.action_encoding != "rotation6d"
|
| 213 |
+
):
|
| 214 |
+
raise ValueError(
|
| 215 |
+
"Matched endpoint supervision requires pose6D chunk-relative targets"
|
| 216 |
+
)
|
| 217 |
+
if self.has_chunk_phase_head and (
|
| 218 |
+
self.method != "chunk_relative"
|
| 219 |
+
or self.action_encoding != "rotation6d"
|
| 220 |
+
):
|
| 221 |
+
raise ValueError(
|
| 222 |
+
"Chunk phase supervision requires fixed-anchor pose6D targets"
|
| 223 |
+
)
|
| 224 |
+
if self.chunk_normalization_population == "supervised" and (
|
| 225 |
+
self.chunk_pose_supervision != "current_endpoint"
|
| 226 |
+
or self.chunk_gripper_supervision != "current"
|
| 227 |
+
or self.chunk_padding != "current_target"
|
| 228 |
+
):
|
| 229 |
+
raise ValueError(
|
| 230 |
+
"Supervised normalization requires repeated complete current-target endpoint labels"
|
| 231 |
+
)
|
| 232 |
+
if self.keypose_dense_head and not self.keypose_stop_head:
|
| 233 |
+
raise ValueError(
|
| 234 |
+
"Dense auxiliary screen requires the existing stop/context policy"
|
| 235 |
+
)
|
| 236 |
+
if self.keypose_stop_head and (
|
| 237 |
+
self.keypose is None
|
| 238 |
+
or self.method != "cvae"
|
| 239 |
+
or self.state_input != "full"
|
| 240 |
+
or self.keypose_target_sequence != "current"
|
| 241 |
+
or self.keypose_context != "previous_target"
|
| 242 |
+
or self.keypose_phase_weight != 0
|
| 243 |
+
):
|
| 244 |
+
raise ValueError(
|
| 245 |
+
"Stop supervision requires current previous-target full-state CVAE keypose without phase"
|
| 246 |
+
)
|
| 247 |
+
if self.keypose_context != "none" and (
|
| 248 |
+
self.keypose is None
|
| 249 |
+
or self.method != "cvae"
|
| 250 |
+
or self.state_input != "full"
|
| 251 |
+
or self.keypose_target_sequence != "current"
|
| 252 |
+
or self.keypose_phase_weight != 0
|
| 253 |
+
):
|
| 254 |
+
raise ValueError(
|
| 255 |
+
"Completed-goal context requires current full-state CVAE keypose without a phase head"
|
| 256 |
+
)
|
| 257 |
+
if self.keypose_target_sequence == "future" and self.keypose is None:
|
| 258 |
+
raise ValueError("Future keypose supervision requires a keypose policy")
|
| 259 |
+
if self.keypose_phase_weight > 0 and self.keypose is None:
|
| 260 |
+
raise ValueError("Phase classification requires a keypose policy")
|
| 261 |
+
if self.chunk_anchor != "chunk_start_tcp" and (
|
| 262 |
+
self.method != "chunk_relative" or self.action_encoding != "rotation6d"
|
| 263 |
+
):
|
| 264 |
+
raise ValueError(
|
| 265 |
+
"Absolute chunk anchors are only defined for pose6D chunk_relative"
|
| 266 |
+
)
|
| 267 |
+
if (
|
| 268 |
+
self.method == "chunk_relative"
|
| 269 |
+
and self.action_encoding == "controller"
|
| 270 |
+
and self.normalization.method != "none"
|
| 271 |
+
):
|
| 272 |
+
raise ValueError(
|
| 273 |
+
"Position-only chunk-relative checkpoints retain their original unnormalized contract"
|
| 274 |
+
)
|
| 275 |
+
if self.keypose is not None and (
|
| 276 |
+
self.method != "cvae"
|
| 277 |
+
or self.action_encoding != "rotation6d"
|
| 278 |
+
or self.state_input != "full"
|
| 279 |
+
or self.action_loss.method != "group_balanced"
|
| 280 |
+
or self.normalization.method != "action_zscore"
|
| 281 |
+
):
|
| 282 |
+
raise ValueError(
|
| 283 |
+
"Keypose screen requires full-state CVAE, rotation6d, group-balanced action-zscore"
|
| 284 |
+
)
|
| 285 |
+
if self.normalization.method != "none" and self.method not in (
|
| 286 |
+
"cvae",
|
| 287 |
+
"chunk_relative",
|
| 288 |
+
):
|
| 289 |
+
raise ValueError(
|
| 290 |
+
"Screen normalization on the native state-conditioned CVAE"
|
| 291 |
+
)
|
| 292 |
+
if self.state_input != "full" and self.method not in ("cvae", "chunk_relative"):
|
| 293 |
+
raise ValueError("State subsets are screened on the CVAE policies")
|
| 294 |
+
if self.action_loss.method != "native" and (
|
| 295 |
+
self.method not in ("cvae", "chunk_relative")
|
| 296 |
+
or self.action_encoding != "rotation6d"
|
| 297 |
+
or (self.state_input != "full" and self.method != "chunk_relative")
|
| 298 |
+
):
|
| 299 |
+
raise ValueError("Screen pose action losses on full-state Rotation6D CVAE")
|
| 300 |
+
if (
|
| 301 |
+
self.method == "chunk_relative"
|
| 302 |
+
and self.action_encoding == "rotation6d"
|
| 303 |
+
and (
|
| 304 |
+
self.keypose is not None
|
| 305 |
+
or self.normalization.method != "action_zscore"
|
| 306 |
+
or self.action_loss.method != "group_balanced"
|
| 307 |
+
)
|
| 308 |
+
):
|
| 309 |
+
raise ValueError(
|
| 310 |
+
"Pose chunk-relative screen requires full-state/group-balanced/action-zscore"
|
| 311 |
+
)
|
| 312 |
+
return self
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
class ModelBuildConfig(BaseModel, frozen=True):
|
| 316 |
+
model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid")
|
| 317 |
+
native_model: Any
|
| 318 |
+
"""Newly initialized pinned DETRVAE; selected modules are reused unchanged."""
|
| 319 |
+
policy: ACTPolicyConfig
|
| 320 |
+
"""Validated policy variant and sampler configuration."""
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
class StateFreeModel(nn.Module):
|
| 324 |
+
"""Constant state tokens preserve capacity but carry no proprioceptive signal."""
|
| 325 |
+
|
| 326 |
+
def __init__(self, config: ModelBuildConfig):
|
| 327 |
+
super().__init__()
|
| 328 |
+
self.base = config.native_model
|
| 329 |
+
self.state_dim = self.base.input_proj_robot_state.in_features
|
| 330 |
+
|
| 331 |
+
def forward(self, obs, actions=None):
|
| 332 |
+
# Both the posterior and action decoder see constants, including training.
|
| 333 |
+
# The original state values are never read; images determine batch/device.
|
| 334 |
+
state = torch.zeros(
|
| 335 |
+
obs["rgb"].shape[0],
|
| 336 |
+
self.state_dim,
|
| 337 |
+
device=obs["rgb"].device,
|
| 338 |
+
dtype=obs["rgb"].dtype,
|
| 339 |
+
)
|
| 340 |
+
return self.base({"rgb": obs["rgb"], "state": state}, actions)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
class StateSubsetModel(nn.Module):
|
| 344 |
+
"""Remove selected state information without changing initialization or width."""
|
| 345 |
+
|
| 346 |
+
def __init__(self, config: ModelBuildConfig):
|
| 347 |
+
super().__init__()
|
| 348 |
+
self.config = config
|
| 349 |
+
self.base = config.native_model
|
| 350 |
+
if self.base.input_proj_robot_state.in_features != 25:
|
| 351 |
+
raise ValueError(
|
| 352 |
+
"State subsets require qpos9, qvel9, TCP position3/quaternion4"
|
| 353 |
+
)
|
| 354 |
+
keep = torch.zeros(25, dtype=torch.bool)
|
| 355 |
+
if config.policy.state_input == "no_velocity":
|
| 356 |
+
keep[:9] = True
|
| 357 |
+
keep[18:] = True
|
| 358 |
+
elif config.policy.state_input == "tcp_only":
|
| 359 |
+
keep[18:] = True
|
| 360 |
+
elif config.policy.state_input != "no_state":
|
| 361 |
+
raise ValueError("Full-state control must use the unwrapped native model")
|
| 362 |
+
self.register_buffer("keep_state", keep, persistent=False)
|
| 363 |
+
|
| 364 |
+
def forward(self, obs, actions=None):
|
| 365 |
+
# Applied after optional per-axis normalization, before posterior/decoder.
|
| 366 |
+
# masked_fill also prevents discarded NaNs from reaching either branch.
|
| 367 |
+
state = obs["state"].masked_fill(~self.keep_state, 0)
|
| 368 |
+
return self.base({**obs, "state": state}, actions)
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
class FlowACT(nn.Module):
|
| 372 |
+
"""Conditional linear-path flow: Gaussian noise -> normalized action chunks.
|
| 373 |
+
|
| 374 |
+
Observation memory is encoded once per fresh observation. Only the action
|
| 375 |
+
decoder is iterated, with noisy actions and continuous time as inputs.
|
| 376 |
+
"""
|
| 377 |
+
|
| 378 |
+
def __init__(self, config: ModelBuildConfig):
|
| 379 |
+
super().__init__()
|
| 380 |
+
native = config.native_model
|
| 381 |
+
self.config = config.policy
|
| 382 |
+
self.backbones = native.backbones
|
| 383 |
+
self.input_proj = native.input_proj
|
| 384 |
+
self.input_proj_robot_state = native.input_proj_robot_state
|
| 385 |
+
self.transformer = native.transformer
|
| 386 |
+
self.query_embed = native.query_embed
|
| 387 |
+
self.action_head = native.action_head
|
| 388 |
+
self.additional_pos_embed = native.additional_pos_embed
|
| 389 |
+
self.num_queries = native.num_queries
|
| 390 |
+
width = self.transformer.d_model
|
| 391 |
+
self.action_input = nn.Linear(self.action_head.out_features, width)
|
| 392 |
+
self.time_mlp = nn.Sequential(
|
| 393 |
+
nn.Linear(width, width), nn.SiLU(), nn.Linear(width, width)
|
| 394 |
+
)
|
| 395 |
+
self.register_buffer(
|
| 396 |
+
"time_frequencies",
|
| 397 |
+
torch.exp(
|
| 398 |
+
-math.log(10000) * torch.arange(width // 2) / max(1, width // 2 - 1)
|
| 399 |
+
),
|
| 400 |
+
)
|
| 401 |
+
self.generator = None
|
| 402 |
+
|
| 403 |
+
def encode_observation(self, obs):
|
| 404 |
+
features, positions = [], []
|
| 405 |
+
for camera in range(obs["rgb"].shape[1]):
|
| 406 |
+
feature, position = self.backbones[0](obs["rgb"][:, camera])
|
| 407 |
+
features.append(self.input_proj(feature[0]))
|
| 408 |
+
positions.append(position[0])
|
| 409 |
+
batch = obs["rgb"].shape[0]
|
| 410 |
+
src = torch.cat(features, dim=3).flatten(2).permute(2, 0, 1)
|
| 411 |
+
pos = (
|
| 412 |
+
torch.cat(positions, dim=3).flatten(2).permute(2, 0, 1).repeat(1, batch, 1)
|
| 413 |
+
)
|
| 414 |
+
proprio = self.input_proj_robot_state(obs["state"]).unsqueeze(0)
|
| 415 |
+
# Keep the native proprioceptive position; there is no CVAE latent token.
|
| 416 |
+
pos = torch.cat(
|
| 417 |
+
[self.additional_pos_embed.weight[1:2, None].expand(-1, batch, -1), pos]
|
| 418 |
+
)
|
| 419 |
+
src = torch.cat([proprio, src])
|
| 420 |
+
memory = self.transformer.encoder(src, pos=pos)
|
| 421 |
+
return memory, pos
|
| 422 |
+
|
| 423 |
+
def velocity(self, noisy, time, memory, pos):
|
| 424 |
+
angles = time[:, None] * self.time_frequencies[None] * 1000
|
| 425 |
+
time_embedding = self.time_mlp(torch.cat([angles.sin(), angles.cos()], dim=-1))
|
| 426 |
+
target = (self.action_input(noisy) + time_embedding[:, None]).transpose(0, 1)
|
| 427 |
+
queries = self.query_embed.weight[:, None].expand(-1, noisy.shape[0], -1)
|
| 428 |
+
hidden = self.transformer.decoder(target, memory, pos=pos, query_pos=queries)[
|
| 429 |
+
-1
|
| 430 |
+
]
|
| 431 |
+
return self.action_head(hidden.transpose(0, 1))
|
| 432 |
+
|
| 433 |
+
def training_loss(self, obs, actions):
|
| 434 |
+
memory, pos = self.encode_observation(obs)
|
| 435 |
+
noise = torch.randn_like(actions)
|
| 436 |
+
time = torch.rand(actions.shape[0], device=actions.device)
|
| 437 |
+
noisy = (1 - time[:, None, None]) * noise + time[:, None, None] * actions
|
| 438 |
+
target = actions - noise
|
| 439 |
+
return F.mse_loss(self.velocity(noisy, time, memory, pos), target)
|
| 440 |
+
|
| 441 |
+
def forward(self, obs):
|
| 442 |
+
memory, pos = self.encode_observation(obs)
|
| 443 |
+
if self.generator is None or self.generator.device != obs["rgb"].device:
|
| 444 |
+
self.generator = torch.Generator(device=obs["rgb"].device)
|
| 445 |
+
self.generator.manual_seed(self.config.inference_seed)
|
| 446 |
+
batch = obs["rgb"].shape[0]
|
| 447 |
+
action = torch.randn(
|
| 448 |
+
batch,
|
| 449 |
+
self.num_queries,
|
| 450 |
+
self.action_head.out_features,
|
| 451 |
+
device=obs["rgb"].device,
|
| 452 |
+
generator=self.generator,
|
| 453 |
+
)
|
| 454 |
+
step = 1 / self.config.flow_steps
|
| 455 |
+
for index in range(self.config.flow_steps):
|
| 456 |
+
time = action.new_full((batch,), index * step)
|
| 457 |
+
action = action + step * self.velocity(action, time, memory, pos)
|
| 458 |
+
# Match native ACT: the controller clips after temporal aggregation.
|
| 459 |
+
return action, (None, None)
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def build_policy(native, spaces, args, policy, normalization=None):
|
| 463 |
+
fitted = checked_statistics(
|
| 464 |
+
normalization, policy.normalization, policy.action_encoding
|
| 465 |
+
)
|
| 466 |
+
if policy.action_encoding != "controller":
|
| 467 |
+
spaces = SimpleNamespace(
|
| 468 |
+
single_observation_space=spaces.single_observation_space,
|
| 469 |
+
single_action_space=SimpleNamespace(
|
| 470 |
+
shape=(
|
| 471 |
+
encoded_dimension(
|
| 472 |
+
spaces.single_action_space.shape[-1], policy.action_encoding
|
| 473 |
+
),
|
| 474 |
+
)
|
| 475 |
+
),
|
| 476 |
+
)
|
| 477 |
+
agent = native.Agent(spaces, args)
|
| 478 |
+
if policy.keypose_stop_head:
|
| 479 |
+
# Attach to the actual native decoder before context/normalization wrappers.
|
| 480 |
+
agent.model.action_head = KeyposeStopHead(
|
| 481 |
+
KeyposeStopHeadConfig(action_head=agent.model.action_head)
|
| 482 |
+
)
|
| 483 |
+
if policy.keypose_dense_head:
|
| 484 |
+
agent.model.action_head = DenseAuxiliaryHead(
|
| 485 |
+
DenseAuxiliaryHeadConfig(
|
| 486 |
+
primary=agent.model.action_head,
|
| 487 |
+
hidden_size=agent.model.action_head.action.in_features,
|
| 488 |
+
)
|
| 489 |
+
)
|
| 490 |
+
if policy.keypose_context != "none":
|
| 491 |
+
if fitted is None:
|
| 492 |
+
raise ValueError(
|
| 493 |
+
"Completed-goal context requires checkpoint-owned action statistics"
|
| 494 |
+
)
|
| 495 |
+
agent.model = KeyposeContextModel(
|
| 496 |
+
KeyposeContextModelConfig(
|
| 497 |
+
model=agent.model, mode=policy.keypose_context, statistics=fitted
|
| 498 |
+
)
|
| 499 |
+
)
|
| 500 |
+
if policy.keypose_phase_weight > 0 or policy.has_chunk_phase_head:
|
| 501 |
+
agent.model.action_head = KeyposePhaseHead(
|
| 502 |
+
KeyposePhaseHeadConfig(
|
| 503 |
+
action_head=agent.model.action_head,
|
| 504 |
+
all_queries=policy.has_chunk_phase_head,
|
| 505 |
+
)
|
| 506 |
+
)
|
| 507 |
+
if policy.chunk_switch_head:
|
| 508 |
+
# Outermost: it may wrap the phase head; both read the same features.
|
| 509 |
+
agent.model.action_head = ChunkSwitchHead(
|
| 510 |
+
ChunkSwitchHeadConfig(action_head=agent.model.action_head)
|
| 511 |
+
)
|
| 512 |
+
if policy.method == "state_free":
|
| 513 |
+
agent.model = StateFreeModel(
|
| 514 |
+
ModelBuildConfig(native_model=agent.model, policy=policy)
|
| 515 |
+
)
|
| 516 |
+
elif policy.method == "flow":
|
| 517 |
+
agent.model = FlowACT(ModelBuildConfig(native_model=agent.model, policy=policy))
|
| 518 |
+
if policy.state_input != "full":
|
| 519 |
+
agent.model = StateSubsetModel(
|
| 520 |
+
ModelBuildConfig(native_model=agent.model, policy=policy)
|
| 521 |
+
)
|
| 522 |
+
if policy.action_loss.method == "gripper_bce":
|
| 523 |
+
agent.model = BinaryGripperModel(BinaryGripperModelConfig(model=agent.model))
|
| 524 |
+
if fitted is not None:
|
| 525 |
+
if spaces.single_action_space.shape != (
|
| 526 |
+
len(fitted.action.center),
|
| 527 |
+
) or spaces.single_observation_space["state"].shape != (
|
| 528 |
+
len(fitted.state.center),
|
| 529 |
+
):
|
| 530 |
+
raise ValueError("Fitted normalization shapes differ from the policy")
|
| 531 |
+
agent.model = NormalizedModel(
|
| 532 |
+
NormalizedModelConfig(model=agent.model, statistics=fitted)
|
| 533 |
+
)
|
| 534 |
+
return agent
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def policy_loss(
|
| 538 |
+
agent,
|
| 539 |
+
native,
|
| 540 |
+
obs,
|
| 541 |
+
actions,
|
| 542 |
+
policy,
|
| 543 |
+
objective,
|
| 544 |
+
phase_labels=None,
|
| 545 |
+
stop_labels=None,
|
| 546 |
+
dense_labels=None,
|
| 547 |
+
switch_labels=None,
|
| 548 |
+
):
|
| 549 |
+
if policy.action_loss.method != "native":
|
| 550 |
+
if objective.config.method != "control":
|
| 551 |
+
raise ValueError(
|
| 552 |
+
"Action loss candidates require the control training recipe"
|
| 553 |
+
)
|
| 554 |
+
obs = {**obs, "rgb": agent.normalize(obs["rgb"].float() / 255)}
|
| 555 |
+
prediction, (mu, logvar) = agent.model(obs, actions)
|
| 556 |
+
losses = pose_reconstruction(prediction, actions, policy.action_loss)
|
| 557 |
+
kl = native.kl_divergence(mu, logvar)[0][0]
|
| 558 |
+
result = {
|
| 559 |
+
"loss": losses["reconstruction"] + agent.kl_weight * kl,
|
| 560 |
+
"kl": kl,
|
| 561 |
+
**losses,
|
| 562 |
+
}
|
| 563 |
+
if policy.keypose_phase_weight > 0:
|
| 564 |
+
logits = read_phase_logits(agent)
|
| 565 |
+
if (
|
| 566 |
+
phase_labels is None
|
| 567 |
+
or phase_labels.dtype != torch.long
|
| 568 |
+
or phase_labels.shape != logits.shape[:1]
|
| 569 |
+
or not ((phase_labels >= 0) & (phase_labels < 6)).all()
|
| 570 |
+
):
|
| 571 |
+
raise ValueError(
|
| 572 |
+
"Expected one integer primitive label in [0, 5] per observation"
|
| 573 |
+
)
|
| 574 |
+
phase_ce = F.cross_entropy(logits, phase_labels)
|
| 575 |
+
result.update(
|
| 576 |
+
loss=result["loss"] + policy.keypose_phase_weight * phase_ce,
|
| 577 |
+
phase_ce=phase_ce,
|
| 578 |
+
phase_accuracy=(logits.argmax(-1) == phase_labels).float().mean(),
|
| 579 |
+
)
|
| 580 |
+
if policy.has_chunk_phase_head:
|
| 581 |
+
logits = read_phase_logits(agent)
|
| 582 |
+
if (
|
| 583 |
+
phase_labels is None
|
| 584 |
+
or phase_labels.dtype != torch.long
|
| 585 |
+
or phase_labels.shape != prediction.shape[:2]
|
| 586 |
+
or logits.shape != (*prediction.shape[:2], 6)
|
| 587 |
+
or not (
|
| 588 |
+
(phase_labels == -100) | ((phase_labels >= 0) & (phase_labels < 6))
|
| 589 |
+
).all()
|
| 590 |
+
or not (phase_labels[:, 0] >= 0).all()
|
| 591 |
+
):
|
| 592 |
+
raise ValueError(
|
| 593 |
+
"Expected valid future phase labels and -100 only for padding"
|
| 594 |
+
)
|
| 595 |
+
phase_ce = F.cross_entropy(
|
| 596 |
+
logits.flatten(0, 1), phase_labels.flatten(), ignore_index=-100
|
| 597 |
+
)
|
| 598 |
+
valid = phase_labels != -100
|
| 599 |
+
# Keep CE as a diagnostic at weight zero, but remove its graph from
|
| 600 |
+
# the objective entirely: unused head parameters must get no gradient.
|
| 601 |
+
if policy.chunk_phase_weight > 0:
|
| 602 |
+
result["loss"] = result["loss"] + policy.chunk_phase_weight * phase_ce
|
| 603 |
+
result.update(
|
| 604 |
+
phase_ce=phase_ce,
|
| 605 |
+
phase_accuracy=(logits.argmax(-1)[valid] == phase_labels[valid])
|
| 606 |
+
.float()
|
| 607 |
+
.mean(),
|
| 608 |
+
phase_query0_accuracy=(logits[:, 0].argmax(-1) == phase_labels[:, 0])
|
| 609 |
+
.float()
|
| 610 |
+
.mean(),
|
| 611 |
+
)
|
| 612 |
+
if policy.keypose_stop_head:
|
| 613 |
+
logits = read_stop_logits(agent)
|
| 614 |
+
if (
|
| 615 |
+
stop_labels is None
|
| 616 |
+
or not stop_labels.is_floating_point()
|
| 617 |
+
or stop_labels.shape != logits.shape
|
| 618 |
+
or logits.ndim != 1
|
| 619 |
+
or not ((stop_labels == 0) | (stop_labels == 1)).all()
|
| 620 |
+
):
|
| 621 |
+
raise ValueError("Expected one float binary stop label per observation")
|
| 622 |
+
stop_bce = F.binary_cross_entropy_with_logits(logits, stop_labels)
|
| 623 |
+
result.update(
|
| 624 |
+
loss=result["loss"] + policy.keypose_stop_weight * stop_bce,
|
| 625 |
+
stop_bce=stop_bce,
|
| 626 |
+
stop_accuracy=((logits >= 0) == stop_labels.bool()).float().mean(),
|
| 627 |
+
stop_predicted_positive=(logits >= 0).float().mean(),
|
| 628 |
+
)
|
| 629 |
+
if policy.chunk_switch_head:
|
| 630 |
+
fraction = read_switch_fraction(agent)
|
| 631 |
+
if (
|
| 632 |
+
switch_labels is None
|
| 633 |
+
or not switch_labels.is_floating_point()
|
| 634 |
+
or switch_labels.shape != fraction.shape
|
| 635 |
+
or not ((switch_labels > 0) & (switch_labels <= 1)).all()
|
| 636 |
+
):
|
| 637 |
+
raise ValueError("Expected one remaining-steps fraction in (0, 1] per observation")
|
| 638 |
+
switch_l1 = (fraction - switch_labels).abs().mean()
|
| 639 |
+
# At weight zero the head stays a diagnostic: no graph, no gradient.
|
| 640 |
+
if policy.chunk_switch_weight > 0:
|
| 641 |
+
result["loss"] = result["loss"] + policy.chunk_switch_weight * switch_l1
|
| 642 |
+
result["switch_l1"] = switch_l1.detach()
|
| 643 |
+
if policy.keypose_dense_head:
|
| 644 |
+
dense_prediction = read_dense_actions(agent)
|
| 645 |
+
if (
|
| 646 |
+
dense_labels is None
|
| 647 |
+
or dense_labels.shape != prediction.shape
|
| 648 |
+
or dense_prediction.shape != prediction.shape
|
| 649 |
+
or not torch.isfinite(dense_labels).all()
|
| 650 |
+
):
|
| 651 |
+
raise ValueError(
|
| 652 |
+
"Expected finite normalized dense labels matching the original Q30 horizon"
|
| 653 |
+
)
|
| 654 |
+
dense_loss = pose_reconstruction(
|
| 655 |
+
dense_prediction,
|
| 656 |
+
dense_labels,
|
| 657 |
+
ActionLossConfig(method="group_balanced"),
|
| 658 |
+
)
|
| 659 |
+
result.update(
|
| 660 |
+
loss=result["loss"]
|
| 661 |
+
+ policy.keypose_dense_weight * dense_loss["reconstruction"],
|
| 662 |
+
**{f"dense_{key}": value for key, value in dense_loss.items()},
|
| 663 |
+
)
|
| 664 |
+
return result
|
| 665 |
+
if policy.method != "flow":
|
| 666 |
+
return objective.compute_loss(agent, native, obs, actions)
|
| 667 |
+
obs = {**obs, "rgb": agent.normalize(obs["rgb"].float() / 255)}
|
| 668 |
+
loss = agent.model.training_loss(obs, actions)
|
| 669 |
+
return {"loss": loss, "flow_mse": loss}
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
class ChunkDatasetConfig(BaseModel, frozen=True):
|
| 673 |
+
model_config = ConfigDict(
|
| 674 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 675 |
+
)
|
| 676 |
+
dataset: Any
|
| 677 |
+
"""Pinned native preprocessed StackCube dataset with state25 and delta actions."""
|
| 678 |
+
action_encoding: ActionEncoding = "controller"
|
| 679 |
+
"""Existing position-only controller labels, or dense fixed-reference pose6D."""
|
| 680 |
+
source: Path | None = None
|
| 681 |
+
"""Pose6D H5 used to verify robot-root axes in every saved state."""
|
| 682 |
+
chunk_anchor: ChunkAnchor = "chunk_start_tcp"
|
| 683 |
+
"""Label origin; identity makes every target an absolute world pose."""
|
| 684 |
+
phase_supervision: bool = False
|
| 685 |
+
"""Return each valid future action's primitive label; ignore padded labels."""
|
| 686 |
+
chunk_pose_supervision: ChunkPoseSupervision = "dense"
|
| 687 |
+
"""Only valid-slot pose labels change; phase and fitted scales do not."""
|
| 688 |
+
chunk_gripper_supervision: ChunkGripperSupervision = "future"
|
| 689 |
+
"""Future commands or current command repeated in valid slots only."""
|
| 690 |
+
chunk_padding: ChunkPadding = "terminal"
|
| 691 |
+
"""Measured terminal pose/last gripper, or repeat the current complete target."""
|
| 692 |
+
chunk_normalization_population: Literal["dense", "supervised"] = "dense"
|
| 693 |
+
"""Action statistics use dense valid pairs, or one complete current target per
|
| 694 |
+
observation for the repeated current-target recipe."""
|
| 695 |
+
chunk_label_offset: NonNegativeInt = 0
|
| 696 |
+
"""Slot i supervises time t+offset+i; zero preserves every existing recipe."""
|
| 697 |
+
chunk_waypoint_threshold_m: PositiveFloat | None = None
|
| 698 |
+
"""AWE distance threshold for future_waypoint labels."""
|
| 699 |
+
switch_supervision: bool = False
|
| 700 |
+
"""Also return the current primitive's remaining-steps fraction."""
|
| 701 |
+
|
| 702 |
+
@model_validator(mode="after")
|
| 703 |
+
def check_supervision(self):
|
| 704 |
+
if self.chunk_padding == "current_target" and (
|
| 705 |
+
self.chunk_pose_supervision != "current_endpoint"
|
| 706 |
+
or self.chunk_gripper_supervision != "current"
|
| 707 |
+
):
|
| 708 |
+
raise ValueError(
|
| 709 |
+
"Current-target padding requires current endpoint and gripper"
|
| 710 |
+
)
|
| 711 |
+
if (
|
| 712 |
+
self.chunk_gripper_supervision != "future"
|
| 713 |
+
and self.action_encoding != "rotation6d"
|
| 714 |
+
):
|
| 715 |
+
raise ValueError("Chunk gripper supervision requires pose6D data")
|
| 716 |
+
if (
|
| 717 |
+
self.chunk_pose_supervision != "dense"
|
| 718 |
+
and self.action_encoding != "rotation6d"
|
| 719 |
+
):
|
| 720 |
+
raise ValueError(
|
| 721 |
+
"Endpoint labels require pose6D chunk-relative data"
|
| 722 |
+
)
|
| 723 |
+
if self.chunk_normalization_population == "supervised" and (
|
| 724 |
+
self.chunk_pose_supervision != "current_endpoint"
|
| 725 |
+
or self.chunk_gripper_supervision != "current"
|
| 726 |
+
or self.chunk_padding != "current_target"
|
| 727 |
+
):
|
| 728 |
+
raise ValueError(
|
| 729 |
+
"Supervised normalization requires repeated complete current-target endpoint labels"
|
| 730 |
+
)
|
| 731 |
+
return self
|
| 732 |
+
|
| 733 |
+
|
| 734 |
+
def remaining_fraction(ends, labels):
|
| 735 |
+
"""Steps left in each observation's primitive, min(steps, horizon)/horizon."""
|
| 736 |
+
remaining = torch.from_numpy(ends).long()[labels] - torch.arange(len(labels))
|
| 737 |
+
if not (remaining >= 1).all():
|
| 738 |
+
raise ValueError("Every observation must have at least one remaining step")
|
| 739 |
+
return remaining.clamp(max=SWITCH_HORIZON).float() / SWITCH_HORIZON
|
| 740 |
+
|
| 741 |
+
|
| 742 |
+
class ChunkRelativeDataset(Dataset):
|
| 743 |
+
"""Encode actual controller goals relative to each query's current TCP.
|
| 744 |
+
|
| 745 |
+
StackCube panda_wristcam state = qpos9, qvel9, world TCP pose7.
|
| 746 |
+
The root orientation is identity and pd_ee_delta_pos uses scale 0.1 m.
|
| 747 |
+
Positions at future steps are supervised data only, never policy inputs.
|
| 748 |
+
"""
|
| 749 |
+
|
| 750 |
+
def __init__(self, config: ChunkDatasetConfig):
|
| 751 |
+
self.config = config
|
| 752 |
+
self.dataset = config.dataset
|
| 753 |
+
self.phase_chunks = []
|
| 754 |
+
self.waypoint_counts = []
|
| 755 |
+
if config.phase_supervision and config.action_encoding != "rotation6d":
|
| 756 |
+
raise ValueError("Chunk phase labels require pose6D data")
|
| 757 |
+
for trajectory in self.dataset.trajectories["observations"]:
|
| 758 |
+
if trajectory["state"].shape[-1] != 25:
|
| 759 |
+
raise ValueError("Chunk labels require the audited state25 layout")
|
| 760 |
+
if config.action_encoding == "rotation6d":
|
| 761 |
+
import h5py
|
| 762 |
+
|
| 763 |
+
if config.source is None:
|
| 764 |
+
raise ValueError(
|
| 765 |
+
"Pose chunk-relative labels require source H5 root-frame verification"
|
| 766 |
+
)
|
| 767 |
+
self.chunks = []
|
| 768 |
+
self.world_targets = []
|
| 769 |
+
self.switch_labels = []
|
| 770 |
+
populations = []
|
| 771 |
+
with h5py.File(config.source) as data:
|
| 772 |
+
names = sorted(data, key=lambda n: int(n.split("_")[-1]))[
|
| 773 |
+
: self.dataset.num_traj
|
| 774 |
+
]
|
| 775 |
+
if len(names) != self.dataset.num_traj:
|
| 776 |
+
raise ValueError(
|
| 777 |
+
"Source trajectory count differs from the native dataset"
|
| 778 |
+
)
|
| 779 |
+
for name, actions, obs in zip(
|
| 780 |
+
names,
|
| 781 |
+
self.trajectories["actions"],
|
| 782 |
+
self.trajectories["observations"],
|
| 783 |
+
strict=True,
|
| 784 |
+
):
|
| 785 |
+
tcp = obs["state"][:, 18:25]
|
| 786 |
+
if actions.shape[-1] != 7 or len(tcp) != len(actions) + 1:
|
| 787 |
+
raise ValueError(
|
| 788 |
+
"Expected unencoded pose actions and a terminal TCP"
|
| 789 |
+
)
|
| 790 |
+
stored_tcp = torch.from_numpy(data[name]["obs/extra/tcp_pose"][:])
|
| 791 |
+
torch.testing.assert_close(tcp, stored_tcp, atol=0, rtol=0)
|
| 792 |
+
roots = data[name]["env_states/articulations/panda_wristcam"][
|
| 793 |
+
:, 3:7
|
| 794 |
+
]
|
| 795 |
+
np.testing.assert_allclose(
|
| 796 |
+
roots, np.tile([1, 0, 0, 0], (len(roots), 1)), atol=1e-5
|
| 797 |
+
)
|
| 798 |
+
goals = controller_pose_targets(actions, tcp[:-1])
|
| 799 |
+
terminal = encode_keypose(tcp[-1], actions[-1, -1])[None]
|
| 800 |
+
goals = torch.cat([goals, terminal])
|
| 801 |
+
times = (
|
| 802 |
+
torch.arange(len(actions))[:, None]
|
| 803 |
+
+ config.chunk_label_offset
|
| 804 |
+
+ torch.arange(self.num_queries)[None]
|
| 805 |
+
)
|
| 806 |
+
valid = times < len(actions)
|
| 807 |
+
if config.chunk_pose_supervision == "future_waypoint":
|
| 808 |
+
from lim.waypoints import next_waypoint, select_waypoints
|
| 809 |
+
|
| 810 |
+
waypoints = select_waypoints(
|
| 811 |
+
goals[: len(actions), :3].numpy(),
|
| 812 |
+
config.chunk_waypoint_threshold_m,
|
| 813 |
+
actions[:, -1].numpy(),
|
| 814 |
+
)
|
| 815 |
+
self.waypoint_counts.append((len(waypoints), len(actions)))
|
| 816 |
+
following = torch.from_numpy(
|
| 817 |
+
next_waypoint(len(actions), waypoints)
|
| 818 |
+
)
|
| 819 |
+
if (
|
| 820 |
+
config.phase_supervision
|
| 821 |
+
or config.chunk_pose_supervision not in ("dense", "future_waypoint")
|
| 822 |
+
):
|
| 823 |
+
from lim.keypose_phase import KEYPOSE_PHASE_NAMES
|
| 824 |
+
|
| 825 |
+
key = data[name]["keyframes"]
|
| 826 |
+
labels = torch.from_numpy(
|
| 827 |
+
key["action_keyframe_index"][:]
|
| 828 |
+
).long()
|
| 829 |
+
starts, ends = key["start_action"][:], key["end_action"][:]
|
| 830 |
+
# Six-class phase labels exist only for the canonical
|
| 831 |
+
# StackCube primitives; other tasks' experts record
|
| 832 |
+
# their own primitive list, used for endpoints alone.
|
| 833 |
+
segments = len(starts)
|
| 834 |
+
if (
|
| 835 |
+
(
|
| 836 |
+
config.phase_supervision
|
| 837 |
+
and tuple(key["name"].asstr()[:]) != KEYPOSE_PHASE_NAMES
|
| 838 |
+
)
|
| 839 |
+
or segments < 1
|
| 840 |
+
or starts.shape != (segments,)
|
| 841 |
+
or ends.shape != (segments,)
|
| 842 |
+
or starts[0] != 0
|
| 843 |
+
or ends[-1] != len(actions)
|
| 844 |
+
or np.any(ends <= starts)
|
| 845 |
+
or not np.array_equal(starts[1:], ends[:-1])
|
| 846 |
+
or not np.array_equal(
|
| 847 |
+
labels.numpy(), np.repeat(np.arange(segments), ends - starts)
|
| 848 |
+
)
|
| 849 |
+
):
|
| 850 |
+
raise ValueError(
|
| 851 |
+
"Expected aligned canonical primitive indices"
|
| 852 |
+
)
|
| 853 |
+
phase = labels[times.clamp(max=len(actions) - 1)].clone()
|
| 854 |
+
phase[~valid] = -100
|
| 855 |
+
self.phase_chunks.append(phase)
|
| 856 |
+
relative = world_to_chunk_relative(
|
| 857 |
+
goals[times.clamp(max=len(actions))],
|
| 858 |
+
resolve_anchor(tcp[:-1, None], config.chunk_anchor),
|
| 859 |
+
)
|
| 860 |
+
# The default population preserves the original dense labels
|
| 861 |
+
# and physical loss weights across supervision variants.
|
| 862 |
+
if config.chunk_normalization_population == "dense":
|
| 863 |
+
populations.append(relative[valid])
|
| 864 |
+
if config.chunk_pose_supervision == "future_waypoint":
|
| 865 |
+
replacement = world_to_chunk_relative(
|
| 866 |
+
goals[following[times.clamp(max=len(actions) - 1)]],
|
| 867 |
+
resolve_anchor(tcp[:-1, None], config.chunk_anchor),
|
| 868 |
+
)
|
| 869 |
+
relative[valid] = torch.cat(
|
| 870 |
+
[replacement[valid][:, :9], relative[valid][:, -1:]], -1
|
| 871 |
+
)
|
| 872 |
+
elif config.chunk_pose_supervision != "dense":
|
| 873 |
+
poses = torch.from_numpy(key["target_pose_world"][:])
|
| 874 |
+
grippers = torch.from_numpy(key["gripper_command"][:])
|
| 875 |
+
if (
|
| 876 |
+
poses.shape != (segments, 7)
|
| 877 |
+
or grippers.shape != (segments,)
|
| 878 |
+
or not torch.isfinite(poses).all()
|
| 879 |
+
or not torch.isfinite(grippers).all()
|
| 880 |
+
or not torch.equal(grippers[labels], actions[:, -1])
|
| 881 |
+
):
|
| 882 |
+
raise ValueError(
|
| 883 |
+
"Endpoint and dense primitive labels disagree"
|
| 884 |
+
)
|
| 885 |
+
endpoints = encode_keypose(poses, grippers)
|
| 886 |
+
if config.chunk_pose_supervision == "phase_segments":
|
| 887 |
+
if self.num_queries != 2:
|
| 888 |
+
raise ValueError("Phase segments require exactly two queries")
|
| 889 |
+
segments = torch.stack(
|
| 890 |
+
[labels, (labels + 1).clamp(max=5)], -1
|
| 891 |
+
)
|
| 892 |
+
# Both slots carry their own primitive gripper command.
|
| 893 |
+
relative = world_to_chunk_relative(
|
| 894 |
+
endpoints[segments],
|
| 895 |
+
resolve_anchor(tcp[:-1, None], config.chunk_anchor),
|
| 896 |
+
)
|
| 897 |
+
self.switch_labels.append(remaining_fraction(ends, labels))
|
| 898 |
+
self.chunks.append(relative)
|
| 899 |
+
self.world_targets.append(goals)
|
| 900 |
+
continue
|
| 901 |
+
if config.switch_supervision:
|
| 902 |
+
self.switch_labels.append(remaining_fraction(ends, labels))
|
| 903 |
+
endpoint_indices = (
|
| 904 |
+
labels[times.clamp(max=len(actions) - 1)]
|
| 905 |
+
if config.chunk_pose_supervision == "future_endpoint"
|
| 906 |
+
else labels[:, None].expand_as(times)
|
| 907 |
+
)
|
| 908 |
+
replacement = world_to_chunk_relative(
|
| 909 |
+
endpoints[endpoint_indices],
|
| 910 |
+
resolve_anchor(tcp[:-1, None], config.chunk_anchor),
|
| 911 |
+
)
|
| 912 |
+
# Preserve original dense terminal padding and every
|
| 913 |
+
# future gripper command, including in current_endpoint.
|
| 914 |
+
relative[valid] = torch.cat(
|
| 915 |
+
[replacement[valid][:, :9], relative[valid][:, -1:]], -1
|
| 916 |
+
)
|
| 917 |
+
if config.chunk_gripper_supervision == "current":
|
| 918 |
+
# Change the supervised gripper timing only. The current
|
| 919 |
+
# command is not the phase-end command and never replaces
|
| 920 |
+
# the terminal padding or dense normalization population.
|
| 921 |
+
repeated = actions[:, -1, None].expand_as(times)
|
| 922 |
+
relative[..., -1][valid] = repeated[valid]
|
| 923 |
+
if config.chunk_padding == "current_target":
|
| 924 |
+
# Query zero always exists and already has the complete
|
| 925 |
+
# current endpoint. Only replace out-of-range slots.
|
| 926 |
+
repeated = relative[:, :1].expand_as(relative)
|
| 927 |
+
relative[~valid] = repeated[~valid]
|
| 928 |
+
if config.chunk_normalization_population == "supervised":
|
| 929 |
+
# One target per original observation, independent of Q
|
| 930 |
+
# and padding, matching the old KeyposeDataset weighting.
|
| 931 |
+
populations.append(relative[:, 0])
|
| 932 |
+
self.chunks.append(relative)
|
| 933 |
+
self.world_targets.append(goals)
|
| 934 |
+
self.normalization_actions = torch.cat(populations)
|
| 935 |
+
self.target_contract = pose_target_contract(
|
| 936 |
+
config.chunk_anchor,
|
| 937 |
+
config.chunk_pose_supervision,
|
| 938 |
+
config.chunk_gripper_supervision,
|
| 939 |
+
config.chunk_padding,
|
| 940 |
+
config.chunk_normalization_population,
|
| 941 |
+
config.chunk_label_offset,
|
| 942 |
+
config.chunk_waypoint_threshold_m,
|
| 943 |
+
)
|
| 944 |
+
all_chunks = torch.cat(self.chunks)
|
| 945 |
+
tensors = {
|
| 946 |
+
"sample_indices": torch.tensor(self.dataset.slices),
|
| 947 |
+
"pose_labels": all_chunks[..., :9],
|
| 948 |
+
"gripper_labels": all_chunks[..., -1],
|
| 949 |
+
"normalization_population": self.normalization_actions,
|
| 950 |
+
}
|
| 951 |
+
if self.phase_chunks:
|
| 952 |
+
tensors["phase_labels"] = torch.cat(self.phase_chunks)
|
| 953 |
+
if self.switch_labels:
|
| 954 |
+
tensors["switch_labels"] = torch.cat(self.switch_labels)
|
| 955 |
+
self.supervision_audit = {
|
| 956 |
+
"pose_supervision": config.chunk_pose_supervision,
|
| 957 |
+
"gripper_supervision": config.chunk_gripper_supervision,
|
| 958 |
+
"samples": len(self.dataset.slices),
|
| 959 |
+
"normalization_samples": len(self.normalization_actions),
|
| 960 |
+
**{
|
| 961 |
+
f"{name}_sha256": hashlib.sha256(
|
| 962 |
+
tensor.contiguous().numpy().tobytes()
|
| 963 |
+
).hexdigest()
|
| 964 |
+
for name, tensor in tensors.items()
|
| 965 |
+
},
|
| 966 |
+
**(
|
| 967 |
+
{
|
| 968 |
+
"waypoints": sum(w for w, _ in self.waypoint_counts),
|
| 969 |
+
"actions": sum(n for _, n in self.waypoint_counts),
|
| 970 |
+
"waypoint_threshold_m": config.chunk_waypoint_threshold_m,
|
| 971 |
+
}
|
| 972 |
+
if self.waypoint_counts
|
| 973 |
+
else {}
|
| 974 |
+
),
|
| 975 |
+
}
|
| 976 |
+
|
| 977 |
+
def __getattr__(self, name):
|
| 978 |
+
return getattr(self.dataset, name)
|
| 979 |
+
|
| 980 |
+
def __len__(self):
|
| 981 |
+
return len(self.dataset)
|
| 982 |
+
|
| 983 |
+
def __getitem__(self, index):
|
| 984 |
+
trajectory, start = self.dataset.slices[index]
|
| 985 |
+
if self.config.action_encoding == "rotation6d":
|
| 986 |
+
return {
|
| 987 |
+
"observations": {
|
| 988 |
+
k: v[start]
|
| 989 |
+
for k, v in self.trajectories["observations"][trajectory].items()
|
| 990 |
+
},
|
| 991 |
+
"actions": self.chunks[trajectory][start],
|
| 992 |
+
**(
|
| 993 |
+
{"phase": self.phase_chunks[trajectory][start]}
|
| 994 |
+
if self.config.phase_supervision
|
| 995 |
+
else {}
|
| 996 |
+
),
|
| 997 |
+
**(
|
| 998 |
+
{"switch": self.switch_labels[trajectory][start]}
|
| 999 |
+
if self.switch_labels
|
| 1000 |
+
else {}
|
| 1001 |
+
),
|
| 1002 |
+
}
|
| 1003 |
+
sample = self.dataset[index]
|
| 1004 |
+
positions = self.dataset.trajectories["observations"][trajectory]["state"][
|
| 1005 |
+
:, 18:21
|
| 1006 |
+
]
|
| 1007 |
+
length = len(self.dataset.trajectories["actions"][trajectory])
|
| 1008 |
+
if len(positions) != length + 1:
|
| 1009 |
+
raise ValueError("Expected terminal TCP observation for stationary padding")
|
| 1010 |
+
times = torch.arange(start, start + self.dataset.num_queries).clamp(max=length)
|
| 1011 |
+
actions = sample["actions"].clone()
|
| 1012 |
+
# Native labels contain already bounded normalized delta commands. Do not
|
| 1013 |
+
# clip the resulting chunk targets: legitimate offsets can exceed +/-1.
|
| 1014 |
+
actions[:, :3] += (positions[times] - positions[start]) / 0.1
|
| 1015 |
+
return {"observations": sample["observations"], "actions": actions}
|
| 1016 |
+
|
| 1017 |
+
|
| 1018 |
+
class TargetTransportConfig(BaseModel, frozen=True):
|
| 1019 |
+
model_config = ConfigDict(
|
| 1020 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 1021 |
+
)
|
| 1022 |
+
wrapped: Any
|
| 1023 |
+
"""Agent or environment at the existing native evaluator boundary."""
|
| 1024 |
+
action_encoding: ActionEncoding = "controller"
|
| 1025 |
+
"""Position-only scaled world goals, or world xyz plus 6D rotation goals."""
|
| 1026 |
+
chunk_anchor: ChunkAnchor = "chunk_start_tcp"
|
| 1027 |
+
"""Frame the model's output is expressed in; must match its training labels."""
|
| 1028 |
+
|
| 1029 |
+
|
| 1030 |
+
class TargetFrameAgent:
|
| 1031 |
+
"""Express all predicted TCP goals in one frame before native ensembling."""
|
| 1032 |
+
|
| 1033 |
+
def __init__(self, config: TargetTransportConfig):
|
| 1034 |
+
self.config = config
|
| 1035 |
+
self.wrapped = config.wrapped
|
| 1036 |
+
|
| 1037 |
+
def __getattr__(self, name):
|
| 1038 |
+
return getattr(self.wrapped, name)
|
| 1039 |
+
|
| 1040 |
+
def get_action(self, obs):
|
| 1041 |
+
target = self.wrapped.get_action(obs).clone()
|
| 1042 |
+
if self.config.action_encoding == "rotation6d":
|
| 1043 |
+
# Restore with the SAME frame the labels were written in.
|
| 1044 |
+
return chunk_relative_to_world(
|
| 1045 |
+
target,
|
| 1046 |
+
resolve_anchor(obs["state"][:, None, 18:25], self.config.chunk_anchor),
|
| 1047 |
+
)
|
| 1048 |
+
if self.config.chunk_anchor != "chunk_start_tcp":
|
| 1049 |
+
raise ValueError("Absolute anchors require the pose6D encoding")
|
| 1050 |
+
target[:, :, :3] += obs["state"][:, None, 18:21] / 0.1
|
| 1051 |
+
return target
|
| 1052 |
+
|
| 1053 |
+
|
| 1054 |
+
class TargetFrameEnv:
|
| 1055 |
+
"""Convert the ensembled goal to the current controller delta exactly once."""
|
| 1056 |
+
|
| 1057 |
+
def __init__(self, config: TargetTransportConfig):
|
| 1058 |
+
self.config = config
|
| 1059 |
+
self.wrapped = config.wrapped
|
| 1060 |
+
self.current_tcp = None
|
| 1061 |
+
if config.action_encoding == "rotation6d":
|
| 1062 |
+
import gymnasium as gym
|
| 1063 |
+
|
| 1064 |
+
self.action_space = gym.spaces.Box(
|
| 1065 |
+
-np.inf, np.inf, (self.wrapped.num_envs, 10), dtype=np.float32
|
| 1066 |
+
)
|
| 1067 |
+
self.single_action_space = gym.spaces.Box(
|
| 1068 |
+
-np.inf, np.inf, (10,), dtype=np.float32
|
| 1069 |
+
)
|
| 1070 |
+
|
| 1071 |
+
def __getattr__(self, name):
|
| 1072 |
+
return getattr(self.wrapped, name)
|
| 1073 |
+
|
| 1074 |
+
def remember(self, observation):
|
| 1075 |
+
self.current_tcp = np.array(observation["state"][:, 18:25], copy=True)
|
| 1076 |
+
|
| 1077 |
+
def reset(self):
|
| 1078 |
+
observation, info = self.wrapped.reset()
|
| 1079 |
+
self.remember(observation)
|
| 1080 |
+
return observation, info
|
| 1081 |
+
|
| 1082 |
+
def step(self, target):
|
| 1083 |
+
if self.config.action_encoding == "rotation6d":
|
| 1084 |
+
delta = world_to_chunk_relative(
|
| 1085 |
+
torch.as_tensor(target), torch.as_tensor(self.current_tcp)
|
| 1086 |
+
)
|
| 1087 |
+
action = sixd_to_controller(delta).numpy()
|
| 1088 |
+
else:
|
| 1089 |
+
action = np.array(target, copy=True)
|
| 1090 |
+
action[:, :3] -= self.current_tcp[:, :3] / 0.1
|
| 1091 |
+
result = self.wrapped.step(action)
|
| 1092 |
+
self.remember(result[0])
|
| 1093 |
+
return result
|
| 1094 |
+
|
| 1095 |
+
|
| 1096 |
+
def evaluation_transport(agent, env, policy):
|
| 1097 |
+
if policy.keypose is not None:
|
| 1098 |
+
return (
|
| 1099 |
+
FirstKeyposeAgent(FirstKeyposeAgentConfig(agent=agent)),
|
| 1100 |
+
KeyposeEnv(KeyposeEnvConfig(env=env, control=policy.keypose)),
|
| 1101 |
+
)
|
| 1102 |
+
if policy.method == "chunk_relative":
|
| 1103 |
+
return (
|
| 1104 |
+
TargetFrameAgent(
|
| 1105 |
+
TargetTransportConfig(
|
| 1106 |
+
wrapped=agent,
|
| 1107 |
+
action_encoding=policy.action_encoding,
|
| 1108 |
+
chunk_anchor=policy.chunk_anchor,
|
| 1109 |
+
)
|
| 1110 |
+
),
|
| 1111 |
+
# The environment converts world goals against the real measured TCP
|
| 1112 |
+
# under every anchor mode; that boundary is physical, not a label frame.
|
| 1113 |
+
TargetFrameEnv(
|
| 1114 |
+
TargetTransportConfig(
|
| 1115 |
+
wrapped=env, action_encoding=policy.action_encoding
|
| 1116 |
+
)
|
| 1117 |
+
),
|
| 1118 |
+
)
|
| 1119 |
+
if policy.action_loss.method == "gripper_bce":
|
| 1120 |
+
env = BinaryGripperEnv(BinaryGripperEnvConfig(env=env))
|
| 1121 |
+
if policy.action_encoding == "rotation6d":
|
| 1122 |
+
return agent, Rotation6DEnv(EncodedEnvConfig(env=env))
|
| 1123 |
+
return agent, env
|
fair-comparison/p3x-liftslow-v1/code/lim/action.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Invertible action coordinates with one shared controller contract."""
|
| 2 |
+
|
| 3 |
+
from typing import Literal
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from scipy.spatial.transform import Rotation
|
| 7 |
+
|
| 8 |
+
ActionFrame = Literal["absolute", "tcp", "target"]
|
| 9 |
+
POSITION_SCALE = 0.1
|
| 10 |
+
# ManiSkill 3.0.1 PDEEPoseController scales by config.rot_lower (-0.1).
|
| 11 |
+
ROTATION_SCALE = -0.1
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def tcp_rotation(tcp: np.ndarray) -> Rotation:
|
| 15 |
+
# SAPIEN exposes wxyz; scipy expects xyzw.
|
| 16 |
+
return Rotation.from_quat(tcp[..., [4, 5, 6, 3]])
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def reference_position(
|
| 20 |
+
frame: ActionFrame, tcp: np.ndarray, target: np.ndarray
|
| 21 |
+
) -> np.ndarray:
|
| 22 |
+
if frame == "absolute":
|
| 23 |
+
return np.zeros_like(tcp[..., :3])
|
| 24 |
+
if frame == "tcp":
|
| 25 |
+
return tcp[..., :3]
|
| 26 |
+
if frame == "target":
|
| 27 |
+
return target
|
| 28 |
+
raise ValueError(frame)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def controller_targets(
|
| 32 |
+
tcp: np.ndarray, actions: np.ndarray
|
| 33 |
+
) -> tuple[np.ndarray, np.ndarray]:
|
| 34 |
+
position = tcp[..., :3] + actions[..., :3] * POSITION_SCALE
|
| 35 |
+
raw_rotation = actions[..., 3:6]
|
| 36 |
+
raw_rotation = raw_rotation / np.maximum(
|
| 37 |
+
np.linalg.norm(raw_rotation, axis=-1, keepdims=True), 1
|
| 38 |
+
)
|
| 39 |
+
delta = Rotation.from_euler("XYZ", raw_rotation * ROTATION_SCALE)
|
| 40 |
+
rotation = (delta * tcp_rotation(tcp)).as_matrix()
|
| 41 |
+
return position, rotation
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def encode_chunk(position, rotation, gripper, current_tcp, target, frame: ActionFrame):
|
| 45 |
+
anchor = reference_position(frame, current_tcp, target)
|
| 46 |
+
pos = (position - anchor) / POSITION_SCALE
|
| 47 |
+
relative_rotation = tcp_rotation(current_tcp).as_matrix().T @ rotation
|
| 48 |
+
rot6d = relative_rotation[..., :, :2].reshape(*relative_rotation.shape[:-2], 6)
|
| 49 |
+
return np.concatenate([pos, rot6d, gripper[..., None]], axis=-1).astype(np.float32)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def prediction_to_world(
|
| 53 |
+
prediction: np.ndarray, tcp: np.ndarray, target: np.ndarray, frame: ActionFrame
|
| 54 |
+
):
|
| 55 |
+
position = prediction[:3] * POSITION_SCALE + reference_position(frame, tcp, target)
|
| 56 |
+
columns = prediction[3:9].reshape(3, 2)
|
| 57 |
+
x = columns[:, 0] / max(np.linalg.norm(columns[:, 0]), 1e-8)
|
| 58 |
+
y = columns[:, 1] - x * np.dot(x, columns[:, 1])
|
| 59 |
+
y /= max(np.linalg.norm(y), 1e-8)
|
| 60 |
+
relative = np.stack([x, y, np.cross(x, y)], axis=1)
|
| 61 |
+
current = tcp_rotation(tcp)
|
| 62 |
+
desired = current * Rotation.from_matrix(relative)
|
| 63 |
+
return position, desired.as_matrix(), float(prediction[9])
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def world_to_controller(position, rotation, gripper, tcp):
|
| 67 |
+
current = tcp_rotation(tcp)
|
| 68 |
+
desired = Rotation.from_matrix(rotation)
|
| 69 |
+
delta = (desired * current.inv()).as_euler("XYZ") / ROTATION_SCALE
|
| 70 |
+
translation = (position - tcp[:3]) / POSITION_SCALE
|
| 71 |
+
return np.clip(np.r_[translation, delta, gripper], -1, 1).astype(np.float32)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def decode_action(prediction, tcp, target, frame: ActionFrame):
|
| 75 |
+
return world_to_controller(
|
| 76 |
+
*prediction_to_world(prediction, tcp, target, frame), tcp
|
| 77 |
+
)
|
fair-comparison/p3x-liftslow-v1/code/lim/action_encoding.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Continuous 6D rotation targets, distinct from the low-level controller ABI."""
|
| 2 |
+
|
| 3 |
+
from typing import Any, Literal
|
| 4 |
+
|
| 5 |
+
import gymnasium as gym
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
from mani_skill.utils.geometry.rotation_conversions import (
|
| 9 |
+
euler_angles_to_matrix,
|
| 10 |
+
matrix_to_euler_angles,
|
| 11 |
+
)
|
| 12 |
+
from pydantic import BaseModel, ConfigDict
|
| 13 |
+
|
| 14 |
+
ActionEncoding = Literal["controller", "rotation6d"]
|
| 15 |
+
ROTATION_SCALE = -0.1 # Installed ManiSkill 3.0.1 CPU PDEEPoseController.
|
| 16 |
+
SIXD_SCALE = 0.1 # Affine label scaling; zero is the identity rotation.
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def encoded_dimension(controller_dimension, encoding):
|
| 20 |
+
if encoding == "controller":
|
| 21 |
+
return controller_dimension
|
| 22 |
+
if encoding != "rotation6d" or controller_dimension != 7:
|
| 23 |
+
raise ValueError("Rotation6D requires the seven-dimensional pose controller")
|
| 24 |
+
return 10
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def matrix_to_sixd(matrix):
|
| 28 |
+
identity = torch.eye(3, dtype=matrix.dtype, device=matrix.device)[:, :2]
|
| 29 |
+
return ((matrix[..., :, :2] - identity) / SIXD_SCALE).flatten(-2)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def sixd_to_matrix(sixd):
|
| 33 |
+
if not torch.isfinite(sixd).all():
|
| 34 |
+
raise ValueError("Nonfinite 6D rotation")
|
| 35 |
+
identity = torch.eye(3, dtype=sixd.dtype, device=sixd.device)
|
| 36 |
+
columns = sixd.reshape(*sixd.shape[:-1], 3, 2) * SIXD_SCALE + identity[:, :2]
|
| 37 |
+
first, second = columns[..., 0], columns[..., 1]
|
| 38 |
+
norm = torch.linalg.vector_norm(first, dim=-1, keepdim=True)
|
| 39 |
+
x = torch.where(norm > 1e-6, first / norm.clamp(min=1e-6), identity[:, 0])
|
| 40 |
+
second = second - (second * x).sum(-1, keepdim=True) * x
|
| 41 |
+
norm = torch.linalg.vector_norm(second, dim=-1, keepdim=True)
|
| 42 |
+
# Undefined zero/collinear network outputs get a deterministic orthogonal basis.
|
| 43 |
+
basis = identity[x.abs().argmin(-1)]
|
| 44 |
+
fallback = basis - (basis * x).sum(-1, keepdim=True) * x
|
| 45 |
+
fallback = fallback / torch.linalg.vector_norm(fallback, dim=-1, keepdim=True)
|
| 46 |
+
y = torch.where(norm > 1e-6, second / norm.clamp(min=1e-6), fallback)
|
| 47 |
+
return torch.stack([x, y, torch.linalg.cross(x, y, dim=-1)], dim=-1)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def controller_to_sixd(actions):
|
| 51 |
+
if actions.shape[-1] != 7:
|
| 52 |
+
raise ValueError("Expected seven-dimensional controller commands")
|
| 53 |
+
rotation = actions[..., 3:6]
|
| 54 |
+
rotation = rotation / torch.linalg.vector_norm(
|
| 55 |
+
rotation, dim=-1, keepdim=True
|
| 56 |
+
).clamp(min=1)
|
| 57 |
+
matrix = euler_angles_to_matrix(rotation * ROTATION_SCALE, "XYZ")
|
| 58 |
+
return torch.cat([actions[..., :3], matrix_to_sixd(matrix), actions[..., -1:]], -1)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def sixd_to_controller(actions):
|
| 62 |
+
if actions.shape[-1] != 10 or not torch.isfinite(actions).all():
|
| 63 |
+
raise ValueError("Expected finite ten-dimensional policy actions")
|
| 64 |
+
matrix = sixd_to_matrix(actions[..., 3:9])
|
| 65 |
+
# A 0.2-rad SO(3) ball avoids gimbal lock and contains all valid controller
|
| 66 |
+
# rotations: Euler norm<=0.1 implies angle<=sqrt(3)*0.1. Do not cap at0.1:
|
| 67 |
+
# some valid compound Euler commands have a geodesic angle slightly above0.1.
|
| 68 |
+
from mani_skill.utils.geometry.rotation_conversions import (
|
| 69 |
+
axis_angle_to_matrix,
|
| 70 |
+
matrix_to_axis_angle,
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
vector = matrix_to_axis_angle(matrix)
|
| 74 |
+
angle = torch.linalg.vector_norm(vector, dim=-1, keepdim=True)
|
| 75 |
+
bounded = axis_angle_to_matrix(vector * (0.2 / angle.clamp(min=1e-8)).clamp(max=1))
|
| 76 |
+
euler = matrix_to_euler_angles(bounded, "XYZ") / ROTATION_SCALE
|
| 77 |
+
euler = euler / torch.linalg.vector_norm(euler, dim=-1, keepdim=True).clamp(min=1)
|
| 78 |
+
return torch.cat([actions[..., :3], euler, actions[..., -1:]], -1)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def encode_dataset_actions(dataset, encoding):
|
| 82 |
+
if encoding == "controller":
|
| 83 |
+
return dataset
|
| 84 |
+
if encoding != "rotation6d" or not dataset.delta_control:
|
| 85 |
+
raise ValueError("Expected unnormalized delta-control demonstration labels")
|
| 86 |
+
# Precompute once. RGB, sample ordering, original H5, and temporal slices stay intact.
|
| 87 |
+
dataset.trajectories["actions"] = [
|
| 88 |
+
controller_to_sixd(a) for a in dataset.trajectories["actions"]
|
| 89 |
+
]
|
| 90 |
+
dataset.pad_action_arm = torch.zeros(9)
|
| 91 |
+
return dataset
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class EncodedEnvConfig(BaseModel, frozen=True):
|
| 95 |
+
model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid")
|
| 96 |
+
env: Any
|
| 97 |
+
"""Native evaluator transport; step receives ensembled policy coordinates."""
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class Rotation6DEnv:
|
| 101 |
+
def __init__(self, config: EncodedEnvConfig):
|
| 102 |
+
self.config = config
|
| 103 |
+
if config.env.action_space.shape[-1] != 7:
|
| 104 |
+
raise ValueError(
|
| 105 |
+
"Rotation6D transport requires a seven-dimensional controller"
|
| 106 |
+
)
|
| 107 |
+
self.action_space = gym.spaces.Box(
|
| 108 |
+
-np.inf, np.inf, (config.env.num_envs, 10), dtype=np.float32
|
| 109 |
+
)
|
| 110 |
+
self.single_action_space = gym.spaces.Box(
|
| 111 |
+
-np.inf, np.inf, (10,), dtype=np.float32
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
def __getattr__(self, name):
|
| 115 |
+
return getattr(self.config.env, name)
|
| 116 |
+
|
| 117 |
+
def step(self, actions):
|
| 118 |
+
# Called AFTER the pinned evaluator averages overlapping 10D predictions.
|
| 119 |
+
command = sixd_to_controller(torch.as_tensor(actions)).numpy()
|
| 120 |
+
return self.config.env.step(command)
|
fair-comparison/p3x-liftslow-v1/code/lim/action_objective.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pose ACT loss groups and binary-gripper inference semantics."""
|
| 2 |
+
|
| 3 |
+
from typing import Any, Literal
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
from pydantic import BaseModel, ConfigDict, PositiveFloat, model_validator
|
| 9 |
+
from torch import nn
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class ActionLossConfig(BaseModel, frozen=True):
|
| 13 |
+
model_config = ConfigDict(
|
| 14 |
+
extra="forbid", use_attribute_docstrings=True, allow_inf_nan=False
|
| 15 |
+
)
|
| 16 |
+
method: Literal["native", "gripper_bce", "group_balanced"] = "native"
|
| 17 |
+
"""Native 3:6:1 L1; 3:6:1 with gripper BCE; or equal means of the three L1 groups."""
|
| 18 |
+
position_axis_weights: tuple[PositiveFloat, PositiveFloat, PositiveFloat] = (
|
| 19 |
+
1.0,
|
| 20 |
+
1.0,
|
| 21 |
+
1.0,
|
| 22 |
+
)
|
| 23 |
+
"""XYZ absolute-error weights before averaging in group_balanced only.
|
| 24 |
+
|
| 25 |
+
Errors are in the coordinates supplied to the loss, including any fitted
|
| 26 |
+
normalization; this changes no labels, normalization or inference decoding.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
@model_validator(mode="after")
|
| 30 |
+
def check_position_weights(self):
|
| 31 |
+
if self.method != "group_balanced" and self.position_axis_weights != (
|
| 32 |
+
1.0,
|
| 33 |
+
1.0,
|
| 34 |
+
1.0,
|
| 35 |
+
):
|
| 36 |
+
raise ValueError("Non-default position weights require group_balanced")
|
| 37 |
+
return self
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def pose_reconstruction(prediction, actions, config: ActionLossConfig):
|
| 41 |
+
if prediction.shape != actions.shape or actions.shape[-1] != 10:
|
| 42 |
+
raise ValueError(
|
| 43 |
+
"Pose objectives require matching ten-dimensional action chunks"
|
| 44 |
+
)
|
| 45 |
+
position = F.l1_loss(prediction[..., :3], actions[..., :3])
|
| 46 |
+
rotation = F.l1_loss(prediction[..., 3:9], actions[..., 3:9])
|
| 47 |
+
groups = {"position_l1": position, "rotation_l1": rotation}
|
| 48 |
+
if config.method == "gripper_bce":
|
| 49 |
+
labels = (actions[..., -1] + 1) / 2
|
| 50 |
+
gripper = F.binary_cross_entropy_with_logits(prediction[..., -1], labels)
|
| 51 |
+
reconstruction = 0.3 * position + 0.6 * rotation + 0.1 * gripper
|
| 52 |
+
groups["gripper_bce"] = gripper
|
| 53 |
+
else:
|
| 54 |
+
gripper = F.l1_loss(prediction[..., -1], actions[..., -1])
|
| 55 |
+
groups["gripper_l1"] = gripper
|
| 56 |
+
if config.method == "group_balanced":
|
| 57 |
+
# Reuse the original tensor/graph at the default, preserving the
|
| 58 |
+
# exact historical loss and gradients rather than multiplying by 1.
|
| 59 |
+
weighted_position = position
|
| 60 |
+
if config.position_axis_weights != (1.0, 1.0, 1.0):
|
| 61 |
+
weighted_position = (
|
| 62 |
+
(prediction[..., :3] - actions[..., :3]).abs()
|
| 63 |
+
* prediction.new_tensor(config.position_axis_weights)
|
| 64 |
+
).mean()
|
| 65 |
+
groups["weighted_position_l1"] = weighted_position
|
| 66 |
+
reconstruction = (weighted_position + rotation + gripper) / 3
|
| 67 |
+
else:
|
| 68 |
+
reconstruction = F.l1_loss(prediction, actions)
|
| 69 |
+
return {"reconstruction": reconstruction, **groups}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def validate_binary_gripper(dataset):
|
| 73 |
+
"""Validate every unpadded training label once; padding holds its final label."""
|
| 74 |
+
for actions in dataset.trajectories["actions"]:
|
| 75 |
+
gripper = actions[..., -1]
|
| 76 |
+
if not torch.all((gripper == -1) | (gripper == 1)):
|
| 77 |
+
raise ValueError("Binary gripper supervision requires exactly -1/+1 labels")
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class BinaryGripperModelConfig(BaseModel, frozen=True):
|
| 81 |
+
model_config = ConfigDict(
|
| 82 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 83 |
+
)
|
| 84 |
+
model: Any
|
| 85 |
+
"""Native CVAE; the last output coordinate is a logit during training."""
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class BinaryGripperModel(nn.Module):
|
| 89 |
+
def __init__(self, config: BinaryGripperModelConfig):
|
| 90 |
+
super().__init__()
|
| 91 |
+
self.config = config
|
| 92 |
+
self.base = config.model
|
| 93 |
+
|
| 94 |
+
def forward(self, obs, actions=None):
|
| 95 |
+
prediction, latent = self.base(obs, actions)
|
| 96 |
+
if actions is None:
|
| 97 |
+
# Native temporal aggregation averages 2*p(open)-1, equivalent to
|
| 98 |
+
# averaging probabilities. Do not threshold each chunk in isolation.
|
| 99 |
+
prediction = torch.cat(
|
| 100 |
+
[prediction[..., :-1], 2 * prediction[..., -1:].sigmoid() - 1], dim=-1
|
| 101 |
+
)
|
| 102 |
+
return prediction, latent
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class BinaryGripperEnvConfig(BaseModel, frozen=True):
|
| 106 |
+
model_config = ConfigDict(
|
| 107 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 108 |
+
)
|
| 109 |
+
env: Any
|
| 110 |
+
"""Physical environment receiving controller commands after temporal averaging."""
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class BinaryGripperEnv:
|
| 114 |
+
def __init__(self, config: BinaryGripperEnvConfig):
|
| 115 |
+
self.config = config
|
| 116 |
+
self.commands = 0
|
| 117 |
+
self.open_commands = 0
|
| 118 |
+
self.close_commands = 0
|
| 119 |
+
self.switches = 0
|
| 120 |
+
self.previous_gripper = None
|
| 121 |
+
|
| 122 |
+
def __getattr__(self, name):
|
| 123 |
+
return getattr(self.config.env, name)
|
| 124 |
+
|
| 125 |
+
def reset(self, *args, **kwargs):
|
| 126 |
+
self.previous_gripper = None
|
| 127 |
+
return self.config.env.reset(*args, **kwargs)
|
| 128 |
+
|
| 129 |
+
def step(self, action):
|
| 130 |
+
command = np.array(action, copy=True)
|
| 131 |
+
score = command[..., -1]
|
| 132 |
+
if not np.isfinite(score).all():
|
| 133 |
+
raise ValueError("Nonfinite ensembled gripper probability")
|
| 134 |
+
gripper = np.where(score >= 0, 1.0, -1.0)
|
| 135 |
+
command[..., -1] = gripper # p(open)>=0.5 opens, including exact ties.
|
| 136 |
+
self.commands += gripper.size
|
| 137 |
+
self.open_commands += int((gripper == 1).sum())
|
| 138 |
+
self.close_commands += int((gripper == -1).sum())
|
| 139 |
+
if self.previous_gripper is not None:
|
| 140 |
+
self.switches += int(
|
| 141 |
+
(
|
| 142 |
+
np.isfinite(self.previous_gripper)
|
| 143 |
+
& (self.previous_gripper != gripper)
|
| 144 |
+
).sum()
|
| 145 |
+
)
|
| 146 |
+
result = self.config.env.step(command)
|
| 147 |
+
# Vector SAME_STEP autoreset starts a new episode after this last command.
|
| 148 |
+
done = np.asarray(result[2]) | np.asarray(result[3])
|
| 149 |
+
self.previous_gripper = np.where(done, np.nan, gripper)
|
| 150 |
+
return result
|
| 151 |
+
|
| 152 |
+
def diagnostics(self):
|
| 153 |
+
return {
|
| 154 |
+
"commands": self.commands,
|
| 155 |
+
"open_commands": self.open_commands,
|
| 156 |
+
"close_commands": self.close_commands,
|
| 157 |
+
"within_episode_switches": self.switches,
|
| 158 |
+
"rule": "average p(open) with native weights; >=0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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dense pose targets with one fixed reference per observation/chunk."""
|
| 2 |
+
|
| 3 |
+
from typing import Literal
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from mani_skill.utils.geometry.rotation_conversions import quaternion_to_matrix
|
| 7 |
+
|
| 8 |
+
from lim.action_encoding import controller_to_sixd, matrix_to_sixd, sixd_to_matrix
|
| 9 |
+
|
| 10 |
+
RELATIVE_POSE_CONTRACT = {
|
| 11 |
+
"version": "chunk_start_pose6d_v1",
|
| 12 |
+
"position": "(world_command_target - observed_chunk_start_tcp) / 0.1",
|
| 13 |
+
"rotation": "scaled6d(R_world_command_target @ R_chunk_start_tcp.T)",
|
| 14 |
+
"gripper": "original continuous command, not a relative offset",
|
| 15 |
+
"target_source": "each saved pre-action TCP composed with its own controller command",
|
| 16 |
+
"padding": "terminal measured TCP pose and last gripper command",
|
| 17 |
+
"normalization_population": "all valid anchor/future-target pairs, no terminal padding",
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
ABSOLUTE_POSE_CONTRACT = {
|
| 21 |
+
"version": "absolute_world_pose6d_v1",
|
| 22 |
+
"position": "world_command_target / 0.1, no anchor subtraction",
|
| 23 |
+
"rotation": "scaled6d(R_world_command_target), no anchor rotation removed",
|
| 24 |
+
"gripper": "original continuous command, not a relative offset",
|
| 25 |
+
"target_source": "each saved pre-action TCP composed with its own controller command",
|
| 26 |
+
"padding": "terminal measured TCP pose and last gripper command",
|
| 27 |
+
"normalization_population": "all valid future targets, no terminal padding",
|
| 28 |
+
"isolation": "identical to chunk_start_pose6d_v1 except the label anchor; the"
|
| 29 |
+
" controller boundary still converts against the real measured TCP",
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
ChunkAnchor = Literal["chunk_start_tcp", "identity"]
|
| 33 |
+
ChunkPoseSupervision = Literal[
|
| 34 |
+
"dense", "future_endpoint", "current_endpoint", "phase_segments", "future_waypoint"
|
| 35 |
+
]
|
| 36 |
+
ChunkGripperSupervision = Literal["future", "current"]
|
| 37 |
+
ChunkPadding = Literal["terminal", "current_target"]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def pose_target_contract(
|
| 41 |
+
anchor: ChunkAnchor,
|
| 42 |
+
supervision: ChunkPoseSupervision,
|
| 43 |
+
gripper: ChunkGripperSupervision = "future",
|
| 44 |
+
padding: ChunkPadding = "terminal",
|
| 45 |
+
normalization_population: Literal["dense", "supervised"] = "dense",
|
| 46 |
+
label_offset: int = 0,
|
| 47 |
+
waypoint_threshold_m: float | None = None,
|
| 48 |
+
):
|
| 49 |
+
"""Persist target semantics for the audited StackCube world-frame dataset.
|
| 50 |
+
|
| 51 |
+
An identity anchor keeps coordinates in the stored TCP/keyframe frame; that
|
| 52 |
+
frame is world in this simulator, not a universal property of absolute poses.
|
| 53 |
+
Existing dense-population recipes retain their checkpoint contract exactly.
|
| 54 |
+
"""
|
| 55 |
+
if anchor not in ("chunk_start_tcp", "identity"):
|
| 56 |
+
raise ValueError(f"Unknown chunk anchor mode: {anchor}")
|
| 57 |
+
if (supervision == "future_waypoint") != (waypoint_threshold_m is not None):
|
| 58 |
+
raise ValueError("Exactly the waypoint supervision carries a waypoint threshold")
|
| 59 |
+
if supervision == "future_waypoint":
|
| 60 |
+
if (anchor, gripper, padding, normalization_population, label_offset) != (
|
| 61 |
+
"chunk_start_tcp", "future", "terminal", "dense", 0
|
| 62 |
+
):
|
| 63 |
+
raise ValueError("Waypoint labels use the TCP anchor and default label fields")
|
| 64 |
+
return {
|
| 65 |
+
**RELATIVE_POSE_CONTRACT,
|
| 66 |
+
"version": f"chunk_start_pose6d_future_waypoint_eta{waypoint_threshold_m:g}_v1",
|
| 67 |
+
"pose_supervision": supervision,
|
| 68 |
+
"waypoint_threshold_m": waypoint_threshold_m,
|
| 69 |
+
"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",
|
| 70 |
+
"gripper": "original future dense gripper command at each slot, unchanged",
|
| 71 |
+
"normalization_population": "original dense valid anchor/future-target pairs, no terminal padding",
|
| 72 |
+
}
|
| 73 |
+
if supervision == "phase_segments":
|
| 74 |
+
if (anchor, gripper, padding, normalization_population, label_offset) != (
|
| 75 |
+
"chunk_start_tcp", "future", "terminal", "dense", 0
|
| 76 |
+
):
|
| 77 |
+
raise ValueError("Phase segments use the TCP anchor and default label fields")
|
| 78 |
+
return {
|
| 79 |
+
**RELATIVE_POSE_CONTRACT,
|
| 80 |
+
"version": "chunk_start_pose6d_phase_segments_v1",
|
| 81 |
+
"pose_supervision": supervision,
|
| 82 |
+
"target_source": "slot0 current primitive endpoint, slot1 next primitive endpoint (last primitive repeats)",
|
| 83 |
+
"gripper": "each slot carries its own primitive gripper command",
|
| 84 |
+
"padding": "none; both slots always exist",
|
| 85 |
+
"switch": "remaining steps in the current primitive, min(steps,30)/30, from decoder query zero",
|
| 86 |
+
"normalization_population": "frozen statistics from a completed training; never refit",
|
| 87 |
+
}
|
| 88 |
+
if label_offset:
|
| 89 |
+
if label_offset < 0 or supervision != "future_endpoint" or anchor != "chunk_start_tcp":
|
| 90 |
+
raise ValueError("Lookahead offsets apply to TCP-anchored future endpoints")
|
| 91 |
+
original = pose_target_contract(
|
| 92 |
+
anchor, supervision, gripper, padding, normalization_population
|
| 93 |
+
)
|
| 94 |
+
return {
|
| 95 |
+
**original,
|
| 96 |
+
"version": original["version"] + f"_lookahead{label_offset}_v1",
|
| 97 |
+
"label_offset": label_offset,
|
| 98 |
+
"target_source": f"primitive endpoint and gripper at time t+{label_offset}+i",
|
| 99 |
+
"normalization_population": "frozen statistics from a completed training; never refit",
|
| 100 |
+
}
|
| 101 |
+
if normalization_population == "supervised":
|
| 102 |
+
if (
|
| 103 |
+
supervision != "current_endpoint"
|
| 104 |
+
or gripper != "current"
|
| 105 |
+
or padding != "current_target"
|
| 106 |
+
):
|
| 107 |
+
raise ValueError(
|
| 108 |
+
"Supervised normalization requires repeated complete current-target endpoint labels"
|
| 109 |
+
)
|
| 110 |
+
original = pose_target_contract(anchor, supervision, gripper, padding)
|
| 111 |
+
return {
|
| 112 |
+
**original,
|
| 113 |
+
"version": original["version"] + "_supervised_population_v1",
|
| 114 |
+
"anchor": anchor,
|
| 115 |
+
"normalization_population": "query-zero complete current endpoint once per original observation; no future-pair or padding reweighting",
|
| 116 |
+
}
|
| 117 |
+
if normalization_population != "dense":
|
| 118 |
+
raise ValueError("Unknown chunk normalization population")
|
| 119 |
+
if padding == "current_target":
|
| 120 |
+
if supervision != "current_endpoint" or gripper != "current":
|
| 121 |
+
raise ValueError(
|
| 122 |
+
"Current-target padding requires current endpoint and gripper"
|
| 123 |
+
)
|
| 124 |
+
original = pose_target_contract(anchor, supervision, gripper)
|
| 125 |
+
return {
|
| 126 |
+
**original,
|
| 127 |
+
"version": original["version"] + "_current_padding_v1",
|
| 128 |
+
"padding": "repeat current observation complete endpoint target in all out-of-range slots",
|
| 129 |
+
"gripper": "current observation command repeated in every slot including padding",
|
| 130 |
+
}
|
| 131 |
+
if padding != "terminal":
|
| 132 |
+
raise ValueError("Unknown chunk padding")
|
| 133 |
+
if gripper == "current":
|
| 134 |
+
original = pose_target_contract(anchor, supervision)
|
| 135 |
+
return {
|
| 136 |
+
**original,
|
| 137 |
+
"version": original["version"] + "_current_gripper_v1",
|
| 138 |
+
"gripper": "current observation command repeated in valid slots; terminal padding unchanged",
|
| 139 |
+
"gripper_supervision": "current",
|
| 140 |
+
}
|
| 141 |
+
if gripper != "future":
|
| 142 |
+
raise ValueError("Unknown chunk gripper supervision")
|
| 143 |
+
base = (
|
| 144 |
+
RELATIVE_POSE_CONTRACT
|
| 145 |
+
if anchor == "chunk_start_tcp"
|
| 146 |
+
else ABSOLUTE_POSE_CONTRACT
|
| 147 |
+
)
|
| 148 |
+
if supervision == "dense":
|
| 149 |
+
return base
|
| 150 |
+
if supervision not in ("future_endpoint", "current_endpoint"):
|
| 151 |
+
raise ValueError("Unknown endpoint supervision")
|
| 152 |
+
return {
|
| 153 |
+
**base,
|
| 154 |
+
"version": (
|
| 155 |
+
f"chunk_start_pose6d_{supervision}_v1"
|
| 156 |
+
if anchor == "chunk_start_tcp"
|
| 157 |
+
else f"absolute_world_pose6d_{supervision}_v1"
|
| 158 |
+
),
|
| 159 |
+
"pose_supervision": supervision,
|
| 160 |
+
"target_source": (
|
| 161 |
+
"primitive endpoint at each future action time"
|
| 162 |
+
if supervision == "future_endpoint"
|
| 163 |
+
else "current observation primitive endpoint repeated in valid future slots"
|
| 164 |
+
),
|
| 165 |
+
"gripper": "original future dense gripper command at each slot, unchanged",
|
| 166 |
+
"normalization_population": "original dense valid anchor/future-target pairs, no terminal padding",
|
| 167 |
+
**(
|
| 168 |
+
{
|
| 169 |
+
"anchor": "identity",
|
| 170 |
+
"coordinate_frame": "stored TCP/keyframe frame, world in this audited StackCube dataset",
|
| 171 |
+
}
|
| 172 |
+
if anchor == "identity"
|
| 173 |
+
else {}
|
| 174 |
+
),
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def resolve_anchor(anchor, mode: ChunkAnchor):
|
| 179 |
+
"""Pick the label origin; identity preserves the stored pose coordinate frame.
|
| 180 |
+
|
| 181 |
+
Only the label/restore frame changes. Converting an absolute goal into a physical
|
| 182 |
+
controller delta always uses the real measured TCP, so this stays a pure
|
| 183 |
+
representation switch rather than a change of what is commanded.
|
| 184 |
+
"""
|
| 185 |
+
if mode == "chunk_start_tcp":
|
| 186 |
+
return anchor
|
| 187 |
+
if mode != "identity":
|
| 188 |
+
raise ValueError(f"Unknown chunk anchor mode: {mode}")
|
| 189 |
+
shape = (*anchor.shape[:-1], 7)
|
| 190 |
+
fixed = torch.zeros(shape, dtype=anchor.dtype, device=anchor.device)
|
| 191 |
+
fixed[..., 3] = 1.0 # identity quaternion, zero translation
|
| 192 |
+
return fixed
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def controller_pose_targets(actions, tcp):
|
| 196 |
+
"""Reconstruct actual CPU controller goals in audited world-aligned root axes."""
|
| 197 |
+
if actions.shape[-1] != 7 or tcp.shape[-1] != 7:
|
| 198 |
+
raise ValueError("Expected controller7 and world TCP7")
|
| 199 |
+
delta = controller_to_sixd(actions)
|
| 200 |
+
rotation = sixd_to_matrix(delta[..., 3:9]) @ quaternion_to_matrix(tcp[..., 3:])
|
| 201 |
+
return torch.cat(
|
| 202 |
+
[
|
| 203 |
+
tcp[..., :3] + actions[..., :3].clamp(-1, 1) * 0.1,
|
| 204 |
+
matrix_to_sixd(rotation),
|
| 205 |
+
actions[..., -1:],
|
| 206 |
+
],
|
| 207 |
+
-1,
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def world_to_chunk_relative(target, anchor):
|
| 212 |
+
"""World target10 -> fixed-origin translation and root-aligned relative rotation."""
|
| 213 |
+
rotation = sixd_to_matrix(target[..., 3:9]) @ quaternion_to_matrix(
|
| 214 |
+
anchor[..., 3:]
|
| 215 |
+
).transpose(-1, -2)
|
| 216 |
+
return torch.cat(
|
| 217 |
+
[
|
| 218 |
+
(target[..., :3] - anchor[..., :3]) / 0.1,
|
| 219 |
+
matrix_to_sixd(rotation),
|
| 220 |
+
target[..., -1:],
|
| 221 |
+
],
|
| 222 |
+
-1,
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def chunk_relative_to_world(target, anchor):
|
| 227 |
+
"""Restore every goal using the SAME anchor; never integrate or clip offsets."""
|
| 228 |
+
rotation = sixd_to_matrix(target[..., 3:9]) @ quaternion_to_matrix(anchor[..., 3:])
|
| 229 |
+
return torch.cat(
|
| 230 |
+
[
|
| 231 |
+
anchor[..., :3] + target[..., :3] * 0.1,
|
| 232 |
+
matrix_to_sixd(rotation),
|
| 233 |
+
target[..., -1:],
|
| 234 |
+
],
|
| 235 |
+
-1,
|
| 236 |
+
)
|
fair-comparison/p3x-liftslow-v1/code/lim/chunk_endpoint.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Nominal endpoint of dense delta commands under perfect per-step tracking.
|
| 2 |
+
|
| 3 |
+
This is a geometric diagnostic, not a dynamics rollout: the trained deltas use
|
| 4 |
+
future measured TCP poses, which are unavailable when skipping intermediate steps.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from mani_skill.utils.geometry.rotation_conversions import (
|
| 9 |
+
euler_angles_to_matrix,
|
| 10 |
+
quaternion_to_matrix,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
from lim.action_encoding import ROTATION_SCALE, matrix_to_sixd, sixd_to_controller
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def check_endpoint_controller(config):
|
| 17 |
+
"""Fail if the source controller differs from the audited CPU Panda contract."""
|
| 18 |
+
if not (
|
| 19 |
+
config.frame == "root_translation:root_aligned_body_rotation"
|
| 20 |
+
and config.use_delta
|
| 21 |
+
and not config.use_target
|
| 22 |
+
and config.normalize_action
|
| 23 |
+
and config.root_link_name is None
|
| 24 |
+
and config.pos_lower == -0.1
|
| 25 |
+
and config.pos_upper == 0.1
|
| 26 |
+
and config.rot_lower == ROTATION_SCALE
|
| 27 |
+
):
|
| 28 |
+
raise ValueError(
|
| 29 |
+
"Dense endpoint requires the audited Panda delta-pose controller"
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def dense_chunk_endpoint(chunk, current_tcp, robot_root):
|
| 34 |
+
"""Return world target10 and decoded commands; keep ONLY the last gripper.
|
| 35 |
+
|
| 36 |
+
Commands are composed in robot-root coordinates with left-multiplied
|
| 37 |
+
rotations, matching ManiSkill CPU's target construction. Rotations are
|
| 38 |
+
decoded through the same 6D adapter and controller clipping as native dense
|
| 39 |
+
execution. No simulation, future feedback, object poses or IK are used.
|
| 40 |
+
"""
|
| 41 |
+
chunk = torch.as_tensor(chunk, dtype=torch.float32)
|
| 42 |
+
current = torch.as_tensor(current_tcp, dtype=chunk.dtype, device=chunk.device)
|
| 43 |
+
root = torch.as_tensor(robot_root, dtype=chunk.dtype, device=chunk.device)
|
| 44 |
+
if chunk.ndim != 2 or chunk.shape[1] != 10 or len(chunk) == 0:
|
| 45 |
+
raise ValueError("Expected nonempty H x 10 dense delta predictions")
|
| 46 |
+
for pose in (current, root):
|
| 47 |
+
if pose.shape != (7,) or not torch.isfinite(pose).all():
|
| 48 |
+
raise ValueError("Expected finite world xyz,wxyz poses")
|
| 49 |
+
if not torch.isclose(pose[3:].norm(), pose.new_tensor(1.0), atol=1e-4):
|
| 50 |
+
raise ValueError("Expected unit pose quaternion")
|
| 51 |
+
commands = sixd_to_controller(chunk).clone()
|
| 52 |
+
commands[:, :3] = commands[:, :3].clamp(-1, 1)
|
| 53 |
+
commands[:, -1] = commands[:, -1].clamp(-1, 1)
|
| 54 |
+
root_rotation = quaternion_to_matrix(root[3:])
|
| 55 |
+
position = root_rotation.T @ (current[:3] - root[:3])
|
| 56 |
+
rotation = root_rotation.T @ quaternion_to_matrix(current[3:])
|
| 57 |
+
for command in commands:
|
| 58 |
+
position = position + 0.1 * command[:3]
|
| 59 |
+
rotation = (
|
| 60 |
+
euler_angles_to_matrix(command[3:6] * ROTATION_SCALE, "XYZ") @ rotation
|
| 61 |
+
)
|
| 62 |
+
target = torch.cat(
|
| 63 |
+
[
|
| 64 |
+
root[:3] + root_rotation @ position,
|
| 65 |
+
matrix_to_sixd(root_rotation @ rotation),
|
| 66 |
+
commands[-1, -1:],
|
| 67 |
+
]
|
| 68 |
+
)
|
| 69 |
+
return target, commands
|
fair-comparison/p3x-liftslow-v1/code/lim/chunk_phase.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Predicted primitive boundaries in fixed-anchor action chunks, without an FSM."""
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def phase_prefix(phases):
|
| 7 |
+
"""Count the first constant-label run; no observed change means horizon, not arrival."""
|
| 8 |
+
phases = torch.as_tensor(phases)
|
| 9 |
+
if (
|
| 10 |
+
phases.ndim != 1
|
| 11 |
+
or len(phases) != 30
|
| 12 |
+
or not ((phases >= 0) & (phases < 6)).all()
|
| 13 |
+
):
|
| 14 |
+
raise ValueError("Expected 30 predicted primitive indices in [0, 5]")
|
| 15 |
+
changes = torch.nonzero(phases != phases[0]).flatten()
|
| 16 |
+
return int(changes[0]) if len(changes) else 30
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def chunk_selection(logits, mode):
|
| 20 |
+
if logits.shape != (30, 6) or not torch.isfinite(logits).all():
|
| 21 |
+
raise ValueError("Expected finite prior logits with shape 30 x 6")
|
| 22 |
+
if mode not in ("full", "boundary", "endpoint"):
|
| 23 |
+
raise ValueError("Unknown phase chunk execution mode")
|
| 24 |
+
labels = logits.argmax(-1)
|
| 25 |
+
prefix = phase_prefix(labels)
|
| 26 |
+
return {
|
| 27 |
+
"phase_labels": labels.tolist(),
|
| 28 |
+
"phase_prefix_length": prefix,
|
| 29 |
+
"boundary_kind": "phase_change" if prefix < 30 else "horizon",
|
| 30 |
+
"consume_length": 30 if mode == "full" else prefix,
|
| 31 |
+
"selected_index": (30 if mode == "full" else prefix) - 1,
|
| 32 |
+
}
|
fair-comparison/p3x-liftslow-v1/code/lim/chunk_switch.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Remaining-steps regression for two-segment phase endpoint outputs."""
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from pydantic import BaseModel, ConfigDict
|
| 5 |
+
from torch import nn
|
| 6 |
+
|
| 7 |
+
SWITCH_HORIZON = 30
|
| 8 |
+
"""Remaining steps are clipped to this horizon and supervised as a fraction of it."""
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ChunkSwitchHeadConfig(BaseModel, frozen=True):
|
| 12 |
+
model_config = ConfigDict(
|
| 13 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 14 |
+
)
|
| 15 |
+
action_head: nn.Module
|
| 16 |
+
"""Existing action projection (optionally wrapped by the phase head)."""
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class ChunkSwitchHead(nn.Module):
|
| 20 |
+
def __init__(self, config: ChunkSwitchHeadConfig):
|
| 21 |
+
super().__init__()
|
| 22 |
+
self.config = config
|
| 23 |
+
self.action = config.action_head
|
| 24 |
+
linear = getattr(self.action, "action", self.action)
|
| 25 |
+
if not isinstance(linear, nn.Linear):
|
| 26 |
+
raise ValueError("Switch head wraps a linear action projection")
|
| 27 |
+
device = linear.weight.device
|
| 28 |
+
devices = [device.index] if device.type == "cuda" else []
|
| 29 |
+
# Preserve subsequent EMA initialization and sampling/dropout RNG.
|
| 30 |
+
with torch.random.fork_rng(devices=devices):
|
| 31 |
+
self.switch = nn.Linear(
|
| 32 |
+
linear.in_features,
|
| 33 |
+
1,
|
| 34 |
+
device=device,
|
| 35 |
+
dtype=linear.weight.dtype,
|
| 36 |
+
)
|
| 37 |
+
self.switch_fraction = None
|
| 38 |
+
|
| 39 |
+
def forward(self, features):
|
| 40 |
+
if features.ndim != 3 or features.shape[1] < 1:
|
| 41 |
+
raise ValueError("Expected ACT decoder features batch x query x hidden")
|
| 42 |
+
actions = self.action(features)
|
| 43 |
+
self.switch_fraction = self.switch(features[:, 0]).squeeze(-1)
|
| 44 |
+
return actions
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def read_switch_fraction(model):
|
| 48 |
+
"""Raw remaining-steps fraction from the latest forward, not clipped or rerun."""
|
| 49 |
+
heads = [part for part in model.modules() if isinstance(part, ChunkSwitchHead)]
|
| 50 |
+
if len(heads) != 1:
|
| 51 |
+
raise ValueError("Expected exactly one enabled chunk switch head")
|
| 52 |
+
fraction = heads[0].switch_fraction
|
| 53 |
+
if fraction is None:
|
| 54 |
+
raise RuntimeError("Switch fraction requires a completed policy forward")
|
| 55 |
+
return fraction
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def switch_steps(fraction):
|
| 59 |
+
"""Predicted steps until the second segment applies, rounded and bounded."""
|
| 60 |
+
return torch.round(fraction.clamp(0, 1) * SWITCH_HORIZON).long()
|
fair-comparison/p3x-liftslow-v1/code/lim/collect_keyposes.py
ADDED
|
@@ -0,0 +1,592 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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and map labels through pose replay.
|
| 2 |
+
|
| 3 |
+
The upstream expert is unchanged. Its planner factory is temporarily wrapped in
|
| 4 |
+
this single-process CLI to observe executed primitives; trial plans are excluded.
|
| 5 |
+
An optional task-irrelevant perturbation (segment time scaling, pauses, detours
|
| 6 |
+
through an offset via-point and tapered joint jitter) changes how each planned
|
| 7 |
+
move is executed; primitive targets, and so keypose labels, stay the expert's.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import hashlib
|
| 11 |
+
import importlib.metadata
|
| 12 |
+
import inspect
|
| 13 |
+
import json
|
| 14 |
+
import time
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Any
|
| 17 |
+
from unittest.mock import patch
|
| 18 |
+
|
| 19 |
+
import gymnasium as gym
|
| 20 |
+
import mani_skill.envs # noqa: F401
|
| 21 |
+
import numpy as np
|
| 22 |
+
import sapien
|
| 23 |
+
import torch
|
| 24 |
+
from mani_skill.utils import common
|
| 25 |
+
from mani_skill.utils.wrappers.record import RecordEpisode
|
| 26 |
+
from pydantic import (
|
| 27 |
+
BaseModel,
|
| 28 |
+
ConfigDict,
|
| 29 |
+
Field,
|
| 30 |
+
NonNegativeFloat,
|
| 31 |
+
NonNegativeInt,
|
| 32 |
+
PositiveFloat,
|
| 33 |
+
PositiveInt,
|
| 34 |
+
SkipValidation,
|
| 35 |
+
)
|
| 36 |
+
from pydantic_settings import CliApp
|
| 37 |
+
|
| 38 |
+
from lim.keypose_data import (
|
| 39 |
+
AnnotationConfig,
|
| 40 |
+
AuditConfig,
|
| 41 |
+
KeyposeSegment,
|
| 42 |
+
audit_dataset,
|
| 43 |
+
write_annotations,
|
| 44 |
+
)
|
| 45 |
+
from lim.replay_pose import (
|
| 46 |
+
TargetReplayConfig,
|
| 47 |
+
replace_last,
|
| 48 |
+
replay_targets,
|
| 49 |
+
tree_first,
|
| 50 |
+
)
|
| 51 |
+
from lim.tasks import expert_module
|
| 52 |
+
|
| 53 |
+
# These are the native StackCube expert's primitives, not an invented phase split.
|
| 54 |
+
STACK_CUBE_SEQUENCE = (
|
| 55 |
+
("move", "approach"),
|
| 56 |
+
("move", "grasp_pose"),
|
| 57 |
+
("close", "close_gripper"),
|
| 58 |
+
("move", "lift"),
|
| 59 |
+
("move", "place_pose"),
|
| 60 |
+
("open", "open_gripper"),
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
FREE_SPACE = ("approach", "place_pose")
|
| 64 |
+
"""Moves away from contact: the reach above cube A and the transport onto B."""
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class PerturbationConfig(BaseModel, frozen=True):
|
| 68 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 69 |
+
time_scale: tuple[PositiveFloat, PositiveFloat] = (1.0, 1.0)
|
| 70 |
+
"""Log-uniform range of each move's duration factor (>1 slower)."""
|
| 71 |
+
pause_probability: float = Field(default=0.0, ge=0, le=1)
|
| 72 |
+
"""Chance that a move holds its current command mid-way."""
|
| 73 |
+
pause_steps: tuple[PositiveInt, PositiveInt] = (3, 10)
|
| 74 |
+
"""Inclusive range of held steps."""
|
| 75 |
+
detour_probability: float = Field(default=0.0, ge=0, le=1)
|
| 76 |
+
"""Chance that a free-space move first passes an offset via-point."""
|
| 77 |
+
detour_m: NonNegativeFloat = 0.0
|
| 78 |
+
"""Sideways offset of the via-point from the straight path's midpoint
|
| 79 |
+
(plus half of it upwards)."""
|
| 80 |
+
jitter_rad: NonNegativeFloat = 0.0
|
| 81 |
+
"""Std of smooth joint noise on free-space moves, tapered to zero at both ends."""
|
| 82 |
+
jitter_smoothing_steps: PositiveFloat = 5.0
|
| 83 |
+
"""Gaussian smoothing width of the joint noise, in control steps."""
|
| 84 |
+
seed: NonNegativeInt = 20261005
|
| 85 |
+
"""Perturbation stream; each attempt uses (seed, scene seed)."""
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
PERTURBATION_LEVELS = {
|
| 89 |
+
1: PerturbationConfig(time_scale=(0.8, 1.25), pause_probability=0.2,
|
| 90 |
+
detour_probability=0.2, detour_m=0.03, jitter_rad=0.005),
|
| 91 |
+
2: PerturbationConfig(time_scale=(0.67, 1.5), pause_probability=0.4,
|
| 92 |
+
detour_probability=0.4, detour_m=0.05, jitter_rad=0.01),
|
| 93 |
+
3: PerturbationConfig(time_scale=(0.5, 2.0), pause_probability=0.6,
|
| 94 |
+
detour_probability=0.6, detour_m=0.08, jitter_rad=0.02),
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class CollectionConfig(BaseModel, frozen=True):
|
| 99 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 100 |
+
output_dir: Path
|
| 101 |
+
"""New dataset directory; existing files are never overwritten."""
|
| 102 |
+
episodes: PositiveInt = 100
|
| 103 |
+
"""Number of successful pose demonstrations to retain."""
|
| 104 |
+
seed_start: NonNegativeInt = 71000
|
| 105 |
+
"""First fresh scene seed, incremented once per attempt without retries."""
|
| 106 |
+
max_attempts: PositiveInt = 150
|
| 107 |
+
"""Finite attempt budget including planner and converted-execution failures."""
|
| 108 |
+
save_video: bool = False
|
| 109 |
+
"""Record successful raw-expert videos for a small visual audit."""
|
| 110 |
+
perturbation_level: int = Field(default=0, ge=0, le=3)
|
| 111 |
+
"""0 keeps the native execution; 1-3 apply PERTURBATION_LEVELS."""
|
| 112 |
+
max_episode_steps: PositiveInt = 200
|
| 113 |
+
"""Environment time limit; demonstrations longer than it are rejected."""
|
| 114 |
+
task: str = "StackCube-v1"
|
| 115 |
+
"""ManiSkill task with an annotated native expert (lim.tasks)."""
|
| 116 |
+
expert: str | None = None
|
| 117 |
+
"""Module with the expert's solve() (e.g. lim.expert_stack_pyramid);
|
| 118 |
+
None uses the task's native expert (lim.tasks)."""
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class PlannerConfig(BaseModel, frozen=True):
|
| 122 |
+
model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid")
|
| 123 |
+
planner: Any
|
| 124 |
+
"""Native Panda planner; all motions are executed by this object."""
|
| 125 |
+
recorder: Any
|
| 126 |
+
"""RecordEpisode supplies the actual dense-action clock."""
|
| 127 |
+
segments: SkipValidation[list[KeyposeSegment]]
|
| 128 |
+
"""Append-only events for this one expert attempt."""
|
| 129 |
+
sequence: tuple[tuple[str, str], ...] | None = STACK_CUBE_SEQUENCE
|
| 130 |
+
"""Expected (kind, name) primitives; None records whatever the expert
|
| 131 |
+
executes, named by kind and position."""
|
| 132 |
+
perturbation: PerturbationConfig | None = None
|
| 133 |
+
rng: SkipValidation[Any] = None
|
| 134 |
+
"""numpy Generator for this attempt's perturbation draws."""
|
| 135 |
+
log: SkipValidation[list] = Field(default_factory=list)
|
| 136 |
+
"""One record per executed move describing the applied perturbation."""
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class PlanningFailure(RuntimeError):
|
| 140 |
+
pass
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def pose_vector(pose):
|
| 144 |
+
return tuple(
|
| 145 |
+
float(x)
|
| 146 |
+
for x in np.r_[
|
| 147 |
+
common.to_numpy(pose.p).reshape(3), common.to_numpy(pose.q).reshape(4)
|
| 148 |
+
]
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class AnnotatedPlanner:
|
| 153 |
+
sequence = STACK_CUBE_SEQUENCE
|
| 154 |
+
|
| 155 |
+
def __init__(self, config: PlannerConfig):
|
| 156 |
+
self.config = config
|
| 157 |
+
|
| 158 |
+
def name(self, index, kind):
|
| 159 |
+
if self.config.sequence is None:
|
| 160 |
+
return f"{kind}_{index}"
|
| 161 |
+
return self.config.sequence[index][1]
|
| 162 |
+
|
| 163 |
+
def record(self, kind, target, gripper, execute):
|
| 164 |
+
index = len(self.config.segments)
|
| 165 |
+
sequence = self.config.sequence
|
| 166 |
+
if sequence is not None and (index >= len(sequence) or sequence[index][0] != kind):
|
| 167 |
+
raise ValueError("Upstream expert primitive sequence changed")
|
| 168 |
+
start = len(self.config.recorder._trajectory_buffer.action) - 1
|
| 169 |
+
goal = pose_vector(target)
|
| 170 |
+
result = execute()
|
| 171 |
+
if isinstance(result, int) and result == -1:
|
| 172 |
+
raise PlanningFailure(
|
| 173 |
+
f"Native planning failed during {self.name(index, kind)}"
|
| 174 |
+
)
|
| 175 |
+
end = len(self.config.recorder._trajectory_buffer.action) - 1
|
| 176 |
+
if end <= start:
|
| 177 |
+
raise ValueError("Executed primitive recorded no actions")
|
| 178 |
+
self.config.segments.append(
|
| 179 |
+
KeyposeSegment(
|
| 180 |
+
name=self.name(index, kind),
|
| 181 |
+
kind=kind,
|
| 182 |
+
start=start,
|
| 183 |
+
end=end,
|
| 184 |
+
target_pose=goal,
|
| 185 |
+
gripper=gripper,
|
| 186 |
+
)
|
| 187 |
+
)
|
| 188 |
+
return result
|
| 189 |
+
|
| 190 |
+
def move_to_pose_with_screw(self, pose, dry_run=False, refine_steps=0):
|
| 191 |
+
planner = self.config.planner
|
| 192 |
+
if dry_run:
|
| 193 |
+
return planner.move_to_pose_with_screw(
|
| 194 |
+
pose, dry_run=True, refine_steps=refine_steps
|
| 195 |
+
)
|
| 196 |
+
if self.config.perturbation is None:
|
| 197 |
+
execute = lambda: planner.move_to_pose_with_screw(pose, refine_steps=refine_steps)
|
| 198 |
+
else:
|
| 199 |
+
name = self.name(len(self.config.segments), "move")
|
| 200 |
+
execute = lambda: self.perturbed_move(pose, name, refine_steps)
|
| 201 |
+
return self.record("move", pose, float(planner.gripper_state), execute)
|
| 202 |
+
|
| 203 |
+
def perturbed_move(self, pose, name, refine_steps):
|
| 204 |
+
"""Execute one planned move with this attempt's perturbation."""
|
| 205 |
+
planner, config, rng = self.config.planner, self.config.perturbation, self.config.rng
|
| 206 |
+
free = name in FREE_SPACE
|
| 207 |
+
record = {"segment": name, "detour": False}
|
| 208 |
+
goals = [pose]
|
| 209 |
+
if free and rng.random() < config.detour_probability and config.detour_m > 0:
|
| 210 |
+
start = common.to_numpy(planner.base_env.agent.tcp.pose.p).reshape(3)
|
| 211 |
+
end = common.to_numpy(pose.p).reshape(3)
|
| 212 |
+
direction = end[:2] - start[:2]
|
| 213 |
+
if np.linalg.norm(direction) < 1e-6:
|
| 214 |
+
angle = rng.uniform(0, 2 * np.pi)
|
| 215 |
+
direction = np.array([np.cos(angle), np.sin(angle)])
|
| 216 |
+
side = np.array([-direction[1], direction[0]]) / np.linalg.norm(direction)
|
| 217 |
+
side *= rng.choice([-1.0, 1.0]) * config.detour_m
|
| 218 |
+
via = (start + end) / 2 + np.r_[side, config.detour_m / 2]
|
| 219 |
+
via_pose = sapien.Pose(via, common.to_numpy(pose.q).reshape(4))
|
| 220 |
+
if planner.move_to_pose_with_screw(via_pose, dry_run=True) != -1:
|
| 221 |
+
goals = [via_pose, pose]
|
| 222 |
+
record.update(detour=True, via=via.tolist())
|
| 223 |
+
result = None
|
| 224 |
+
for index, goal in enumerate(goals):
|
| 225 |
+
plan = planner.move_to_pose_with_screw(goal, dry_run=True)
|
| 226 |
+
if isinstance(plan, int) and plan == -1:
|
| 227 |
+
return -1
|
| 228 |
+
positions = np.asarray(plan["position"], dtype=np.float64)
|
| 229 |
+
scale = float(np.exp(rng.uniform(*np.log(config.time_scale))))
|
| 230 |
+
steps = max(2, round(len(positions) * scale))
|
| 231 |
+
grid = np.linspace(0, len(positions) - 1, steps)
|
| 232 |
+
positions = np.stack(
|
| 233 |
+
[np.interp(grid, np.arange(len(positions)), joint) for joint in positions.T], -1
|
| 234 |
+
)
|
| 235 |
+
if free and config.jitter_rad > 0 and steps > 2:
|
| 236 |
+
noise = rng.normal(size=positions.shape)
|
| 237 |
+
width = config.jitter_smoothing_steps
|
| 238 |
+
radius = min(int(3 * width), (steps - 1) // 2)
|
| 239 |
+
kernel = np.exp(-0.5 * (np.arange(-radius, radius + 1) / width) ** 2)
|
| 240 |
+
noise = np.stack([np.convolve(n, kernel, mode="same") for n in noise.T], -1)
|
| 241 |
+
noise /= noise.std(0, keepdims=True) + 1e-12
|
| 242 |
+
taper = np.sin(np.linspace(0, np.pi, steps))[:, None]
|
| 243 |
+
positions = positions + config.jitter_rad * noise * taper
|
| 244 |
+
pause = 0
|
| 245 |
+
if index == len(goals) - 1 and rng.random() < config.pause_probability:
|
| 246 |
+
pause = int(rng.integers(config.pause_steps[0], config.pause_steps[1] + 1))
|
| 247 |
+
at = int(rng.integers(1, steps))
|
| 248 |
+
positions = np.concatenate(
|
| 249 |
+
[positions[:at], np.repeat(positions[at - 1 : at], pause, 0), positions[at:]]
|
| 250 |
+
)
|
| 251 |
+
record.setdefault("parts", []).append(
|
| 252 |
+
{"planned_steps": len(plan["position"]), "time_scale": scale,
|
| 253 |
+
"executed_steps": len(positions), "pause_steps": pause}
|
| 254 |
+
)
|
| 255 |
+
velocity = np.gradient(positions, axis=0) / planner.base_env.control_timestep
|
| 256 |
+
result = planner.follow_path(
|
| 257 |
+
{"position": positions, "velocity": velocity}, refine_steps=refine_steps
|
| 258 |
+
)
|
| 259 |
+
self.config.log.append(record)
|
| 260 |
+
return result
|
| 261 |
+
|
| 262 |
+
def close_gripper(self, t=6, gripper_state=None):
|
| 263 |
+
planner = self.config.planner
|
| 264 |
+
return self.record(
|
| 265 |
+
"close",
|
| 266 |
+
planner.base_env.agent.tcp.pose,
|
| 267 |
+
float(planner.CLOSED if gripper_state is None else gripper_state),
|
| 268 |
+
lambda: planner.close_gripper(t=t, gripper_state=gripper_state),
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
def open_gripper(self, t=6, gripper_state=None):
|
| 272 |
+
planner = self.config.planner
|
| 273 |
+
return self.record(
|
| 274 |
+
"open",
|
| 275 |
+
planner.base_env.agent.tcp.pose,
|
| 276 |
+
float(planner.OPEN if gripper_state is None else gripper_state),
|
| 277 |
+
lambda: planner.open_gripper(t=t, gripper_state=gripper_state),
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
def close(self):
|
| 281 |
+
self.config.planner.close()
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def clear_recording(recorder):
|
| 285 |
+
if recorder._trajectory_buffer is not None:
|
| 286 |
+
recorder.flush_trajectory(save=False)
|
| 287 |
+
if recorder.save_video:
|
| 288 |
+
recorder.flush_video(save=False)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def sha256(path):
|
| 292 |
+
digest = hashlib.sha256()
|
| 293 |
+
with Path(path).open("rb") as f:
|
| 294 |
+
for block in iter(lambda: f.read(8 * 1024 * 1024), b""):
|
| 295 |
+
digest.update(block)
|
| 296 |
+
return digest.hexdigest()
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def run(config: CollectionConfig, replay=None):
|
| 300 |
+
"""Collect annotated demonstrations.
|
| 301 |
+
|
| 302 |
+
`replay`, if given, replaces the conversion of the expert's joint actions:
|
| 303 |
+
replay(target_env, segments, max_steps) executes the expert's annotated
|
| 304 |
+
segments in the pose environment by its own rule and returns
|
| 305 |
+
(info, executed_segments, failure); its dense actions are then its own
|
| 306 |
+
commands and its segments are in its own step coordinates. Its
|
| 307 |
+
`provenance` attribute is recorded. None keeps the native conversion."""
|
| 308 |
+
if config.max_attempts < config.episodes:
|
| 309 |
+
raise ValueError("Attempt budget cannot be smaller than the requested dataset")
|
| 310 |
+
torch.set_num_threads(4)
|
| 311 |
+
config.output_dir.mkdir(parents=True, exist_ok=False)
|
| 312 |
+
(config.output_dir / "config.json").write_text(
|
| 313 |
+
config.model_dump_json(indent=2) + "\n"
|
| 314 |
+
)
|
| 315 |
+
# Freeze the actual collector, replay code and native expert used for this dataset.
|
| 316 |
+
from lim import keypose_data, replay_pose
|
| 317 |
+
|
| 318 |
+
expert = expert_module(config.task, config.expert)
|
| 319 |
+
files = [
|
| 320 |
+
Path(__file__),
|
| 321 |
+
Path(keypose_data.__file__),
|
| 322 |
+
Path(replay_pose.__file__),
|
| 323 |
+
Path(inspect.getfile(expert)),
|
| 324 |
+
]
|
| 325 |
+
provenance = {
|
| 326 |
+
"source_sha256": {str(p): sha256(p) for p in files},
|
| 327 |
+
"software_versions": {
|
| 328 |
+
p: importlib.metadata.version(p)
|
| 329 |
+
for p in ["mani-skill", "sapien", "torch", "numpy", "mplib"]
|
| 330 |
+
},
|
| 331 |
+
"observation_policy": "all RGB, TCP, qpos/qvel and dense actions retained",
|
| 332 |
+
"annotation_policy": "native primitive targets/events; no image or action decimation",
|
| 333 |
+
"expert_information": "native expert uses simulator object poses to create labels; not policy inputs",
|
| 334 |
+
"perturbation": PERTURBATION_LEVELS[config.perturbation_level].model_dump(mode="json")
|
| 335 |
+
if config.perturbation_level
|
| 336 |
+
else None,
|
| 337 |
+
"replay": replay.provenance if replay is not None else "native joint-action conversion",
|
| 338 |
+
}
|
| 339 |
+
snapshot = config.output_dir / "source_snapshot"
|
| 340 |
+
snapshot.mkdir()
|
| 341 |
+
for p in files:
|
| 342 |
+
(snapshot / p.name).write_bytes(p.read_bytes())
|
| 343 |
+
(config.output_dir / "provenance.json").write_text(
|
| 344 |
+
json.dumps(provenance, indent=2) + "\n"
|
| 345 |
+
)
|
| 346 |
+
kwargs = {
|
| 347 |
+
"sim_backend": "physx_cpu",
|
| 348 |
+
"num_envs": 1,
|
| 349 |
+
"max_episode_steps": config.max_episode_steps,
|
| 350 |
+
"reward_mode": "sparse",
|
| 351 |
+
"render_mode": "rgb_array",
|
| 352 |
+
"sensor_configs": {"shader_pack": "default"},
|
| 353 |
+
"human_render_camera_configs": {"shader_pack": "default"},
|
| 354 |
+
"viewer_camera_configs": {"shader_pack": "default"},
|
| 355 |
+
}
|
| 356 |
+
raw = RecordEpisode(
|
| 357 |
+
gym.make(config.task, obs_mode="rgb", control_mode="pd_joint_pos", **kwargs),
|
| 358 |
+
output_dir=str(config.output_dir / "source"),
|
| 359 |
+
trajectory_name="trajectory",
|
| 360 |
+
save_on_reset=False,
|
| 361 |
+
save_video=config.save_video,
|
| 362 |
+
video_fps=20,
|
| 363 |
+
source_type="motionplanning",
|
| 364 |
+
source_desc=f"native {config.task} expert with primitive annotations",
|
| 365 |
+
)
|
| 366 |
+
original = gym.make(
|
| 367 |
+
config.task, obs_mode="none", control_mode="pd_joint_pos", **kwargs
|
| 368 |
+
)
|
| 369 |
+
target = RecordEpisode(
|
| 370 |
+
gym.make(
|
| 371 |
+
config.task, obs_mode="rgb", control_mode="pd_ee_delta_pose", **kwargs
|
| 372 |
+
),
|
| 373 |
+
output_dir=str(config.output_dir / "pose"),
|
| 374 |
+
trajectory_name="trajectory",
|
| 375 |
+
save_on_reset=False,
|
| 376 |
+
save_video=False,
|
| 377 |
+
source_type="motionplanning",
|
| 378 |
+
source_desc="pose replay with exact source-action annotation mapping",
|
| 379 |
+
)
|
| 380 |
+
started = time.monotonic()
|
| 381 |
+
accepted = 0
|
| 382 |
+
attempts = []
|
| 383 |
+
native_planner = expert.PandaArmMotionPlanningSolver
|
| 384 |
+
sequence = STACK_CUBE_SEQUENCE if config.task == "StackCube-v1" else None
|
| 385 |
+
try:
|
| 386 |
+
for attempt in range(config.max_attempts):
|
| 387 |
+
seed = config.seed_start + attempt
|
| 388 |
+
clear_recording(raw)
|
| 389 |
+
clear_recording(target)
|
| 390 |
+
segments = []
|
| 391 |
+
planners = []
|
| 392 |
+
|
| 393 |
+
perturbation = PERTURBATION_LEVELS.get(config.perturbation_level)
|
| 394 |
+
moves = []
|
| 395 |
+
rng = (
|
| 396 |
+
np.random.default_rng([perturbation.seed, seed]) if perturbation else None
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
def factory(
|
| 400 |
+
*args,
|
| 401 |
+
_planners=planners,
|
| 402 |
+
_segments=segments,
|
| 403 |
+
_moves=moves,
|
| 404 |
+
_perturbation=perturbation,
|
| 405 |
+
_rng=rng,
|
| 406 |
+
**kwargs,
|
| 407 |
+
):
|
| 408 |
+
planner = native_planner(*args, **kwargs)
|
| 409 |
+
_planners.append(planner)
|
| 410 |
+
return AnnotatedPlanner(
|
| 411 |
+
PlannerConfig(
|
| 412 |
+
planner=planner,
|
| 413 |
+
recorder=raw,
|
| 414 |
+
segments=_segments,
|
| 415 |
+
sequence=sequence,
|
| 416 |
+
perturbation=_perturbation,
|
| 417 |
+
rng=_rng,
|
| 418 |
+
log=_moves,
|
| 419 |
+
)
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
failure = None
|
| 423 |
+
try:
|
| 424 |
+
# Scoped single-process adapter; the upstream function and planner remain unchanged.
|
| 425 |
+
with patch.object(expert, "PandaArmMotionPlanningSolver", factory):
|
| 426 |
+
result = expert.solve(raw, seed=seed, debug=False, vis=False)
|
| 427 |
+
raw_success = not isinstance(result, int) and bool(
|
| 428 |
+
result[-1]["success"].item()
|
| 429 |
+
)
|
| 430 |
+
except PlanningFailure as error:
|
| 431 |
+
raw_success = False
|
| 432 |
+
failure = str(error)
|
| 433 |
+
finally:
|
| 434 |
+
for planner in planners:
|
| 435 |
+
planner.close()
|
| 436 |
+
record = {
|
| 437 |
+
"attempt": attempt,
|
| 438 |
+
"seed": seed,
|
| 439 |
+
"raw_success": raw_success,
|
| 440 |
+
"pose_success": False,
|
| 441 |
+
"failure": failure,
|
| 442 |
+
}
|
| 443 |
+
if perturbation is not None:
|
| 444 |
+
record["perturbation"] = moves
|
| 445 |
+
if raw_success and len(raw._trajectory_buffer.action) - 1 > config.max_episode_steps:
|
| 446 |
+
# Demonstrations must fit the time limit the policies are evaluated
|
| 447 |
+
# with; the planner can return very long paths from some states.
|
| 448 |
+
raw_success = False
|
| 449 |
+
record.update(
|
| 450 |
+
raw_success=False,
|
| 451 |
+
failure=f"expert exceeded the {config.max_episode_steps}-step limit",
|
| 452 |
+
source_steps=len(raw._trajectory_buffer.action) - 1,
|
| 453 |
+
)
|
| 454 |
+
if raw_success:
|
| 455 |
+
if sequence is not None and len(segments) != len(sequence):
|
| 456 |
+
raise ValueError("Successful source has incomplete annotations")
|
| 457 |
+
raw_steps = len(raw._trajectory_buffer.action) - 1
|
| 458 |
+
raw.flush_trajectory()
|
| 459 |
+
source_id = raw._episode_id
|
| 460 |
+
source_group = raw._h5_file[f"traj_{source_id}"]
|
| 461 |
+
write_annotations(
|
| 462 |
+
source_group,
|
| 463 |
+
AnnotationConfig(
|
| 464 |
+
segments=tuple(segments),
|
| 465 |
+
source_steps=raw_steps,
|
| 466 |
+
target_to_source=tuple(range(raw_steps)),
|
| 467 |
+
),
|
| 468 |
+
)
|
| 469 |
+
raw._h5_file.flush()
|
| 470 |
+
if config.save_video:
|
| 471 |
+
raw.flush_video(name=f"seed{seed}")
|
| 472 |
+
original.reset(seed=seed)
|
| 473 |
+
target.reset(seed=seed)
|
| 474 |
+
initial = tree_first(source_group["env_states"])
|
| 475 |
+
original.unwrapped.set_state_dict(initial)
|
| 476 |
+
target.unwrapped.set_state_dict(initial)
|
| 477 |
+
obs = target.unwrapped.get_obs()
|
| 478 |
+
replace_last(target._trajectory_buffer.state, common.batch(initial))
|
| 479 |
+
replace_last(
|
| 480 |
+
target._trajectory_buffer.observation,
|
| 481 |
+
common.to_numpy(common.batch(obs)),
|
| 482 |
+
)
|
| 483 |
+
# Exact identity/state correspondence is checked before executing any converted action.
|
| 484 |
+
for name in ["qpos", "qvel"]:
|
| 485 |
+
np.testing.assert_allclose(
|
| 486 |
+
common.to_numpy(obs["agent"][name])[0],
|
| 487 |
+
source_group[f"obs/agent/{name}"][0],
|
| 488 |
+
rtol=0,
|
| 489 |
+
atol=1e-6,
|
| 490 |
+
)
|
| 491 |
+
if replay is None:
|
| 492 |
+
mapping = []
|
| 493 |
+
info = replay_targets(
|
| 494 |
+
TargetReplayConfig(
|
| 495 |
+
original=original,
|
| 496 |
+
target=target,
|
| 497 |
+
actions=source_group["actions"][:],
|
| 498 |
+
on_target_step=mapping.append,
|
| 499 |
+
)
|
| 500 |
+
)
|
| 501 |
+
annotation = AnnotationConfig(
|
| 502 |
+
segments=tuple(segments),
|
| 503 |
+
source_steps=raw_steps,
|
| 504 |
+
target_to_source=tuple(mapping),
|
| 505 |
+
)
|
| 506 |
+
pose_steps = len(mapping)
|
| 507 |
+
else:
|
| 508 |
+
info, executed, failure = replay(
|
| 509 |
+
target, tuple(segments), config.max_episode_steps
|
| 510 |
+
)
|
| 511 |
+
pose_steps = executed[-1].end if executed else 0
|
| 512 |
+
annotation = None
|
| 513 |
+
if failure is None:
|
| 514 |
+
annotation = AnnotationConfig(
|
| 515 |
+
segments=executed,
|
| 516 |
+
source_steps=pose_steps,
|
| 517 |
+
target_to_source=tuple(range(pose_steps)),
|
| 518 |
+
)
|
| 519 |
+
record["replay_failure"] = failure
|
| 520 |
+
pose_success = (
|
| 521 |
+
info is not None
|
| 522 |
+
and bool(info["success"].item())
|
| 523 |
+
and pose_steps <= config.max_episode_steps
|
| 524 |
+
)
|
| 525 |
+
record.update(
|
| 526 |
+
source_episode_id=source_id,
|
| 527 |
+
source_steps=raw_steps,
|
| 528 |
+
pose_steps=pose_steps,
|
| 529 |
+
pose_success=pose_success,
|
| 530 |
+
)
|
| 531 |
+
if pose_success:
|
| 532 |
+
target.flush_trajectory()
|
| 533 |
+
output_id = target._episode_id
|
| 534 |
+
write_annotations(target._h5_file[f"traj_{output_id}"], annotation)
|
| 535 |
+
target._json_data["episodes"][-1].update(
|
| 536 |
+
source_episode_id=source_id, source_episode_seed=seed
|
| 537 |
+
)
|
| 538 |
+
target._h5_file.flush()
|
| 539 |
+
accepted += 1
|
| 540 |
+
record["output_episode_id"] = output_id
|
| 541 |
+
# Explicitly discard failed buffers before reset, including the last attempt.
|
| 542 |
+
clear_recording(raw)
|
| 543 |
+
clear_recording(target)
|
| 544 |
+
record.update(accepted=accepted, elapsed_s=time.monotonic() - started)
|
| 545 |
+
attempts.append(record)
|
| 546 |
+
with (config.output_dir / "attempts.jsonl").open("a") as f:
|
| 547 |
+
f.write(json.dumps(record) + "\n")
|
| 548 |
+
(config.output_dir / "progress.json").write_text(
|
| 549 |
+
json.dumps(record, indent=2) + "\n"
|
| 550 |
+
)
|
| 551 |
+
print("KEYPOSE_ATTEMPT", json.dumps(record), flush=True)
|
| 552 |
+
if accepted == config.episodes:
|
| 553 |
+
break
|
| 554 |
+
finally:
|
| 555 |
+
clear_recording(raw)
|
| 556 |
+
clear_recording(target)
|
| 557 |
+
raw.close()
|
| 558 |
+
original.close()
|
| 559 |
+
target.close()
|
| 560 |
+
audits = {}
|
| 561 |
+
for variant in ["source", "pose"]:
|
| 562 |
+
audit = audit_dataset(
|
| 563 |
+
AuditConfig(
|
| 564 |
+
dataset=config.output_dir / variant / "trajectory.h5",
|
| 565 |
+
output=config.output_dir / f"audit-{variant}.json",
|
| 566 |
+
# Cross-file identity holds only for the native action conversion.
|
| 567 |
+
source_dataset=config.output_dir / "source" / "trajectory.h5"
|
| 568 |
+
if variant == "pose" and replay is None
|
| 569 |
+
else None,
|
| 570 |
+
)
|
| 571 |
+
)
|
| 572 |
+
audits[variant] = {k: v for k, v in audit.items() if k != "rows"}
|
| 573 |
+
summary = {
|
| 574 |
+
"status": "complete"
|
| 575 |
+
if accepted == config.episodes
|
| 576 |
+
else "insufficient_successes",
|
| 577 |
+
"requested": config.episodes,
|
| 578 |
+
"accepted": accepted,
|
| 579 |
+
"attempted": len(attempts),
|
| 580 |
+
"wall_s": time.monotonic() - started,
|
| 581 |
+
"audits": audits,
|
| 582 |
+
"scope": "new annotated demonstration data; no learned keypose policy evaluated",
|
| 583 |
+
}
|
| 584 |
+
(config.output_dir / "result.json").write_text(json.dumps(summary, indent=2) + "\n")
|
| 585 |
+
print("KEYPOSE_COMPLETE", json.dumps(summary), flush=True)
|
| 586 |
+
if accepted != config.episodes:
|
| 587 |
+
raise RuntimeError("Collection exhausted its declared attempt budget")
|
| 588 |
+
return summary
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
if __name__ == "__main__":
|
| 592 |
+
run(CliApp.run(CollectionConfig))
|
fair-comparison/p3x-liftslow-v1/code/lim/evaluate_phase_chunk.py
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""One frozen dense+phase model, three separately logged execution contracts."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from types import SimpleNamespace
|
| 7 |
+
from typing import Literal
|
| 8 |
+
|
| 9 |
+
import gymnasium as gym
|
| 10 |
+
import mani_skill.envs # noqa: F401
|
| 11 |
+
import numpy as np
|
| 12 |
+
import torch
|
| 13 |
+
from mani_skill.utils.wrappers import CPUGymWrapper
|
| 14 |
+
from pydantic import BaseModel, ConfigDict, PositiveInt
|
| 15 |
+
from pydantic_settings import CliApp
|
| 16 |
+
|
| 17 |
+
from lim.act_policy import build_policy
|
| 18 |
+
from lim.action_encoding import sixd_to_controller
|
| 19 |
+
from lim.chunk_coordinates import chunk_relative_to_world, world_to_chunk_relative
|
| 20 |
+
from lim.chunk_endpoint import check_endpoint_controller
|
| 21 |
+
from lim.chunk_phase import chunk_selection
|
| 22 |
+
from lim.evaluate_planned_keypose import planning_state, verify_planning_unchanged
|
| 23 |
+
from lim.gripper_feedback import (
|
| 24 |
+
FeedbackReaderConfig,
|
| 25 |
+
GripperCompletionConfig,
|
| 26 |
+
PandaGripperFeedback,
|
| 27 |
+
)
|
| 28 |
+
from lim.keypose_diagnostics import (
|
| 29 |
+
TrainingResetConfig,
|
| 30 |
+
TrainingSceneReset,
|
| 31 |
+
predict_action_chunk,
|
| 32 |
+
)
|
| 33 |
+
from lim.keypose_phase import read_phase_logits
|
| 34 |
+
from lim.planned_keypose import (
|
| 35 |
+
MplibKeyposePlanner,
|
| 36 |
+
PlannedExecutorConfig,
|
| 37 |
+
PlannedKeyposeExecutor,
|
| 38 |
+
PlannerConfig,
|
| 39 |
+
)
|
| 40 |
+
from lim.reference_act import (
|
| 41 |
+
ReferenceConfig,
|
| 42 |
+
check_policy_checkpoint,
|
| 43 |
+
load_checkpoint,
|
| 44 |
+
load_official,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class PhaseChunkEvaluationConfig(BaseModel, frozen=True):
|
| 49 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 50 |
+
reference: Path
|
| 51 |
+
"""Frozen fixed-anchor phase-supervised dense checkpoint and sensor configuration."""
|
| 52 |
+
output_dir: Path
|
| 53 |
+
"""New results directory; never overwrite a previous run."""
|
| 54 |
+
mode: Literal["full", "boundary", "endpoint"]
|
| 55 |
+
"""Full30 playback, phase-prefix playback, or planned prefix endpoint."""
|
| 56 |
+
episodes: PositiveInt = 60
|
| 57 |
+
"""All consecutive scenes, including failures."""
|
| 58 |
+
seed_start: int = 54000
|
| 59 |
+
"""First scene seed."""
|
| 60 |
+
training_dataset: Path | None = None
|
| 61 |
+
"""Optional restoration of training initial states only, never labels for control."""
|
| 62 |
+
gripper_completion: GripperCompletionConfig = GripperCompletionConfig()
|
| 63 |
+
"""Original planned executor completion contract; playback has no extra dwell."""
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def write_row(stream, row):
|
| 67 |
+
stream.write(json.dumps(row, allow_nan=False) + "\n")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def run(config: PhaseChunkEvaluationConfig):
|
| 71 |
+
torch.set_num_threads(4)
|
| 72 |
+
torch.manual_seed(0)
|
| 73 |
+
np.random.seed(0)
|
| 74 |
+
reference = ReferenceConfig.model_validate_json(config.reference.read_text())
|
| 75 |
+
if not (
|
| 76 |
+
reference.policy.chunk_phase_weight > 0
|
| 77 |
+
and reference.policy.method == "chunk_relative"
|
| 78 |
+
and reference.policy.chunk_anchor == "chunk_start_tcp"
|
| 79 |
+
and reference.num_queries == 30
|
| 80 |
+
and reference.control_mode == "pd_ee_delta_pose"
|
| 81 |
+
and not reference.gripper_execution.active
|
| 82 |
+
):
|
| 83 |
+
raise ValueError("Expected one phase-supervised fixed-anchor Q30 pose6D model")
|
| 84 |
+
checkpoint, provenance = load_checkpoint(reference.checkpoint)
|
| 85 |
+
check_policy_checkpoint(checkpoint, reference)
|
| 86 |
+
module = load_official(reference)
|
| 87 |
+
metadata = json.loads(reference.demonstration_metadata.read_text())
|
| 88 |
+
sensor = metadata["env_info"]["env_kwargs"]["sensor_configs"]
|
| 89 |
+
planned = config.mode == "endpoint"
|
| 90 |
+
control_mode = "pd_joint_pos" if planned else "pd_ee_delta_pose"
|
| 91 |
+
config.output_dir.mkdir(parents=True, exist_ok=False)
|
| 92 |
+
for folder in ("plans", "query_observations"):
|
| 93 |
+
(config.output_dir / folder).mkdir()
|
| 94 |
+
raw = gym.make(
|
| 95 |
+
"StackCube-v1",
|
| 96 |
+
obs_mode="rgb",
|
| 97 |
+
control_mode=control_mode,
|
| 98 |
+
reward_mode="sparse",
|
| 99 |
+
render_mode="rgb_array",
|
| 100 |
+
sim_backend="physx_cpu",
|
| 101 |
+
num_envs=1,
|
| 102 |
+
reconfiguration_freq=1,
|
| 103 |
+
max_episode_steps=200,
|
| 104 |
+
sensor_configs=sensor,
|
| 105 |
+
)
|
| 106 |
+
if config.training_dataset is not None:
|
| 107 |
+
raw = TrainingSceneReset(
|
| 108 |
+
TrainingResetConfig(env=raw, dataset=config.training_dataset)
|
| 109 |
+
)
|
| 110 |
+
env = CPUGymWrapper(
|
| 111 |
+
module.FlattenRGBDObservationWrapper(raw, depth=False),
|
| 112 |
+
ignore_terminations=True,
|
| 113 |
+
record_metrics=True,
|
| 114 |
+
)
|
| 115 |
+
spaces = SimpleNamespace(
|
| 116 |
+
single_observation_space=env.observation_space,
|
| 117 |
+
single_action_space=gym.spaces.Box(-1, 1, (7,), dtype=np.float32),
|
| 118 |
+
)
|
| 119 |
+
records = []
|
| 120 |
+
started = time.time()
|
| 121 |
+
try:
|
| 122 |
+
agent = (
|
| 123 |
+
build_policy(
|
| 124 |
+
module,
|
| 125 |
+
spaces,
|
| 126 |
+
module.args,
|
| 127 |
+
reference.policy,
|
| 128 |
+
checkpoint.get("normalization"),
|
| 129 |
+
)
|
| 130 |
+
.cuda()
|
| 131 |
+
.eval()
|
| 132 |
+
)
|
| 133 |
+
agent.load_state_dict(checkpoint["ema_agent"])
|
| 134 |
+
if not np.isclose(env.unwrapped.control_timestep, 0.05):
|
| 135 |
+
raise ValueError("Expected 20Hz physical playback")
|
| 136 |
+
with (
|
| 137 |
+
(config.output_dir / "predictions.jsonl").open("x") as queries,
|
| 138 |
+
(config.output_dir / "steps.jsonl").open("x") as steps,
|
| 139 |
+
(config.output_dir / "episodes.jsonl").open("x") as episodes,
|
| 140 |
+
):
|
| 141 |
+
for seed in range(config.seed_start, config.seed_start + config.episodes):
|
| 142 |
+
obs, _ = env.reset(seed=seed)
|
| 143 |
+
base = env.unwrapped
|
| 144 |
+
check_endpoint_controller(
|
| 145 |
+
base.agent._controller_configs["pd_ee_delta_pose"]["arm"]
|
| 146 |
+
)
|
| 147 |
+
np.testing.assert_allclose(
|
| 148 |
+
base.agent.robot.pose.raw_pose[0, 3:].cpu().numpy(),
|
| 149 |
+
[1, 0, 0, 0],
|
| 150 |
+
atol=1e-5,
|
| 151 |
+
)
|
| 152 |
+
torch.save(
|
| 153 |
+
{
|
| 154 |
+
"observation": obs,
|
| 155 |
+
"cubeA_pose": base.cubeA.pose.raw_pose.cpu(),
|
| 156 |
+
"cubeB_pose": base.cubeB.pose.raw_pose.cpu(),
|
| 157 |
+
},
|
| 158 |
+
config.output_dir / f"initial-{seed}.pt",
|
| 159 |
+
)
|
| 160 |
+
initial_grip = float(
|
| 161 |
+
np.float32(
|
| 162 |
+
np.clip((obs["state"][7:9].mean() + 0.01) / 0.05 * 2 - 1, -1, 1)
|
| 163 |
+
)
|
| 164 |
+
)
|
| 165 |
+
executor = PlannedKeyposeExecutor(
|
| 166 |
+
PlannedExecutorConfig(
|
| 167 |
+
initial_gripper=initial_grip,
|
| 168 |
+
gripper_completion=config.gripper_completion,
|
| 169 |
+
)
|
| 170 |
+
)
|
| 171 |
+
planner = (
|
| 172 |
+
MplibKeyposePlanner(PlannerConfig(env=env)) if planned else None
|
| 173 |
+
)
|
| 174 |
+
feedback = (
|
| 175 |
+
PandaGripperFeedback(
|
| 176 |
+
FeedbackReaderConfig(
|
| 177 |
+
env=env, completion=config.gripper_completion
|
| 178 |
+
)
|
| 179 |
+
)
|
| 180 |
+
if planned
|
| 181 |
+
else None
|
| 182 |
+
)
|
| 183 |
+
query = cursor = consume = failures = 0
|
| 184 |
+
once = False
|
| 185 |
+
world = None
|
| 186 |
+
for step in range(200):
|
| 187 |
+
before = obs["state"].copy()
|
| 188 |
+
needs_query = (
|
| 189 |
+
executor.needs_prediction if planned else cursor == consume
|
| 190 |
+
)
|
| 191 |
+
if needs_query:
|
| 192 |
+
query += 1
|
| 193 |
+
np.savez_compressed(
|
| 194 |
+
config.output_dir
|
| 195 |
+
/ f"query_observations/seed{seed}-query{query}.npz",
|
| 196 |
+
**obs,
|
| 197 |
+
)
|
| 198 |
+
chunk = predict_action_chunk(agent, obs)
|
| 199 |
+
logits = read_phase_logits(agent)[0].detach().cpu()
|
| 200 |
+
if chunk.shape != (30, 10) or not torch.isfinite(chunk).all():
|
| 201 |
+
raise ValueError("Expected finite fixed-anchor chunk")
|
| 202 |
+
selection = chunk_selection(logits, config.mode)
|
| 203 |
+
consume, cursor = selection["consume_length"], 0
|
| 204 |
+
world = chunk_relative_to_world(
|
| 205 |
+
chunk, torch.tensor(before[18:25])
|
| 206 |
+
)
|
| 207 |
+
target = world[selection["selected_index"]]
|
| 208 |
+
prefix_grip = world[: selection["phase_prefix_length"], -1] >= 0
|
| 209 |
+
row = {
|
| 210 |
+
"seed": seed,
|
| 211 |
+
"step": step,
|
| 212 |
+
"query": query,
|
| 213 |
+
"state_before": before.tolist(),
|
| 214 |
+
"relative_chunk": chunk.tolist(),
|
| 215 |
+
"world_chunk": world.tolist(),
|
| 216 |
+
"phase_logits": logits.tolist(),
|
| 217 |
+
**selection,
|
| 218 |
+
"within_prefix_gripper_sign_changes": int(
|
| 219 |
+
(prefix_grip[1:] != prefix_grip[:-1]).sum()
|
| 220 |
+
),
|
| 221 |
+
"model_target": target.tolist(),
|
| 222 |
+
"planning_status": None,
|
| 223 |
+
"path_steps": 0,
|
| 224 |
+
}
|
| 225 |
+
if planned:
|
| 226 |
+
physical = planning_state(base)
|
| 227 |
+
plan = planner.plan(target)
|
| 228 |
+
verify_planning_unchanged(physical, planning_state(base))
|
| 229 |
+
row["planning_status"] = planner.last_status
|
| 230 |
+
failures += int(plan is None)
|
| 231 |
+
if plan is not None:
|
| 232 |
+
np.savez_compressed(
|
| 233 |
+
config.output_dir
|
| 234 |
+
/ f"plans/seed{seed}-query{query}.npz",
|
| 235 |
+
position=plan["position"],
|
| 236 |
+
velocity=plan["velocity"],
|
| 237 |
+
time=plan["time"],
|
| 238 |
+
)
|
| 239 |
+
row["path_steps"] = len(plan["position"])
|
| 240 |
+
executor.begin(
|
| 241 |
+
target,
|
| 242 |
+
None if plan is None else plan["position"],
|
| 243 |
+
before[:9],
|
| 244 |
+
source_query=query,
|
| 245 |
+
)
|
| 246 |
+
write_row(queries, row)
|
| 247 |
+
if planned:
|
| 248 |
+
index = selection["selected_index"]
|
| 249 |
+
command, details = executor.command(before[18:25])
|
| 250 |
+
else:
|
| 251 |
+
index = cursor
|
| 252 |
+
command = sixd_to_controller(
|
| 253 |
+
world_to_chunk_relative(
|
| 254 |
+
world[index], torch.tensor(before[18:25])
|
| 255 |
+
)
|
| 256 |
+
).numpy()
|
| 257 |
+
cursor += 1
|
| 258 |
+
details = {"phase": "playback"}
|
| 259 |
+
obs, _, _, _, info = env.step(command)
|
| 260 |
+
if planned:
|
| 261 |
+
measured = feedback.read(float(command[-1]))
|
| 262 |
+
details["gripper_measurement"] = measured.model_dump(
|
| 263 |
+
mode="json"
|
| 264 |
+
)
|
| 265 |
+
if details["phase"] == "gripper":
|
| 266 |
+
details["gripper_feedback"] = executor.observe_gripper(
|
| 267 |
+
measured
|
| 268 |
+
)
|
| 269 |
+
details["executor_phase_after"] = executor.phase
|
| 270 |
+
success = bool(info["success"])
|
| 271 |
+
once = once or success
|
| 272 |
+
write_row(
|
| 273 |
+
steps,
|
| 274 |
+
{
|
| 275 |
+
"seed": seed,
|
| 276 |
+
"step": step,
|
| 277 |
+
"query": query,
|
| 278 |
+
"chunk_index": index,
|
| 279 |
+
"state_before": before.tolist(),
|
| 280 |
+
"state_after": obs["state"].tolist(),
|
| 281 |
+
"command": command.tolist(),
|
| 282 |
+
"success": success,
|
| 283 |
+
**details,
|
| 284 |
+
},
|
| 285 |
+
)
|
| 286 |
+
episode = {
|
| 287 |
+
"seed": seed,
|
| 288 |
+
"steps": 200,
|
| 289 |
+
"success_once": once,
|
| 290 |
+
"success_at_end": success,
|
| 291 |
+
"policy_calls": query,
|
| 292 |
+
"planning_failures": failures,
|
| 293 |
+
"gripper_timeouts": executor.gripper_timeouts if planned else 0,
|
| 294 |
+
}
|
| 295 |
+
assert once == bool(
|
| 296 |
+
info["episode"]["success_once"]
|
| 297 |
+
) and success == bool(info["episode"]["success_at_end"])
|
| 298 |
+
write_row(episodes, episode)
|
| 299 |
+
records.append(episode)
|
| 300 |
+
finally:
|
| 301 |
+
env.close()
|
| 302 |
+
result = {
|
| 303 |
+
"status": "complete",
|
| 304 |
+
"config": config.model_dump(mode="json"),
|
| 305 |
+
"policy": reference.policy.model_dump(mode="json"),
|
| 306 |
+
"provenance": provenance,
|
| 307 |
+
"sensor_configs": sensor,
|
| 308 |
+
"parameters": sum(p.numel() for p in agent.parameters()),
|
| 309 |
+
"control_mode": control_mode,
|
| 310 |
+
"control_hz": 20,
|
| 311 |
+
"episodes": len(records),
|
| 312 |
+
"counts": {
|
| 313 |
+
key: sum(int(r[key]) for r in records)
|
| 314 |
+
for key in ("success_once", "success_at_end")
|
| 315 |
+
},
|
| 316 |
+
"started_epoch": started,
|
| 317 |
+
"ended_epoch": time.time(),
|
| 318 |
+
"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.",
|
| 319 |
+
}
|
| 320 |
+
(config.output_dir / "result.json").write_text(
|
| 321 |
+
json.dumps(result, indent=2, allow_nan=False) + "\n"
|
| 322 |
+
)
|
| 323 |
+
print("PHASE_CHUNK_COMPLETE", json.dumps(result), flush=True)
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
if __name__ == "__main__":
|
| 327 |
+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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Matched single-environment evaluation of frozen reactive and planned keyposes."""
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import inspect
|
| 5 |
+
import json
|
| 6 |
+
import time
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from types import SimpleNamespace
|
| 9 |
+
from typing import Literal
|
| 10 |
+
|
| 11 |
+
import gymnasium as gym
|
| 12 |
+
import mani_skill.envs # noqa: F401
|
| 13 |
+
import numpy as np
|
| 14 |
+
import torch
|
| 15 |
+
from mani_skill.utils.wrappers import CPUGymWrapper
|
| 16 |
+
from pydantic import (
|
| 17 |
+
BaseModel,
|
| 18 |
+
ConfigDict,
|
| 19 |
+
Field,
|
| 20 |
+
NonNegativeInt,
|
| 21 |
+
PositiveInt,
|
| 22 |
+
model_validator,
|
| 23 |
+
)
|
| 24 |
+
from pydantic_settings import CliApp
|
| 25 |
+
|
| 26 |
+
from lim.act_policy import build_policy
|
| 27 |
+
from lim.chunk_coordinates import chunk_relative_to_world
|
| 28 |
+
from lim.chunk_endpoint import check_endpoint_controller, dense_chunk_endpoint
|
| 29 |
+
from lim.gripper_feedback import (
|
| 30 |
+
FeedbackReaderConfig,
|
| 31 |
+
GripperCompletionConfig,
|
| 32 |
+
PandaGripperFeedback,
|
| 33 |
+
)
|
| 34 |
+
from lim.keypose_control import KeyposeControlConfig, keypose_command
|
| 35 |
+
from lim.keypose_diagnostics import (
|
| 36 |
+
FirstTargetXYZConfig,
|
| 37 |
+
TrainingFirstTargetXYZ,
|
| 38 |
+
TrainingResetConfig,
|
| 39 |
+
TrainingSceneReset,
|
| 40 |
+
first_target_intervention,
|
| 41 |
+
nearest_cube_intervention,
|
| 42 |
+
predict_action_chunk,
|
| 43 |
+
predict_keypose,
|
| 44 |
+
)
|
| 45 |
+
from lim.keypose_phase import KEYPOSE_PHASE_NAMES, read_phase_logits
|
| 46 |
+
from lim.keypose_stop import read_stop_logits
|
| 47 |
+
from lim.planned_keypose import (
|
| 48 |
+
MplibKeyposePlanner,
|
| 49 |
+
PlannedExecutorConfig,
|
| 50 |
+
PlannedKeyposeExecutor,
|
| 51 |
+
PlannerConfig,
|
| 52 |
+
)
|
| 53 |
+
from lim.policy_video import PolicyVideo, PolicyVideoConfig
|
| 54 |
+
from lim.reference_act import (
|
| 55 |
+
AuditConfig,
|
| 56 |
+
ReferenceConfig,
|
| 57 |
+
ReleasedSupportAudit,
|
| 58 |
+
check_policy_checkpoint,
|
| 59 |
+
load_checkpoint,
|
| 60 |
+
load_official,
|
| 61 |
+
source_provenance,
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class EvaluationConfig(BaseModel, frozen=True):
|
| 66 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 67 |
+
reference: Path = Path("round9/specs/eval-keypose-main.json")
|
| 68 |
+
"""Frozen model and sensor contract; checked against its trained action semantics."""
|
| 69 |
+
target_source: Literal[
|
| 70 |
+
"keypose", "dense_chunk_endpoint", "chunk_relative_endpoint"
|
| 71 |
+
] = "keypose"
|
| 72 |
+
"""Direct query-zero keypose, or nominal endpoint composed from a dense delta chunk."""
|
| 73 |
+
mode: Literal["reactive", "planned"]
|
| 74 |
+
"""Fresh prediction each step, or full planned path before each prediction."""
|
| 75 |
+
reactive_gripper_gate: bool = True
|
| 76 |
+
"""Reactive only: false directly executes predicted gripper, changing no motion command."""
|
| 77 |
+
output_dir: Path
|
| 78 |
+
"""New directory containing every episode, command, prediction and plan."""
|
| 79 |
+
episodes: PositiveInt = 60
|
| 80 |
+
"""Consecutive original ID scenes; no selection or retries."""
|
| 81 |
+
seed_start: int = 54000
|
| 82 |
+
"""First paired scene seed."""
|
| 83 |
+
max_steps: PositiveInt = 200
|
| 84 |
+
"""Physical control steps per scene; non-200 budgets are horizon diagnostics."""
|
| 85 |
+
video_seeds: tuple[int, ...] = (54000, 54017)
|
| 86 |
+
"""Selected recordings; the model does not see the observer camera."""
|
| 87 |
+
gripper_completion: GripperCompletionConfig = GripperCompletionConfig()
|
| 88 |
+
"""Finger encoder/contact feedback criteria for planned execution completion."""
|
| 89 |
+
resume_after_incomplete: bool = False
|
| 90 |
+
"""Keep querying after an unmet gripper command instead of freezing the episode.
|
| 91 |
+
|
| 92 |
+
The original contract has no path back from gripper_timeout: the 27 stalled
|
| 93 |
+
chunk_relative endpoint episodes spent 2,314 further steps (42.9% of their
|
| 94 |
+
budget) without a single new query. Default false preserves scored runs.
|
| 95 |
+
"""
|
| 96 |
+
carry_gripper_feedback: bool = False
|
| 97 |
+
"""Reuse fresh motion-time gripper stability for an exactly unchanged command."""
|
| 98 |
+
phase_gripper_events: bool = False
|
| 99 |
+
"""Use predicted close/open classes to hold the arm and execute the predicted
|
| 100 |
+
continuous gripper immediately; other classes retain full planned motion."""
|
| 101 |
+
motion_replan_steps: NonNegativeInt = 0
|
| 102 |
+
"""Refresh the target after N actual motion steps; zero executes full paths."""
|
| 103 |
+
first_close_hold: bool = False
|
| 104 |
+
"""On the first requested open-to-close transition, hold measured arm joints
|
| 105 |
+
and execute only the predicted gripper. Context retains the raw request,
|
| 106 |
+
whose arm pose was bypassed, after gripper feedback completion."""
|
| 107 |
+
hold_after_first_release: bool = False
|
| 108 |
+
"""After the first predicted negative-to-nonnegative gripper transition
|
| 109 |
+
completes its original path and feedback, hold its final command to horizon."""
|
| 110 |
+
honor_predicted_stop: bool = False
|
| 111 |
+
"""Consume the checkpoint's stop-after-target prediction only after full
|
| 112 |
+
execution and feedback; false logs the same logits but continues querying."""
|
| 113 |
+
terminal_gripper_event: bool = False
|
| 114 |
+
"""For a predicted terminal target with nonnegative gripper, bypass its arm
|
| 115 |
+
pose and hold measured joints during the original gripper feedback."""
|
| 116 |
+
training_dataset: Path | None = None
|
| 117 |
+
"""Diagnostic only: restore saved training states selected by episode seed."""
|
| 118 |
+
first_target_xyz_alpha: float | None = Field(
|
| 119 |
+
default=None, ge=0, le=1, allow_inf_nan=False
|
| 120 |
+
)
|
| 121 |
+
"""Training-scene oracle only: first XYZ = expert + alpha * model residual.
|
| 122 |
+
None preserves the original path; alpha=1 is an exact identity diagnostic.
|
| 123 |
+
Rotation, gripper and all later predictions remain the model's outputs.
|
| 124 |
+
"""
|
| 125 |
+
first_target_xy: Literal["predicted", "cube_center"] = "predicted"
|
| 126 |
+
"""Diagnostic only: replace first target XY, retaining all other predictions."""
|
| 127 |
+
every_target_xy: Literal["predicted", "nearest_cube_center"] = "predicted"
|
| 128 |
+
"""Diagnostic only: replace EVERY target XY with the nearest cube center.
|
| 129 |
+
|
| 130 |
+
Isolates localization precision from phase advancement: height, orientation,
|
| 131 |
+
continuous gripper and the decision of when to advance remain the model's.
|
| 132 |
+
"""
|
| 133 |
+
|
| 134 |
+
@property
|
| 135 |
+
def diagnostic_xy(self):
|
| 136 |
+
"""Number of active privileged-XY interventions; zero for a scored run."""
|
| 137 |
+
return int(self.first_target_xy != "predicted") + int(
|
| 138 |
+
self.every_target_xy != "predicted"
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
@model_validator(mode="after")
|
| 142 |
+
def check_single_intervention(self):
|
| 143 |
+
if self.terminal_gripper_event and not self.honor_predicted_stop:
|
| 144 |
+
raise ValueError("Terminal gripper events require predicted-stop execution")
|
| 145 |
+
if self.honor_predicted_stop and (
|
| 146 |
+
self.mode != "planned"
|
| 147 |
+
or self.target_source != "keypose"
|
| 148 |
+
or self.hold_after_first_release
|
| 149 |
+
or self.first_close_hold
|
| 150 |
+
or self.motion_replan_steps
|
| 151 |
+
or self.carry_gripper_feedback
|
| 152 |
+
or self.resume_after_incomplete
|
| 153 |
+
or self.phase_gripper_events
|
| 154 |
+
or self.diagnostic_xy
|
| 155 |
+
or self.first_target_xyz_alpha is not None
|
| 156 |
+
or not self.reactive_gripper_gate
|
| 157 |
+
):
|
| 158 |
+
raise ValueError("Predicted stop requires an isolated planned context lane")
|
| 159 |
+
if self.hold_after_first_release and (
|
| 160 |
+
self.mode != "planned"
|
| 161 |
+
or self.target_source != "keypose"
|
| 162 |
+
or self.first_close_hold
|
| 163 |
+
or self.motion_replan_steps
|
| 164 |
+
or self.carry_gripper_feedback
|
| 165 |
+
or self.resume_after_incomplete
|
| 166 |
+
or self.phase_gripper_events
|
| 167 |
+
or self.diagnostic_xy
|
| 168 |
+
or self.first_target_xyz_alpha is not None
|
| 169 |
+
or not self.reactive_gripper_gate
|
| 170 |
+
):
|
| 171 |
+
raise ValueError("Release hold requires an isolated planned context lane")
|
| 172 |
+
if self.first_close_hold and (
|
| 173 |
+
self.mode != "planned"
|
| 174 |
+
or self.target_source != "keypose"
|
| 175 |
+
or self.motion_replan_steps
|
| 176 |
+
or self.carry_gripper_feedback
|
| 177 |
+
or self.resume_after_incomplete
|
| 178 |
+
or self.phase_gripper_events
|
| 179 |
+
or self.diagnostic_xy
|
| 180 |
+
or self.first_target_xyz_alpha is not None
|
| 181 |
+
or not self.reactive_gripper_gate
|
| 182 |
+
):
|
| 183 |
+
raise ValueError("First-close hold requires an isolated planned lane")
|
| 184 |
+
if self.motion_replan_steps and (
|
| 185 |
+
self.mode != "planned"
|
| 186 |
+
or self.target_source != "keypose"
|
| 187 |
+
or self.carry_gripper_feedback
|
| 188 |
+
or self.resume_after_incomplete
|
| 189 |
+
or self.phase_gripper_events
|
| 190 |
+
or self.diagnostic_xy
|
| 191 |
+
or self.first_target_xyz_alpha is not None
|
| 192 |
+
or not self.reactive_gripper_gate
|
| 193 |
+
):
|
| 194 |
+
raise ValueError("Motion replanning requires an isolated planned lane")
|
| 195 |
+
if self.phase_gripper_events and (
|
| 196 |
+
self.mode != "planned"
|
| 197 |
+
or self.target_source != "keypose"
|
| 198 |
+
or self.carry_gripper_feedback
|
| 199 |
+
or self.resume_after_incomplete
|
| 200 |
+
or self.diagnostic_xy
|
| 201 |
+
or self.first_target_xyz_alpha is not None
|
| 202 |
+
):
|
| 203 |
+
raise ValueError(
|
| 204 |
+
"Phase gripper events require an isolated planned keypose lane"
|
| 205 |
+
)
|
| 206 |
+
if not self.reactive_gripper_gate and self.mode != "reactive":
|
| 207 |
+
raise ValueError("Disabling the gripper gate requires reactive execution")
|
| 208 |
+
if self.carry_gripper_feedback and self.mode != "planned":
|
| 209 |
+
raise ValueError("Motion feedback carry requires planned execution")
|
| 210 |
+
if self.diagnostic_xy > 1:
|
| 211 |
+
raise ValueError(
|
| 212 |
+
"Choose one XY intervention; combining them confounds the diagnostic"
|
| 213 |
+
)
|
| 214 |
+
if self.first_target_xyz_alpha is not None:
|
| 215 |
+
if (
|
| 216 |
+
self.mode != "planned"
|
| 217 |
+
or self.target_source != "keypose"
|
| 218 |
+
or self.training_dataset is None
|
| 219 |
+
):
|
| 220 |
+
raise ValueError(
|
| 221 |
+
"First XYZ residual diagnostic requires planned keypose and training_dataset"
|
| 222 |
+
)
|
| 223 |
+
if self.diagnostic_xy:
|
| 224 |
+
raise ValueError(
|
| 225 |
+
"First XYZ residual diagnostic cannot combine with XY interventions"
|
| 226 |
+
)
|
| 227 |
+
if self.target_source != "keypose" and (
|
| 228 |
+
self.mode != "planned"
|
| 229 |
+
or self.diagnostic_xy
|
| 230 |
+
or self.training_dataset is not None
|
| 231 |
+
):
|
| 232 |
+
raise ValueError(
|
| 233 |
+
"Dense endpoint diagnostic uses planned execution without privileged interventions"
|
| 234 |
+
)
|
| 235 |
+
return self
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def reactive_action(current, target, previous_gripper, control, *, gripper_gate=True):
|
| 239 |
+
"""Apply the original TCP controller, optionally replacing its gripper only."""
|
| 240 |
+
command, reached, position_error, rotation_error = keypose_command(
|
| 241 |
+
current, target, previous_gripper, control
|
| 242 |
+
)
|
| 243 |
+
gated = command[..., -1].clone()
|
| 244 |
+
requested = target[..., -1].clamp(-1, 1)
|
| 245 |
+
would_change = bool((gated != requested).item())
|
| 246 |
+
if not gripper_gate:
|
| 247 |
+
command[..., -1] = requested
|
| 248 |
+
return command, {
|
| 249 |
+
"phase": "reactive",
|
| 250 |
+
"reached": bool(reached.item()),
|
| 251 |
+
"position_error_m": position_error.item(),
|
| 252 |
+
"rotation_error_rad": rotation_error.item(),
|
| 253 |
+
"requested_gripper": requested.item(),
|
| 254 |
+
"gated_gripper": gated.item(),
|
| 255 |
+
"gate_would_change_gripper": would_change,
|
| 256 |
+
"gripper_gate_blocked": bool(gripper_gate and would_change),
|
| 257 |
+
"reactive_gripper_gate": gripper_gate,
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def phase_prediction_details(agent):
|
| 262 |
+
"""Read only the latest batch-one prior forward; no environment phase input."""
|
| 263 |
+
logits = read_phase_logits(agent).detach().cpu()
|
| 264 |
+
if (
|
| 265 |
+
logits.shape != (1, len(KEYPOSE_PHASE_NAMES))
|
| 266 |
+
or not torch.isfinite(logits).all()
|
| 267 |
+
):
|
| 268 |
+
raise ValueError("Expected finite batch-one six-class prior phase logits")
|
| 269 |
+
return {
|
| 270 |
+
"phase_logits_prior": logits[0].tolist(),
|
| 271 |
+
"predicted_phase": int(logits[0].argmax().item()),
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def is_gripper_phase(details):
|
| 276 |
+
"""Only the current model argmax selects an event; no ordering or sign rule."""
|
| 277 |
+
index = details["predicted_phase"]
|
| 278 |
+
if index not in range(len(KEYPOSE_PHASE_NAMES)):
|
| 279 |
+
raise ValueError("Invalid predicted phase")
|
| 280 |
+
return KEYPOSE_PHASE_NAMES[index] in ("close_gripper", "open_gripper")
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def with_completed_target(observation, previous):
|
| 284 |
+
"""Encode the prior feedback-completed request; no expert phase is supplied.
|
| 285 |
+
|
| 286 |
+
Normally its arm path executed. The explicit first-close-hold intervention
|
| 287 |
+
preserves the requested pose despite bypassing it and logs that exception.
|
| 288 |
+
"""
|
| 289 |
+
context = np.zeros(11, dtype=np.float32)
|
| 290 |
+
if previous is not None:
|
| 291 |
+
value = np.asarray(previous, dtype=np.float32)
|
| 292 |
+
if value.shape != (10,) or not np.isfinite(value).all():
|
| 293 |
+
raise ValueError("Expected a finite completed world keypose10")
|
| 294 |
+
context[:10], context[10] = value, 1
|
| 295 |
+
return {**observation, "completed_target": context}
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def should_hold_first_close(predicted, executed_gripper, *, already_held):
|
| 299 |
+
"""First closing request after an actual nonnegative actuator command."""
|
| 300 |
+
target = torch.as_tensor(predicted)
|
| 301 |
+
if target.shape != (10,) or not torch.isfinite(target).all():
|
| 302 |
+
raise ValueError("Expected finite raw predicted world keypose10")
|
| 303 |
+
if executed_gripper is not None and not np.isfinite(executed_gripper):
|
| 304 |
+
raise ValueError("Expected a finite previously executed gripper command")
|
| 305 |
+
return bool(
|
| 306 |
+
not already_held
|
| 307 |
+
and executed_gripper is not None
|
| 308 |
+
and executed_gripper >= 0
|
| 309 |
+
and target[-1] < 0
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def is_first_release_request(predicted, executed_gripper, *, already_requested):
|
| 314 |
+
"""A predicted opening follows an actual negative actuator command."""
|
| 315 |
+
target = torch.as_tensor(predicted)
|
| 316 |
+
if target.shape != (10,) or not torch.isfinite(target).all():
|
| 317 |
+
raise ValueError("Expected finite raw predicted world keypose10")
|
| 318 |
+
if executed_gripper is not None and not np.isfinite(executed_gripper):
|
| 319 |
+
raise ValueError("Expected a finite previously executed gripper command")
|
| 320 |
+
return bool(
|
| 321 |
+
not already_requested
|
| 322 |
+
and executed_gripper is not None
|
| 323 |
+
and executed_gripper < 0
|
| 324 |
+
and target[-1] >= 0
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def completed_target_hold_command(command, feedback, *, query, hold_query):
|
| 329 |
+
"""Latch only a physically executed command after the selected feedback completes."""
|
| 330 |
+
if (
|
| 331 |
+
hold_query is None
|
| 332 |
+
or query != hold_query
|
| 333 |
+
or feedback.get("status") != "complete"
|
| 334 |
+
):
|
| 335 |
+
return None
|
| 336 |
+
result = np.asarray(command, dtype=np.float32).copy()
|
| 337 |
+
if result.shape != (8,) or not np.isfinite(result).all():
|
| 338 |
+
raise ValueError("Expected the finite executed joint/gripper command8")
|
| 339 |
+
return result
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def stop_prediction_details(agent):
|
| 343 |
+
"""Read the latest prior forward without another model call or oracle input."""
|
| 344 |
+
logits = read_stop_logits(agent).detach().cpu().clone()
|
| 345 |
+
if logits.shape != (1,) or not torch.isfinite(logits).all():
|
| 346 |
+
raise ValueError("Expected one finite stop-after-target logit")
|
| 347 |
+
return {
|
| 348 |
+
"stop_logit": float(logits[0]),
|
| 349 |
+
"stop_probability": float(logits[0].sigmoid()),
|
| 350 |
+
"stop_after_target": bool(logits[0] >= 0),
|
| 351 |
+
}
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def is_terminal_gripper_event(predicted, stop_after_target):
|
| 355 |
+
"""Use only the model's terminal intent and original gripper request."""
|
| 356 |
+
target = torch.as_tensor(predicted)
|
| 357 |
+
if target.shape != (10,) or not torch.isfinite(target).all():
|
| 358 |
+
raise ValueError("Expected finite raw predicted world keypose10")
|
| 359 |
+
return bool(stop_after_target and target[-1] >= 0)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def planning_state(base):
|
| 363 |
+
"""Read physical state without rendering or taking a simulation step."""
|
| 364 |
+
return {
|
| 365 |
+
"qpos": base.agent.robot.get_qpos().detach().cpu().numpy().copy(),
|
| 366 |
+
"qvel": base.agent.robot.get_qvel().detach().cpu().numpy().copy(),
|
| 367 |
+
"tcp": base.agent.tcp.pose.raw_pose.detach().cpu().numpy().copy(),
|
| 368 |
+
"elapsed_steps": torch.as_tensor(base.elapsed_steps).cpu().numpy().copy(),
|
| 369 |
+
}
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def verify_planning_unchanged(before, after):
|
| 373 |
+
if before.keys() != after.keys():
|
| 374 |
+
raise ValueError("Planning state fields differ")
|
| 375 |
+
for key in before:
|
| 376 |
+
if not np.array_equal(before[key], after[key]):
|
| 377 |
+
raise RuntimeError(f"Planner dry-run changed physical {key}")
|
| 378 |
+
return True
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def executor_trace(executor):
|
| 382 |
+
"""Log active execution separately from the latest (possibly rejected) query."""
|
| 383 |
+
return {
|
| 384 |
+
"goal_id": executor.goal_id,
|
| 385 |
+
"path_revision": executor.path_revision,
|
| 386 |
+
"active_target_query": executor.active_query,
|
| 387 |
+
"completed_target_from_query": executor.completed_target_query,
|
| 388 |
+
"completed_target": None
|
| 389 |
+
if executor.completed_target is None
|
| 390 |
+
else executor.completed_target.tolist(),
|
| 391 |
+
"completed_goals": executor.completed_goals,
|
| 392 |
+
"motion_steps_since_attempt": executor.motion_steps_since_attempt,
|
| 393 |
+
"goal_motion_steps": executor.goal_motion_steps,
|
| 394 |
+
"total_motion_steps": executor.total_motion_steps,
|
| 395 |
+
"goal_replan_attempts": executor.goal_replan_attempts,
|
| 396 |
+
}
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def run(config: EvaluationConfig):
|
| 400 |
+
torch.set_num_threads(4)
|
| 401 |
+
torch.manual_seed(0)
|
| 402 |
+
np.random.seed(0)
|
| 403 |
+
config.output_dir.mkdir(parents=True, exist_ok=False)
|
| 404 |
+
(config.output_dir / "plans").mkdir()
|
| 405 |
+
if config.motion_replan_steps:
|
| 406 |
+
(config.output_dir / "query_observations").mkdir()
|
| 407 |
+
reference = ReferenceConfig.model_validate_json(config.reference.read_text())
|
| 408 |
+
context_enabled = reference.policy.keypose_context != "none"
|
| 409 |
+
stop_enabled = reference.policy.keypose_stop_head
|
| 410 |
+
if config.honor_predicted_stop and not stop_enabled:
|
| 411 |
+
raise ValueError(
|
| 412 |
+
"Predicted stop requires a checkpoint trained with a stop head"
|
| 413 |
+
)
|
| 414 |
+
if stop_enabled and (
|
| 415 |
+
config.hold_after_first_release
|
| 416 |
+
or config.first_close_hold
|
| 417 |
+
or config.motion_replan_steps
|
| 418 |
+
):
|
| 419 |
+
raise ValueError("Stop-head evaluation cannot combine execution interventions")
|
| 420 |
+
if config.hold_after_first_release and not context_enabled:
|
| 421 |
+
raise ValueError("Release hold requires a context-enabled keypose checkpoint")
|
| 422 |
+
if context_enabled and (
|
| 423 |
+
config.mode != "planned"
|
| 424 |
+
or config.target_source != "keypose"
|
| 425 |
+
or config.diagnostic_xy
|
| 426 |
+
or config.first_target_xyz_alpha is not None
|
| 427 |
+
or config.phase_gripper_events
|
| 428 |
+
or config.carry_gripper_feedback
|
| 429 |
+
or config.resume_after_incomplete
|
| 430 |
+
):
|
| 431 |
+
raise ValueError(
|
| 432 |
+
"Completed goal conditioning requires an isolated planned lane"
|
| 433 |
+
)
|
| 434 |
+
if config.phase_gripper_events and reference.policy.keypose_phase_weight <= 0:
|
| 435 |
+
raise ValueError(
|
| 436 |
+
"Phase gripper events require a checkpoint trained with phase outputs"
|
| 437 |
+
)
|
| 438 |
+
dense_endpoint = config.target_source == "dense_chunk_endpoint"
|
| 439 |
+
relative_endpoint = config.target_source == "chunk_relative_endpoint"
|
| 440 |
+
if dense_endpoint or relative_endpoint:
|
| 441 |
+
if not (
|
| 442 |
+
reference.policy.keypose is None
|
| 443 |
+
and reference.policy.method
|
| 444 |
+
== ("chunk_relative" if relative_endpoint else "cvae")
|
| 445 |
+
and reference.policy.action_encoding == "rotation6d"
|
| 446 |
+
and reference.control_mode == "pd_ee_delta_pose"
|
| 447 |
+
and reference.num_queries == 30
|
| 448 |
+
and not reference.gripper_execution.active
|
| 449 |
+
):
|
| 450 |
+
raise ValueError("Expected frozen 30-query dense CVAE pose6D model")
|
| 451 |
+
elif reference.policy.keypose is None:
|
| 452 |
+
raise ValueError("Direct keypose evaluation requires a trained keypose model")
|
| 453 |
+
control = reference.policy.keypose or KeyposeControlConfig()
|
| 454 |
+
module = load_official(reference)
|
| 455 |
+
checkpoint, provenance = load_checkpoint(reference.checkpoint)
|
| 456 |
+
check_policy_checkpoint(checkpoint, reference)
|
| 457 |
+
first_xyz_oracle = (
|
| 458 |
+
TrainingFirstTargetXYZ(
|
| 459 |
+
FirstTargetXYZConfig(
|
| 460 |
+
dataset=config.training_dataset, alpha=config.first_target_xyz_alpha
|
| 461 |
+
)
|
| 462 |
+
)
|
| 463 |
+
if config.first_target_xyz_alpha is not None
|
| 464 |
+
else None
|
| 465 |
+
)
|
| 466 |
+
metadata = json.loads(reference.demonstration_metadata.read_text())
|
| 467 |
+
sensor = metadata["env_info"]["env_kwargs"]["sensor_configs"]
|
| 468 |
+
control_mode = "pd_joint_pos" if config.mode == "planned" else "pd_ee_delta_pose"
|
| 469 |
+
raw = gym.make(
|
| 470 |
+
"StackCube-v1",
|
| 471 |
+
obs_mode="rgb",
|
| 472 |
+
control_mode=control_mode,
|
| 473 |
+
reward_mode="sparse",
|
| 474 |
+
render_mode="rgb_array",
|
| 475 |
+
sim_backend="physx_cpu",
|
| 476 |
+
reconfiguration_freq=1,
|
| 477 |
+
max_episode_steps=config.max_steps,
|
| 478 |
+
sensor_configs=sensor,
|
| 479 |
+
)
|
| 480 |
+
if config.training_dataset is not None:
|
| 481 |
+
raw = TrainingSceneReset(
|
| 482 |
+
TrainingResetConfig(env=raw, dataset=config.training_dataset)
|
| 483 |
+
)
|
| 484 |
+
env = ReleasedSupportAudit(
|
| 485 |
+
AuditConfig(
|
| 486 |
+
env=raw,
|
| 487 |
+
snapshots=config.output_dir / "raw_observations",
|
| 488 |
+
stride=10,
|
| 489 |
+
seed_start=config.seed_start,
|
| 490 |
+
)
|
| 491 |
+
)
|
| 492 |
+
env = PolicyVideo(
|
| 493 |
+
PolicyVideoConfig(
|
| 494 |
+
env=env,
|
| 495 |
+
output_dir=config.output_dir / "videos",
|
| 496 |
+
seeds=config.video_seeds,
|
| 497 |
+
label=f"{config.target_source}-{config.mode}",
|
| 498 |
+
max_steps=config.max_steps,
|
| 499 |
+
)
|
| 500 |
+
)
|
| 501 |
+
env = module.FlattenRGBDObservationWrapper(env, depth=False)
|
| 502 |
+
env = CPUGymWrapper(env, ignore_terminations=True, record_metrics=True)
|
| 503 |
+
# Build against the checkpoint's original pose controller7, independent of
|
| 504 |
+
# physical joint ABI8. The policy config distinguishes world poses from deltas.
|
| 505 |
+
spaces = SimpleNamespace(
|
| 506 |
+
single_observation_space=env.observation_space,
|
| 507 |
+
single_action_space=gym.spaces.Box(-1, 1, (7,), dtype=np.float32),
|
| 508 |
+
)
|
| 509 |
+
episodes = []
|
| 510 |
+
started = time.time()
|
| 511 |
+
try:
|
| 512 |
+
agent = (
|
| 513 |
+
build_policy(
|
| 514 |
+
module,
|
| 515 |
+
spaces,
|
| 516 |
+
module.args,
|
| 517 |
+
reference.policy,
|
| 518 |
+
checkpoint.get("normalization"),
|
| 519 |
+
)
|
| 520 |
+
.cuda()
|
| 521 |
+
.eval()
|
| 522 |
+
)
|
| 523 |
+
agent.load_state_dict(checkpoint["ema_agent"])
|
| 524 |
+
with (
|
| 525 |
+
(config.output_dir / "steps.jsonl").open("x") as trace,
|
| 526 |
+
(config.output_dir / "predictions.jsonl").open("x") as predictions,
|
| 527 |
+
):
|
| 528 |
+
for seed in range(config.seed_start, config.seed_start + config.episodes):
|
| 529 |
+
obs, _ = env.reset(seed=seed)
|
| 530 |
+
base = env.unwrapped
|
| 531 |
+
if dense_endpoint or relative_endpoint:
|
| 532 |
+
check_endpoint_controller(
|
| 533 |
+
base.agent._controller_configs["pd_ee_delta_pose"]["arm"]
|
| 534 |
+
)
|
| 535 |
+
if relative_endpoint:
|
| 536 |
+
np.testing.assert_allclose(
|
| 537 |
+
base.agent.robot.pose.raw_pose[0, 3:].cpu().numpy(),
|
| 538 |
+
[1, 0, 0, 0],
|
| 539 |
+
atol=1e-5,
|
| 540 |
+
)
|
| 541 |
+
torch.save(
|
| 542 |
+
{
|
| 543 |
+
"observation": obs,
|
| 544 |
+
"cubeA_pose": base.cubeA.pose.raw_pose.cpu(),
|
| 545 |
+
"cubeB_pose": base.cubeB.pose.raw_pose.cpu(),
|
| 546 |
+
},
|
| 547 |
+
config.output_dir / f"initial-{seed}.pt",
|
| 548 |
+
)
|
| 549 |
+
grip = torch.tensor(
|
| 550 |
+
[np.clip((obs["state"][7:9].mean() + 0.01) / 0.05 * 2 - 1, -1, 1)],
|
| 551 |
+
dtype=torch.float32,
|
| 552 |
+
)
|
| 553 |
+
planner = (
|
| 554 |
+
MplibKeyposePlanner(PlannerConfig(env=env))
|
| 555 |
+
if config.mode == "planned"
|
| 556 |
+
else None
|
| 557 |
+
)
|
| 558 |
+
executor = PlannedKeyposeExecutor(
|
| 559 |
+
PlannedExecutorConfig(
|
| 560 |
+
control=control,
|
| 561 |
+
gripper_completion=config.gripper_completion,
|
| 562 |
+
initial_gripper=float(grip.item()),
|
| 563 |
+
resume_after_incomplete=config.resume_after_incomplete,
|
| 564 |
+
carry_gripper_feedback=config.carry_gripper_feedback,
|
| 565 |
+
motion_replan_steps=config.motion_replan_steps,
|
| 566 |
+
)
|
| 567 |
+
)
|
| 568 |
+
feedback_reader = (
|
| 569 |
+
PandaGripperFeedback(
|
| 570 |
+
FeedbackReaderConfig(
|
| 571 |
+
env=env, completion=config.gripper_completion
|
| 572 |
+
)
|
| 573 |
+
)
|
| 574 |
+
if planner is not None
|
| 575 |
+
else None
|
| 576 |
+
)
|
| 577 |
+
calls, failures, plans_completed, gripper_events = 0, 0, 0, 0
|
| 578 |
+
previous_command = None
|
| 579 |
+
first_close_hold_query = None
|
| 580 |
+
release_query, release_request_step = None, None
|
| 581 |
+
release_feedback_complete_step, hold_started_step = None, None
|
| 582 |
+
stop_query, stop_request_step, stop_feedback_complete_step = (
|
| 583 |
+
None,
|
| 584 |
+
None,
|
| 585 |
+
None,
|
| 586 |
+
)
|
| 587 |
+
terminal_command = None
|
| 588 |
+
terminal_event_query = None
|
| 589 |
+
terminal_hold_steps = 0
|
| 590 |
+
for step in range(config.max_steps):
|
| 591 |
+
before = obs["state"].copy()
|
| 592 |
+
replan = executor.needs_motion_replan
|
| 593 |
+
if terminal_command is None and (
|
| 594 |
+
config.mode == "reactive" or executor.needs_prediction or replan
|
| 595 |
+
):
|
| 596 |
+
if (
|
| 597 |
+
config.mode == "planned"
|
| 598 |
+
and calls
|
| 599 |
+
and not config.motion_replan_steps
|
| 600 |
+
):
|
| 601 |
+
plans_completed += 1
|
| 602 |
+
query_state_before = (
|
| 603 |
+
executor_trace(executor)
|
| 604 |
+
if config.motion_replan_steps
|
| 605 |
+
else {}
|
| 606 |
+
)
|
| 607 |
+
inference_start = (
|
| 608 |
+
time.monotonic() if config.motion_replan_steps else None
|
| 609 |
+
)
|
| 610 |
+
endpoint_details = {}
|
| 611 |
+
if dense_endpoint:
|
| 612 |
+
chunk = predict_action_chunk(agent, obs)
|
| 613 |
+
if chunk.shape != (reference.num_queries, 10):
|
| 614 |
+
raise ValueError(
|
| 615 |
+
"Dense checkpoint returned unexpected chunk shape"
|
| 616 |
+
)
|
| 617 |
+
root_pose = base.agent.robot.pose.raw_pose[0].cpu()
|
| 618 |
+
predicted, decoded = dense_chunk_endpoint(
|
| 619 |
+
chunk, before[18:25], root_pose
|
| 620 |
+
)
|
| 621 |
+
endpoint_details = {
|
| 622 |
+
"dense_chunk": chunk.tolist(),
|
| 623 |
+
"decoded_commands": decoded.tolist(),
|
| 624 |
+
"robot_root_pose": root_pose.tolist(),
|
| 625 |
+
"model_target_semantics": "nominal composed endpoint; raw model output is dense_chunk",
|
| 626 |
+
}
|
| 627 |
+
elif relative_endpoint:
|
| 628 |
+
chunk = predict_action_chunk(agent, obs)
|
| 629 |
+
if chunk.shape != (reference.num_queries, 10):
|
| 630 |
+
raise ValueError(
|
| 631 |
+
"Expected a 30x10 fixed-reference chunk"
|
| 632 |
+
)
|
| 633 |
+
anchor = torch.tensor(before[18:25])
|
| 634 |
+
predicted = chunk_relative_to_world(chunk[-1], anchor)
|
| 635 |
+
endpoint_details = {
|
| 636 |
+
"relative_chunk": chunk.tolist(),
|
| 637 |
+
"chunk_start_tcp": anchor.tolist(),
|
| 638 |
+
"selected_query_index": len(chunk) - 1,
|
| 639 |
+
"model_target_semantics": "query29 restored from its fixed chunk-start TCP; no delta accumulation",
|
| 640 |
+
}
|
| 641 |
+
else:
|
| 642 |
+
model_obs = (
|
| 643 |
+
with_completed_target(obs, executor.completed_target)
|
| 644 |
+
if context_enabled
|
| 645 |
+
else obs
|
| 646 |
+
)
|
| 647 |
+
predicted = predict_keypose(agent, model_obs)
|
| 648 |
+
if context_enabled:
|
| 649 |
+
endpoint_details = {
|
| 650 |
+
"completed_target_input": model_obs[
|
| 651 |
+
"completed_target"
|
| 652 |
+
].tolist(),
|
| 653 |
+
"completed_target_from_query": executor.completed_target_query,
|
| 654 |
+
"context_mode": reference.policy.keypose_context,
|
| 655 |
+
}
|
| 656 |
+
if config.first_close_hold:
|
| 657 |
+
endpoint_details.update(
|
| 658 |
+
requested_target_context=model_obs[
|
| 659 |
+
"completed_target"
|
| 660 |
+
].tolist(),
|
| 661 |
+
context_semantics="historical_requested_target_after_feedback",
|
| 662 |
+
context_arm_pose_executed=None
|
| 663 |
+
if executor.completed_target_query is None
|
| 664 |
+
else executor.completed_target_query
|
| 665 |
+
!= first_close_hold_query,
|
| 666 |
+
)
|
| 667 |
+
if reference.policy.keypose_phase_weight > 0:
|
| 668 |
+
endpoint_details = phase_prediction_details(agent)
|
| 669 |
+
if stop_enabled:
|
| 670 |
+
endpoint_details.update(stop_prediction_details(agent))
|
| 671 |
+
if config.motion_replan_steps:
|
| 672 |
+
inference_wall_s = time.monotonic() - inference_start
|
| 673 |
+
observation_path = (
|
| 674 |
+
config.output_dir
|
| 675 |
+
/ f"query_observations/seed{seed}-query{calls + 1}.npz"
|
| 676 |
+
)
|
| 677 |
+
np.savez_compressed(observation_path, **model_obs)
|
| 678 |
+
target = first_target_intervention(
|
| 679 |
+
predicted,
|
| 680 |
+
query=calls + 1,
|
| 681 |
+
cube_xy=base.cubeA.pose.p[0, :2].cpu()
|
| 682 |
+
if config.first_target_xy == "cube_center" and calls == 0
|
| 683 |
+
else None,
|
| 684 |
+
)
|
| 685 |
+
nearest = None
|
| 686 |
+
if config.every_target_xy == "nearest_cube_center":
|
| 687 |
+
# Live poses: a perfect localizer would read current state.
|
| 688 |
+
target, nearest = nearest_cube_intervention(
|
| 689 |
+
predicted,
|
| 690 |
+
cubes={
|
| 691 |
+
"cubeA": base.cubeA.pose.p[0, :2].cpu(),
|
| 692 |
+
"cubeB": base.cubeB.pose.p[0, :2].cpu(),
|
| 693 |
+
},
|
| 694 |
+
)
|
| 695 |
+
xyz_intervention = None
|
| 696 |
+
if first_xyz_oracle is not None:
|
| 697 |
+
target, xyz_intervention = first_xyz_oracle.apply(
|
| 698 |
+
predicted, query=calls + 1, seed=seed
|
| 699 |
+
)
|
| 700 |
+
calls += 1
|
| 701 |
+
prediction = {
|
| 702 |
+
"seed": seed,
|
| 703 |
+
"step": step,
|
| 704 |
+
"query": calls,
|
| 705 |
+
"target": target.tolist(),
|
| 706 |
+
"model_target": predicted.tolist(),
|
| 707 |
+
"first_xy_overridden": config.first_target_xy
|
| 708 |
+
== "cube_center"
|
| 709 |
+
and calls == 1,
|
| 710 |
+
"every_xy_overridden": nearest is not None,
|
| 711 |
+
"state_before": before.tolist(),
|
| 712 |
+
**(
|
| 713 |
+
{"nearest_cube": nearest} if nearest is not None else {}
|
| 714 |
+
),
|
| 715 |
+
**(
|
| 716 |
+
{"first_xyz_intervention": xyz_intervention}
|
| 717 |
+
if xyz_intervention is not None
|
| 718 |
+
else {}
|
| 719 |
+
),
|
| 720 |
+
**endpoint_details,
|
| 721 |
+
}
|
| 722 |
+
if stop_enabled:
|
| 723 |
+
if stop_query is None and prediction["stop_after_target"]:
|
| 724 |
+
stop_query, stop_request_step = calls, step
|
| 725 |
+
prediction.update(
|
| 726 |
+
stop_query=stop_query,
|
| 727 |
+
stop_request_step=stop_request_step,
|
| 728 |
+
honor_predicted_stop=config.honor_predicted_stop,
|
| 729 |
+
)
|
| 730 |
+
event = config.phase_gripper_events and is_gripper_phase(
|
| 731 |
+
endpoint_details
|
| 732 |
+
)
|
| 733 |
+
hold_close = (
|
| 734 |
+
config.first_close_hold
|
| 735 |
+
and should_hold_first_close(
|
| 736 |
+
predicted,
|
| 737 |
+
None
|
| 738 |
+
if previous_command is None
|
| 739 |
+
else float(previous_command[-1]),
|
| 740 |
+
already_held=first_close_hold_query is not None,
|
| 741 |
+
)
|
| 742 |
+
)
|
| 743 |
+
hold_terminal = (
|
| 744 |
+
config.terminal_gripper_event
|
| 745 |
+
and is_terminal_gripper_event(
|
| 746 |
+
predicted, prediction["stop_after_target"]
|
| 747 |
+
)
|
| 748 |
+
)
|
| 749 |
+
if config.terminal_gripper_event:
|
| 750 |
+
prediction.update(
|
| 751 |
+
terminal_gripper_event=hold_terminal,
|
| 752 |
+
arm_pose_executed=False if hold_terminal else None,
|
| 753 |
+
)
|
| 754 |
+
if config.hold_after_first_release:
|
| 755 |
+
release_requested = is_first_release_request(
|
| 756 |
+
predicted,
|
| 757 |
+
None
|
| 758 |
+
if previous_command is None
|
| 759 |
+
else float(previous_command[-1]),
|
| 760 |
+
already_requested=release_query is not None,
|
| 761 |
+
)
|
| 762 |
+
if release_requested:
|
| 763 |
+
release_query, release_request_step = calls, step
|
| 764 |
+
prediction.update(
|
| 765 |
+
release_requested=release_requested,
|
| 766 |
+
release_query=release_query,
|
| 767 |
+
release_request_step=release_request_step,
|
| 768 |
+
previous_executed_gripper=None
|
| 769 |
+
if previous_command is None
|
| 770 |
+
else float(previous_command[-1]),
|
| 771 |
+
)
|
| 772 |
+
if config.first_close_hold:
|
| 773 |
+
prediction.update(
|
| 774 |
+
first_close_hold_triggered=hold_close,
|
| 775 |
+
previous_executed_gripper=None
|
| 776 |
+
if previous_command is None
|
| 777 |
+
else float(previous_command[-1]),
|
| 778 |
+
arm_pose_executed=False if hold_close else None,
|
| 779 |
+
)
|
| 780 |
+
if event or hold_close or hold_terminal:
|
| 781 |
+
executor.begin_gripper(
|
| 782 |
+
target, before[:9], source_query=calls
|
| 783 |
+
)
|
| 784 |
+
if hold_close:
|
| 785 |
+
first_close_hold_query = calls
|
| 786 |
+
elif hold_terminal:
|
| 787 |
+
terminal_event_query = calls
|
| 788 |
+
else:
|
| 789 |
+
gripper_events += 1
|
| 790 |
+
prediction.update(
|
| 791 |
+
planning_status="first_close_hold"
|
| 792 |
+
if hold_close
|
| 793 |
+
else "terminal_gripper_event"
|
| 794 |
+
if hold_terminal
|
| 795 |
+
else "gripper_event",
|
| 796 |
+
planning_wall_s=0.0,
|
| 797 |
+
path_steps=0,
|
| 798 |
+
hold_arm_qpos=before[:7].tolist(),
|
| 799 |
+
)
|
| 800 |
+
elif planner is not None:
|
| 801 |
+
physical_before_plan = (
|
| 802 |
+
planning_state(base)
|
| 803 |
+
if config.motion_replan_steps
|
| 804 |
+
else None
|
| 805 |
+
)
|
| 806 |
+
start = time.monotonic()
|
| 807 |
+
plan = planner.plan(target)
|
| 808 |
+
prediction["planning_wall_s"] = time.monotonic() - start
|
| 809 |
+
prediction["planning_status"] = planner.last_status
|
| 810 |
+
failures += int(plan is None)
|
| 811 |
+
if config.motion_replan_steps:
|
| 812 |
+
unchanged = verify_planning_unchanged(
|
| 813 |
+
physical_before_plan, planning_state(base)
|
| 814 |
+
)
|
| 815 |
+
if plan is not None:
|
| 816 |
+
np.savez_compressed(
|
| 817 |
+
config.output_dir
|
| 818 |
+
/ f"plans/seed{seed}-query{calls}.npz",
|
| 819 |
+
position=plan["position"],
|
| 820 |
+
velocity=plan["velocity"],
|
| 821 |
+
time=plan["time"],
|
| 822 |
+
)
|
| 823 |
+
prediction["path_steps"] = len(plan["position"])
|
| 824 |
+
if replan:
|
| 825 |
+
accepted = executor.replace_motion_plan(
|
| 826 |
+
target,
|
| 827 |
+
None if plan is None else plan["position"],
|
| 828 |
+
source_query=calls,
|
| 829 |
+
)
|
| 830 |
+
else:
|
| 831 |
+
executor.begin(
|
| 832 |
+
target,
|
| 833 |
+
None if plan is None else plan["position"],
|
| 834 |
+
before[:9],
|
| 835 |
+
source_query=calls,
|
| 836 |
+
)
|
| 837 |
+
accepted = plan is not None
|
| 838 |
+
if config.motion_replan_steps:
|
| 839 |
+
prediction.update(
|
| 840 |
+
query_kind="motion_replan"
|
| 841 |
+
if replan
|
| 842 |
+
else "goal_start",
|
| 843 |
+
candidate_target=target.tolist(),
|
| 844 |
+
accepted=accepted,
|
| 845 |
+
active_target=executor.target.tolist(),
|
| 846 |
+
query_state_before=query_state_before,
|
| 847 |
+
**executor_trace(executor),
|
| 848 |
+
candidate_path_steps=0
|
| 849 |
+
if plan is None
|
| 850 |
+
else len(plan["position"]),
|
| 851 |
+
dry_run_state_unchanged=unchanged,
|
| 852 |
+
inference_wall_s=inference_wall_s,
|
| 853 |
+
inference_planning_wall_s=inference_wall_s
|
| 854 |
+
+ prediction["planning_wall_s"],
|
| 855 |
+
deadline_50ms_exceeded=inference_wall_s
|
| 856 |
+
+ prediction["planning_wall_s"]
|
| 857 |
+
> 0.05,
|
| 858 |
+
deadline_200ms_exceeded=inference_wall_s
|
| 859 |
+
+ prediction["planning_wall_s"]
|
| 860 |
+
> 0.2,
|
| 861 |
+
observation_file=str(
|
| 862 |
+
observation_path.relative_to(config.output_dir)
|
| 863 |
+
),
|
| 864 |
+
observation_sha256=hashlib.sha256(
|
| 865 |
+
observation_path.read_bytes()
|
| 866 |
+
).hexdigest(),
|
| 867 |
+
)
|
| 868 |
+
if accepted:
|
| 869 |
+
prediction["first_command_minus_qpos"] = (
|
| 870 |
+
executor.path[0] - before[:7]
|
| 871 |
+
).tolist()
|
| 872 |
+
prediction["first_command_minus_previous"] = (
|
| 873 |
+
None
|
| 874 |
+
if previous_command is None
|
| 875 |
+
else (
|
| 876 |
+
executor.path[0] - previous_command[:7]
|
| 877 |
+
).tolist()
|
| 878 |
+
)
|
| 879 |
+
# A failed candidate must never become the executed target.
|
| 880 |
+
target = executor.target.clone()
|
| 881 |
+
predictions.write(json.dumps(prediction) + "\n")
|
| 882 |
+
phase_before = executor.phase
|
| 883 |
+
if terminal_command is not None:
|
| 884 |
+
command = terminal_command.copy()
|
| 885 |
+
if hold_started_step is None:
|
| 886 |
+
hold_started_step = step
|
| 887 |
+
terminal_hold_steps += 1
|
| 888 |
+
details = {
|
| 889 |
+
"phase": "terminal_hold",
|
| 890 |
+
"held_command": command.tolist(),
|
| 891 |
+
}
|
| 892 |
+
elif planner is None:
|
| 893 |
+
command_tensor, details = reactive_action(
|
| 894 |
+
torch.tensor(before[18:25])[None],
|
| 895 |
+
target[None],
|
| 896 |
+
grip,
|
| 897 |
+
control,
|
| 898 |
+
gripper_gate=config.reactive_gripper_gate,
|
| 899 |
+
)
|
| 900 |
+
command = command_tensor[0].numpy()
|
| 901 |
+
grip = command_tensor[:, -1].clone()
|
| 902 |
+
else:
|
| 903 |
+
command, details = executor.command(before[18:25])
|
| 904 |
+
obs, _, terminated, truncated, info = env.step(command)
|
| 905 |
+
if config.motion_replan_steps and details["phase"] == "trajectory":
|
| 906 |
+
executor.observe_motion_step()
|
| 907 |
+
measured_gripper = (
|
| 908 |
+
feedback_reader.read(
|
| 909 |
+
float(command[-1])
|
| 910 |
+
if config.carry_gripper_feedback
|
| 911 |
+
else executor.gripper
|
| 912 |
+
)
|
| 913 |
+
if planner is not None and details["phase"] != "terminal_hold"
|
| 914 |
+
else None
|
| 915 |
+
)
|
| 916 |
+
if planner is not None and details["phase"] == "gripper":
|
| 917 |
+
details["gripper_feedback"] = executor.observe_gripper(
|
| 918 |
+
measured_gripper
|
| 919 |
+
)
|
| 920 |
+
elif (
|
| 921 |
+
planner is not None
|
| 922 |
+
and config.carry_gripper_feedback
|
| 923 |
+
and details["phase"] == "trajectory"
|
| 924 |
+
):
|
| 925 |
+
details["motion_gripper_feedback"] = (
|
| 926 |
+
executor.observe_motion_gripper(measured_gripper)
|
| 927 |
+
)
|
| 928 |
+
if config.motion_replan_steps:
|
| 929 |
+
details.update(
|
| 930 |
+
**executor_trace(executor),
|
| 931 |
+
phase_before=phase_before,
|
| 932 |
+
phase_after=executor.phase,
|
| 933 |
+
qpos_before=before[:9].tolist(),
|
| 934 |
+
qvel_before=before[9:18].tolist(),
|
| 935 |
+
qvel_after=obs["state"][9:18].tolist(),
|
| 936 |
+
completion_published=details.get(
|
| 937 |
+
"gripper_feedback", {}
|
| 938 |
+
).get("status")
|
| 939 |
+
== "complete",
|
| 940 |
+
)
|
| 941 |
+
previous_command = command.copy()
|
| 942 |
+
if config.first_close_hold:
|
| 943 |
+
completed_now = (
|
| 944 |
+
details.get("gripper_feedback", {}).get("status")
|
| 945 |
+
== "complete"
|
| 946 |
+
)
|
| 947 |
+
details.update(
|
| 948 |
+
first_close_hold_query=first_close_hold_query,
|
| 949 |
+
first_close_hold_active=calls == first_close_hold_query,
|
| 950 |
+
arm_pose_executed=False
|
| 951 |
+
if calls == first_close_hold_query
|
| 952 |
+
else (True if completed_now else None),
|
| 953 |
+
request_feedback_completed=completed_now,
|
| 954 |
+
completed_target_from_query=executor.completed_target_query,
|
| 955 |
+
completed_target_arm_pose_executed=None
|
| 956 |
+
if executor.completed_target_query is None
|
| 957 |
+
else executor.completed_target_query
|
| 958 |
+
!= first_close_hold_query,
|
| 959 |
+
)
|
| 960 |
+
previous_command = command.copy()
|
| 961 |
+
if config.hold_after_first_release:
|
| 962 |
+
if terminal_command is None:
|
| 963 |
+
terminal_command = completed_target_hold_command(
|
| 964 |
+
command,
|
| 965 |
+
details.get("gripper_feedback", {}),
|
| 966 |
+
query=calls,
|
| 967 |
+
hold_query=release_query,
|
| 968 |
+
)
|
| 969 |
+
if terminal_command is not None:
|
| 970 |
+
release_feedback_complete_step = step
|
| 971 |
+
details.update(
|
| 972 |
+
release_query=release_query,
|
| 973 |
+
release_request_step=release_request_step,
|
| 974 |
+
release_feedback_complete_step=release_feedback_complete_step,
|
| 975 |
+
hold_started_step=hold_started_step,
|
| 976 |
+
terminal_hold_steps=terminal_hold_steps,
|
| 977 |
+
)
|
| 978 |
+
previous_command = command.copy()
|
| 979 |
+
if stop_enabled:
|
| 980 |
+
if stop_feedback_complete_step is None:
|
| 981 |
+
completed_command = completed_target_hold_command(
|
| 982 |
+
command,
|
| 983 |
+
details.get("gripper_feedback", {}),
|
| 984 |
+
query=calls,
|
| 985 |
+
hold_query=stop_query,
|
| 986 |
+
)
|
| 987 |
+
if completed_command is not None:
|
| 988 |
+
stop_feedback_complete_step = step
|
| 989 |
+
if config.honor_predicted_stop:
|
| 990 |
+
terminal_command = completed_command
|
| 991 |
+
details.update(
|
| 992 |
+
stop_query=stop_query,
|
| 993 |
+
stop_request_step=stop_request_step,
|
| 994 |
+
stop_feedback_complete_step=stop_feedback_complete_step,
|
| 995 |
+
hold_started_step=hold_started_step,
|
| 996 |
+
terminal_hold_steps=terminal_hold_steps,
|
| 997 |
+
)
|
| 998 |
+
if config.terminal_gripper_event:
|
| 999 |
+
details.update(
|
| 1000 |
+
terminal_event_query=terminal_event_query,
|
| 1001 |
+
terminal_gripper_event_active=calls == terminal_event_query,
|
| 1002 |
+
arm_pose_executed=False
|
| 1003 |
+
if calls == terminal_event_query
|
| 1004 |
+
else None,
|
| 1005 |
+
)
|
| 1006 |
+
assert not terminated and bool(truncated) == (
|
| 1007 |
+
step == config.max_steps - 1
|
| 1008 |
+
)
|
| 1009 |
+
trace.write(
|
| 1010 |
+
json.dumps(
|
| 1011 |
+
{
|
| 1012 |
+
"seed": seed,
|
| 1013 |
+
"step": step,
|
| 1014 |
+
"query": calls,
|
| 1015 |
+
"target": target.tolist(),
|
| 1016 |
+
"command": command.tolist(),
|
| 1017 |
+
"tcp_before": before[18:25].tolist(),
|
| 1018 |
+
"tcp_after": obs["state"][18:25].tolist(),
|
| 1019 |
+
"qpos_after": obs["state"][:9].tolist(),
|
| 1020 |
+
"success": bool(info["success"]),
|
| 1021 |
+
**details,
|
| 1022 |
+
}
|
| 1023 |
+
)
|
| 1024 |
+
+ "\n"
|
| 1025 |
+
)
|
| 1026 |
+
row = {k: np.asarray(v).item() for k, v in info["episode"].items()}
|
| 1027 |
+
row.update(
|
| 1028 |
+
seed=seed,
|
| 1029 |
+
audit_release_once=bool(info["audit_release_once"]),
|
| 1030 |
+
audit_release_at_end=bool(info["audit_release_at_end"]),
|
| 1031 |
+
steps=config.max_steps,
|
| 1032 |
+
policy_calls=calls,
|
| 1033 |
+
planning_failures=failures,
|
| 1034 |
+
completed_plans=executor.completed_goals
|
| 1035 |
+
if config.motion_replan_steps
|
| 1036 |
+
else plans_completed
|
| 1037 |
+
+ int(planner is not None and executor.needs_prediction),
|
| 1038 |
+
last_phase="terminal_hold"
|
| 1039 |
+
if terminal_hold_steps
|
| 1040 |
+
else executor.phase
|
| 1041 |
+
if planner
|
| 1042 |
+
else "reactive",
|
| 1043 |
+
# Cumulative: resuming clears the phase that used to record it.
|
| 1044 |
+
# With resume disabled a timeout is terminal, so this still
|
| 1045 |
+
# equals the previous 0/1 indicator on every scored run.
|
| 1046 |
+
gripper_timeouts=executor.gripper_timeouts if planner else 0,
|
| 1047 |
+
gripper_arrests=executor.gripper_arrests if planner else 0,
|
| 1048 |
+
)
|
| 1049 |
+
if config.carry_gripper_feedback:
|
| 1050 |
+
row["gripper_feedback_carried"] = executor.gripper_feedback_carried
|
| 1051 |
+
if config.phase_gripper_events:
|
| 1052 |
+
row["gripper_event_queries"] = gripper_events
|
| 1053 |
+
if config.first_close_hold:
|
| 1054 |
+
row.update(
|
| 1055 |
+
first_close_hold_queries=int(
|
| 1056 |
+
first_close_hold_query is not None
|
| 1057 |
+
),
|
| 1058 |
+
first_close_hold_query=first_close_hold_query,
|
| 1059 |
+
)
|
| 1060 |
+
if config.hold_after_first_release:
|
| 1061 |
+
row.update(
|
| 1062 |
+
release_query=release_query,
|
| 1063 |
+
release_request_step=release_request_step,
|
| 1064 |
+
release_feedback_complete_step=release_feedback_complete_step,
|
| 1065 |
+
hold_started_step=hold_started_step,
|
| 1066 |
+
terminal_hold_steps=terminal_hold_steps,
|
| 1067 |
+
held_command=None
|
| 1068 |
+
if terminal_command is None
|
| 1069 |
+
else terminal_command.tolist(),
|
| 1070 |
+
)
|
| 1071 |
+
if stop_enabled:
|
| 1072 |
+
row.update(
|
| 1073 |
+
stop_query=stop_query,
|
| 1074 |
+
stop_request_step=stop_request_step,
|
| 1075 |
+
stop_feedback_complete_step=stop_feedback_complete_step,
|
| 1076 |
+
honor_predicted_stop=config.honor_predicted_stop,
|
| 1077 |
+
hold_started_step=hold_started_step,
|
| 1078 |
+
terminal_hold_steps=terminal_hold_steps,
|
| 1079 |
+
held_command=None
|
| 1080 |
+
if terminal_command is None
|
| 1081 |
+
else terminal_command.tolist(),
|
| 1082 |
+
)
|
| 1083 |
+
if config.terminal_gripper_event:
|
| 1084 |
+
row["terminal_event_query"] = terminal_event_query
|
| 1085 |
+
if config.motion_replan_steps:
|
| 1086 |
+
row.update(
|
| 1087 |
+
completed_goals=executor.completed_goals,
|
| 1088 |
+
accepted_paths=executor.accepted_paths,
|
| 1089 |
+
replan_attempts=executor.replan_attempts,
|
| 1090 |
+
replan_failures=executor.replan_failures,
|
| 1091 |
+
total_motion_steps=executor.total_motion_steps,
|
| 1092 |
+
unfinished_path_steps=len(executor.path) - executor.index
|
| 1093 |
+
if executor.phase == "trajectory"
|
| 1094 |
+
else 0,
|
| 1095 |
+
)
|
| 1096 |
+
episodes.append(row)
|
| 1097 |
+
with (config.output_dir / "episodes.jsonl").open("a") as stream:
|
| 1098 |
+
stream.write(json.dumps(row) + "\n")
|
| 1099 |
+
predictions.flush()
|
| 1100 |
+
trace.flush()
|
| 1101 |
+
print("EPISODE_COMPLETE", json.dumps(row), flush=True)
|
| 1102 |
+
finally:
|
| 1103 |
+
env.close()
|
| 1104 |
+
from mani_skill.examples.motionplanning.base_motionplanner import motionplanner
|
| 1105 |
+
|
| 1106 |
+
result = {
|
| 1107 |
+
"config": config.model_dump(mode="json"),
|
| 1108 |
+
"provenance": provenance | source_provenance(reference),
|
| 1109 |
+
"policy": reference.policy.model_dump(mode="json"),
|
| 1110 |
+
"sensor_configs": sensor,
|
| 1111 |
+
"control_mode": control_mode,
|
| 1112 |
+
"control_hz": 20,
|
| 1113 |
+
"diagnostic": config.training_dataset is not None
|
| 1114 |
+
or config.first_target_xyz_alpha is not None
|
| 1115 |
+
or config.first_target_xy != "predicted"
|
| 1116 |
+
or config.every_target_xy != "predicted"
|
| 1117 |
+
or config.max_steps != 200
|
| 1118 |
+
or not config.reactive_gripper_gate
|
| 1119 |
+
or dense_endpoint
|
| 1120 |
+
or relative_endpoint,
|
| 1121 |
+
"pose_control_diagnostics": control.model_dump(mode="json"),
|
| 1122 |
+
"target_semantics": (
|
| 1123 |
+
"Compose all 30 decoded deltas assuming perfect tracking; only final gripper is retained. "
|
| 1124 |
+
"Intermediate motion and gripper events are discarded, then re-planned by the unchanged executor."
|
| 1125 |
+
if dense_endpoint
|
| 1126 |
+
else (
|
| 1127 |
+
"Last predicted relative target restored from the fixed chunk-start TCP; only final gripper retained."
|
| 1128 |
+
if relative_endpoint
|
| 1129 |
+
else "Latest query-zero world keypose"
|
| 1130 |
+
)
|
| 1131 |
+
),
|
| 1132 |
+
"episodes": len(episodes),
|
| 1133 |
+
"counts": {
|
| 1134 |
+
k: sum(r[k] for r in episodes)
|
| 1135 |
+
for k in (
|
| 1136 |
+
"success_once",
|
| 1137 |
+
"success_at_end",
|
| 1138 |
+
"audit_release_once",
|
| 1139 |
+
"audit_release_at_end",
|
| 1140 |
+
)
|
| 1141 |
+
},
|
| 1142 |
+
"policy_calls": sum(r["policy_calls"] for r in episodes),
|
| 1143 |
+
"planning_failures": sum(r["planning_failures"] for r in episodes),
|
| 1144 |
+
"started_epoch": started,
|
| 1145 |
+
"ended_epoch": time.time(),
|
| 1146 |
+
"planner_source_sha256": hashlib.sha256(
|
| 1147 |
+
Path(inspect.getfile(motionplanner)).read_bytes()
|
| 1148 |
+
).hexdigest(),
|
| 1149 |
+
"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."
|
| 1150 |
+
+ (
|
| 1151 |
+
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."
|
| 1152 |
+
if config.motion_replan_steps
|
| 1153 |
+
else ""
|
| 1154 |
+
)
|
| 1155 |
+
+ (
|
| 1156 |
+
" 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."
|
| 1157 |
+
if context_enabled and config.first_close_hold
|
| 1158 |
+
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."
|
| 1159 |
+
if context_enabled
|
| 1160 |
+
else ""
|
| 1161 |
+
)
|
| 1162 |
+
+ (
|
| 1163 |
+
" 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."
|
| 1164 |
+
if config.first_close_hold
|
| 1165 |
+
else ""
|
| 1166 |
+
)
|
| 1167 |
+
+ (
|
| 1168 |
+
" 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."
|
| 1169 |
+
if config.hold_after_first_release
|
| 1170 |
+
else ""
|
| 1171 |
+
)
|
| 1172 |
+
+ (
|
| 1173 |
+
" 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."
|
| 1174 |
+
if stop_enabled
|
| 1175 |
+
else ""
|
| 1176 |
+
)
|
| 1177 |
+
+ (
|
| 1178 |
+
" 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."
|
| 1179 |
+
if config.terminal_gripper_event
|
| 1180 |
+
else ""
|
| 1181 |
+
)
|
| 1182 |
+
+ (
|
| 1183 |
+
" 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."
|
| 1184 |
+
if first_xyz_oracle is not None
|
| 1185 |
+
else ""
|
| 1186 |
+
)
|
| 1187 |
+
+ (
|
| 1188 |
+
" Motion-time stable feedback can complete an unchanged gripper command at the final path step; changed commands still require post-path feedback."
|
| 1189 |
+
if config.carry_gripper_feedback
|
| 1190 |
+
else ""
|
| 1191 |
+
)
|
| 1192 |
+
+ (
|
| 1193 |
+
" Reactive gripper gate disabled: only the gripper scalar is replaced by the clipped model request; arm motion commands are unchanged."
|
| 1194 |
+
if not config.reactive_gripper_gate
|
| 1195 |
+
else ""
|
| 1196 |
+
)
|
| 1197 |
+
+ (
|
| 1198 |
+
" 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."
|
| 1199 |
+
if config.phase_gripper_events
|
| 1200 |
+
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."
|
| 1201 |
+
if reference.policy.keypose_phase_weight > 0
|
| 1202 |
+
else ""
|
| 1203 |
+
),
|
| 1204 |
+
}
|
| 1205 |
+
(config.output_dir / "result.json").write_text(json.dumps(result, indent=2) + "\n")
|
| 1206 |
+
print("PLANNED_COMPARISON_COMPLETE", json.dumps(result), flush=True)
|
| 1207 |
+
|
| 1208 |
+
|
| 1209 |
+
if __name__ == "__main__":
|
| 1210 |
+
run(CliApp.run(EvaluationConfig))
|
fair-comparison/p3x-liftslow-v1/code/lim/expert_stack_pyramid.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Revised StackPyramid expert: the native solution with five failure causes removed.
|
| 2 |
+
|
| 3 |
+
Same primitives, poses and planner settings as
|
| 4 |
+
mani_skill.examples.motionplanning.panda.solutions.stack_pyramid, except:
|
| 5 |
+
|
| 6 |
+
1. Push condition. The native expert pushes A only when A is more than 7 cm
|
| 7 |
+
from B, but success needs A within 6.16 cm (xy) of B, so scenes starting
|
| 8 |
+
6.16-7 cm apart fail without a push. Here A is pushed when it is more than
|
| 9 |
+
PUSH_IF_M from B.
|
| 10 |
+
2. Push goal. The native expert drags A to 0.8 x B's world position, which is
|
| 11 |
+
0.2 |B| from B whatever the side A comes from (up to 4.5 cm, and A ends
|
| 12 |
+
0.3-0.5 cm behind the fingers), so A sometimes stops beyond 6.16 cm. Here
|
| 13 |
+
the TCP drags A to PUSH_GAP_M from B on A's own side.
|
| 14 |
+
3. Press depth. The native expert presses on A towards a TCP at A's centre
|
| 15 |
+
height, about 3 cm below where the closed fingers rest on A's top; the
|
| 16 |
+
press loads A onto the table, the arm lags behind its push path (joint
|
| 17 |
+
paths) or stops short of it (keypose rule), and A ends 1.5-2.5 cm short of
|
| 18 |
+
the goal. Here the descent onto A and the push aim the TCP at PRESS_Z_M,
|
| 19 |
+
about 1 cm below the resting height.
|
| 20 |
+
4. Lift-off. The native expert leaves the push by moving straight towards
|
| 21 |
+
the pose above C, from fingers pressed on A's top; executed at the keypose
|
| 22 |
+
rule's speed this drags A off B. Here the TCP first rises straight up from
|
| 23 |
+
where it stopped to LIFT_Z_M.
|
| 24 |
+
5. Grasp orientation for C. The native expert takes the face pair closest to
|
| 25 |
+
the TCP's current closing axis and only rotates when the planner cannot
|
| 26 |
+
reach it, so the open fingers can land on A or B next to C. Here the face
|
| 27 |
+
pair whose finger footprints keep the larger clearance from A and B comes
|
| 28 |
+
first; the native order of +-angles for reachability is kept.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
import numpy as np
|
| 32 |
+
import sapien
|
| 33 |
+
from mani_skill.examples.motionplanning.base_motionplanner.utils import compute_grasp_info_by_obb, get_actor_obb
|
| 34 |
+
from mani_skill.examples.motionplanning.panda.motionplanner import PandaArmMotionPlanningSolver
|
| 35 |
+
from transforms3d.euler import euler2quat
|
| 36 |
+
|
| 37 |
+
PUSH_IF_M = 0.055
|
| 38 |
+
PRESS_Z_M = 0.04
|
| 39 |
+
PUSH_GAP_M = 0.045
|
| 40 |
+
LIFT_Z_M = 0.10
|
| 41 |
+
FINGER_INNER_M, FINGER_OUTER_M, FINGER_HALF_WIDTH_M = 0.04, 0.052, 0.01
|
| 42 |
+
"""Open-finger footprint along the closing axis from the TCP, and half its width across."""
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def square_distance(point, centre, yaw, half=0.02):
|
| 46 |
+
"""Signed xy distance from a point to a cube's square footprint (negative inside)."""
|
| 47 |
+
c, s = np.cos(-yaw), np.sin(-yaw)
|
| 48 |
+
d = np.array([[c, -s], [s, c]]) @ (np.asarray(point) - np.asarray(centre))
|
| 49 |
+
q = np.abs(d) - half
|
| 50 |
+
return float(np.linalg.norm(np.maximum(q, 0)) + min(max(q[0], q[1]), 0))
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def clearance(centre, closing, neighbours):
|
| 54 |
+
"""Smallest distance between the two open-finger footprints around `centre` and the neighbour cubes."""
|
| 55 |
+
closing = np.asarray(closing[:2]) / np.linalg.norm(closing[:2])
|
| 56 |
+
across = np.array([-closing[1], closing[0]])
|
| 57 |
+
points = [centre + sign * along * closing + width * across
|
| 58 |
+
for sign in (1, -1)
|
| 59 |
+
for along in np.linspace(FINGER_INNER_M, FINGER_OUTER_M, 4)
|
| 60 |
+
for width in np.linspace(-FINGER_HALF_WIDTH_M, FINGER_HALF_WIDTH_M, 5)]
|
| 61 |
+
return min(square_distance(p, c, yaw) for p in points for c, yaw in neighbours)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def yaw_of(actor):
|
| 65 |
+
w, x, y, z = actor.pose.q[0].cpu().numpy()
|
| 66 |
+
return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def solve(env, seed=None, debug=False, vis=False):
|
| 70 |
+
env.reset(seed=seed)
|
| 71 |
+
assert env.unwrapped.control_mode in ["pd_joint_pos", "pd_joint_pos_vel"], env.unwrapped.control_mode
|
| 72 |
+
planner = PandaArmMotionPlanningSolver(
|
| 73 |
+
env, debug=debug, vis=vis, base_pose=env.unwrapped.agent.robot.pose,
|
| 74 |
+
visualize_target_grasp_pose=vis, print_env_info=False,
|
| 75 |
+
)
|
| 76 |
+
FINGER_LENGTH = 0.025
|
| 77 |
+
env = env.unwrapped
|
| 78 |
+
approaching = np.array([0, 0, -1])
|
| 79 |
+
a, b = env.cubeA.pose.sp.p, env.cubeB.pose.sp.p
|
| 80 |
+
if np.linalg.norm((a - b)[:2]) > PUSH_IF_M:
|
| 81 |
+
target_closing = env.agent.tcp.pose.to_transformation_matrix()[0, :3, 1].cpu().numpy()
|
| 82 |
+
closing = compute_grasp_info_by_obb(get_actor_obb(env.cubeA), approaching=approaching,
|
| 83 |
+
target_closing=target_closing, depth=FINGER_LENGTH)["closing"]
|
| 84 |
+
planner.close_gripper()
|
| 85 |
+
grasp_pose = env.agent.build_grasp_pose(approaching, closing, np.r_[a[:2], PRESS_Z_M])
|
| 86 |
+
planner.move_to_pose_with_screw(grasp_pose * sapien.Pose([0, 0, -0.05]))
|
| 87 |
+
planner.move_to_pose_with_screw(grasp_pose)
|
| 88 |
+
planner.close_gripper()
|
| 89 |
+
side = (a - b)[:2] / np.linalg.norm((a - b)[:2])
|
| 90 |
+
goal = np.r_[b[:2] + PUSH_GAP_M * side, grasp_pose.p[2]]
|
| 91 |
+
planner.move_to_pose_with_screw(sapien.Pose(goal, grasp_pose.q))
|
| 92 |
+
tcp = env.agent.tcp.pose.sp.p
|
| 93 |
+
planner.move_to_pose_with_screw(sapien.Pose(np.r_[tcp[:2], LIFT_Z_M], grasp_pose.q))
|
| 94 |
+
pushed = True
|
| 95 |
+
else:
|
| 96 |
+
pushed = False
|
| 97 |
+
|
| 98 |
+
target_closing = env.agent.tcp.pose.to_transformation_matrix()[0, :3, 1].cpu().numpy()
|
| 99 |
+
info = compute_grasp_info_by_obb(get_actor_obb(env.cubeC), approaching=approaching,
|
| 100 |
+
target_closing=target_closing, depth=FINGER_LENGTH)
|
| 101 |
+
closing, center = info["closing"], info["center"]
|
| 102 |
+
base = env.agent.build_grasp_pose(approaching, closing, center)
|
| 103 |
+
neighbours = [(actor.pose.sp.p[:2], yaw_of(actor)) for actor in (env.cubeA, env.cubeB)]
|
| 104 |
+
order = sorted((0.0, np.pi / 2), key=lambda angle: -clearance(
|
| 105 |
+
center[:2], (base * sapien.Pose(q=euler2quat(0, 0, angle))).to_transformation_matrix()[:3, 1], neighbours))
|
| 106 |
+
grasp_pose = base
|
| 107 |
+
for angle in [x for first in order for x in (first, -first)]:
|
| 108 |
+
candidate = base * sapien.Pose(q=euler2quat(0, 0, angle))
|
| 109 |
+
if planner.move_to_pose_with_screw(candidate, dry_run=True) == -1:
|
| 110 |
+
continue
|
| 111 |
+
grasp_pose = candidate
|
| 112 |
+
break
|
| 113 |
+
else:
|
| 114 |
+
print("Fail to find a valid grasp pose")
|
| 115 |
+
planner.move_to_pose_with_screw(grasp_pose * sapien.Pose([0, 0, -0.05]))
|
| 116 |
+
if pushed:
|
| 117 |
+
planner.open_gripper()
|
| 118 |
+
planner.move_to_pose_with_screw(grasp_pose)
|
| 119 |
+
planner.close_gripper()
|
| 120 |
+
lift_pose = sapien.Pose([0, 0, 0.1]) * grasp_pose
|
| 121 |
+
planner.move_to_pose_with_screw(lift_pose)
|
| 122 |
+
goal_pose_A = env.cubeA.pose * sapien.Pose([0, 0, env.cube_half_size[2] * 2])
|
| 123 |
+
goal_pose_B = env.cubeB.pose * sapien.Pose([0, 0, env.cube_half_size[2] * 2])
|
| 124 |
+
goal_pose_p = (goal_pose_A.p + goal_pose_B.p) / 2
|
| 125 |
+
offset = (goal_pose_p - env.cubeC.pose.p).cpu().numpy()[0]
|
| 126 |
+
planner.move_to_pose_with_screw(sapien.Pose(lift_pose.p + offset, lift_pose.q))
|
| 127 |
+
res = planner.open_gripper()
|
| 128 |
+
planner.close()
|
| 129 |
+
return res
|
fair-comparison/p3x-liftslow-v1/code/lim/expert_stack_pyramid_pick.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""StackPyramid expert that picks A and places it next to B instead of dragging it.
|
| 2 |
+
|
| 3 |
+
The native expert (and lim.expert_stack_pyramid) drags A along the table by
|
| 4 |
+
friction under closed fingers pressed on its top. Executed by the keypose rule
|
| 5 |
+
the press is the vertical part of a capped straight step toward the push
|
| 6 |
+
endpoint, so on long pushes it is small and A slips from under the fingers
|
| 7 |
+
(lim.expert_stack_pyramid executed online: 265 of 1,294 attempts pushed short).
|
| 8 |
+
Here A is picked and placed, as in the StackCube expert:
|
| 9 |
+
|
| 10 |
+
- A is moved when it is more than MOVE_IF_M (xy) from B. Its placement is
|
| 11 |
+
PLACE_GAP_M from B's centre along the one of B's four face normals that
|
| 12 |
+
points most towards A among those leaving at least C_CLEARANCE_M to C; A is
|
| 13 |
+
turned about the vertical so its faces line up with B's.
|
| 14 |
+
- A's grasp and placement are chosen together, lexicographically: open
|
| 15 |
+
fingers landing at least FINGER_CLEARANCE_M from B and C; closing axis,
|
| 16 |
+
after the turn, perpendicular to the placement direction, so no finger is
|
| 17 |
+
lowered or opened in the gap between A and B; the spot at least
|
| 18 |
+
C_CLEARANCE_M from C; the direction pointing most towards A. The first
|
| 19 |
+
choice whose grasp is reachable (native +-angle order) is taken.
|
| 20 |
+
- C is grasped on the face pair whose open-finger footprints keep the larger
|
| 21 |
+
clearance from A and B first; for reachability the native order of
|
| 22 |
+
+-angles is kept.
|
| 23 |
+
- After releasing A the TCP rises straight up to LIFT_Z_M.
|
| 24 |
+
C is then grasped, lifted and placed over the midpoint of A's and B's tops
|
| 25 |
+
exactly as in the native expert.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
import sapien
|
| 30 |
+
from mani_skill.examples.motionplanning.base_motionplanner.utils import compute_grasp_info_by_obb, get_actor_obb
|
| 31 |
+
from mani_skill.examples.motionplanning.panda.motionplanner import PandaArmMotionPlanningSolver
|
| 32 |
+
from transforms3d.euler import euler2quat
|
| 33 |
+
|
| 34 |
+
from lim.expert_stack_pyramid import clearance, yaw_of
|
| 35 |
+
|
| 36 |
+
MOVE_IF_M = 0.055
|
| 37 |
+
PLACE_GAP_M = 0.05
|
| 38 |
+
C_CLEARANCE_M = 0.06
|
| 39 |
+
FINGER_CLEARANCE_M = 0.01
|
| 40 |
+
LIFT_Z_M = 0.10
|
| 41 |
+
FINGER_LENGTH = 0.025
|
| 42 |
+
APPROACHING = np.array([0, 0, -1])
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def wrap_quarter(angle):
|
| 46 |
+
"""Angle wrapped to [-pi/4, pi/4) (cube symmetry about the vertical)."""
|
| 47 |
+
return (angle + np.pi / 4) % (np.pi / 2) - np.pi / 4
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def grasp_pose_for(env, planner, actor, others):
|
| 51 |
+
"""Top grasp of `actor`, face pair ranked by finger clearance from `others`, first reachable angle."""
|
| 52 |
+
target_closing = env.agent.tcp.pose.to_transformation_matrix()[0, :3, 1].cpu().numpy()
|
| 53 |
+
info = compute_grasp_info_by_obb(get_actor_obb(actor), approaching=APPROACHING,
|
| 54 |
+
target_closing=target_closing, depth=FINGER_LENGTH)
|
| 55 |
+
base = env.agent.build_grasp_pose(APPROACHING, info["closing"], info["center"])
|
| 56 |
+
neighbours = [(o.pose.sp.p[:2], yaw_of(o)) for o in others]
|
| 57 |
+
order = sorted((0.0, np.pi / 2), key=lambda angle: -clearance(
|
| 58 |
+
info["center"][:2], (base * sapien.Pose(q=euler2quat(0, 0, angle))).to_transformation_matrix()[:3, 1], neighbours))
|
| 59 |
+
for angle in [x for first in order for x in (first, -first)]:
|
| 60 |
+
candidate = base * sapien.Pose(q=euler2quat(0, 0, angle))
|
| 61 |
+
if planner.move_to_pose_with_screw(candidate, dry_run=True) != -1:
|
| 62 |
+
return candidate
|
| 63 |
+
print("Fail to find a valid grasp pose")
|
| 64 |
+
return base
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def pick_and_place_a(env, planner):
|
| 68 |
+
"""Grasp pose of A, A's placement spot next to B, and the turn about the vertical that aligns A with B."""
|
| 69 |
+
a, b, c = env.cubeA.pose.sp.p, env.cubeB.pose.sp.p, env.cubeC.pose.sp.p
|
| 70 |
+
b_yaw = yaw_of(env.cubeB)
|
| 71 |
+
turn = wrap_quarter(b_yaw - yaw_of(env.cubeA))
|
| 72 |
+
target_closing = env.agent.tcp.pose.to_transformation_matrix()[0, :3, 1].cpu().numpy()
|
| 73 |
+
info = compute_grasp_info_by_obb(get_actor_obb(env.cubeA), approaching=APPROACHING,
|
| 74 |
+
target_closing=target_closing, depth=FINGER_LENGTH)
|
| 75 |
+
base = env.agent.build_grasp_pose(APPROACHING, info["closing"], info["center"])
|
| 76 |
+
neighbours = [(o.pose.sp.p[:2], yaw_of(o)) for o in (env.cubeB, env.cubeC)]
|
| 77 |
+
side = (a - b)[:2] / np.linalg.norm((a - b)[:2])
|
| 78 |
+
rotate = np.array([[np.cos(turn), -np.sin(turn)], [np.sin(turn), np.cos(turn)]])
|
| 79 |
+
options = []
|
| 80 |
+
for angle in (0.0, np.pi / 2):
|
| 81 |
+
closing = (base * sapien.Pose(q=euler2quat(0, 0, angle))).to_transformation_matrix()[:3, 1]
|
| 82 |
+
clear = clearance(info["center"][:2], closing, neighbours) >= FINGER_CLEARANCE_M
|
| 83 |
+
turned = rotate @ closing[:2]
|
| 84 |
+
for k in range(4):
|
| 85 |
+
normal = np.array([np.cos(b_yaw + k * np.pi / 2), np.sin(b_yaw + k * np.pi / 2)])
|
| 86 |
+
spot = b[:2] + PLACE_GAP_M * normal
|
| 87 |
+
key = (clear, abs(turned @ normal) < 0.5 * np.linalg.norm(turned),
|
| 88 |
+
np.linalg.norm(spot - c[:2]) >= C_CLEARANCE_M, float(normal @ side))
|
| 89 |
+
options.append((key, angle, spot))
|
| 90 |
+
options.sort(key=lambda o: o[0], reverse=True)
|
| 91 |
+
for _, angle, spot in options:
|
| 92 |
+
for signed in (angle, -angle):
|
| 93 |
+
candidate = base * sapien.Pose(q=euler2quat(0, 0, signed))
|
| 94 |
+
if planner.move_to_pose_with_screw(candidate, dry_run=True) != -1:
|
| 95 |
+
return candidate, spot, turn
|
| 96 |
+
print("Fail to find a valid grasp pose")
|
| 97 |
+
return base, options[0][2], turn
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def solve(env, seed=None, debug=False, vis=False):
|
| 101 |
+
env.reset(seed=seed)
|
| 102 |
+
assert env.unwrapped.control_mode in ["pd_joint_pos", "pd_joint_pos_vel"], env.unwrapped.control_mode
|
| 103 |
+
planner = PandaArmMotionPlanningSolver(
|
| 104 |
+
env, debug=debug, vis=vis, base_pose=env.unwrapped.agent.robot.pose,
|
| 105 |
+
visualize_target_grasp_pose=vis, print_env_info=False,
|
| 106 |
+
)
|
| 107 |
+
env = env.unwrapped
|
| 108 |
+
a, b = env.cubeA.pose.sp.p, env.cubeB.pose.sp.p
|
| 109 |
+
if np.linalg.norm((a - b)[:2]) > MOVE_IF_M:
|
| 110 |
+
grasp, spot, angle = pick_and_place_a(env, planner)
|
| 111 |
+
planner.move_to_pose_with_screw(grasp * sapien.Pose([0, 0, -0.05]))
|
| 112 |
+
planner.move_to_pose_with_screw(grasp)
|
| 113 |
+
planner.close_gripper()
|
| 114 |
+
planner.move_to_pose_with_screw(sapien.Pose(np.r_[grasp.p[:2], LIFT_Z_M], grasp.q))
|
| 115 |
+
q = (sapien.Pose(q=euler2quat(0, 0, angle)) * sapien.Pose(q=grasp.q)).q
|
| 116 |
+
planner.move_to_pose_with_screw(sapien.Pose(np.r_[spot, LIFT_Z_M], q))
|
| 117 |
+
planner.move_to_pose_with_screw(sapien.Pose(np.r_[spot, grasp.p[2] + 0.005], q))
|
| 118 |
+
planner.open_gripper()
|
| 119 |
+
planner.move_to_pose_with_screw(sapien.Pose(np.r_[spot, LIFT_Z_M], q))
|
| 120 |
+
grasp = grasp_pose_for(env, planner, env.cubeC, (env.cubeA, env.cubeB))
|
| 121 |
+
planner.move_to_pose_with_screw(grasp * sapien.Pose([0, 0, -0.05]))
|
| 122 |
+
planner.move_to_pose_with_screw(grasp)
|
| 123 |
+
planner.close_gripper()
|
| 124 |
+
lift_pose = sapien.Pose([0, 0, 0.1]) * grasp
|
| 125 |
+
planner.move_to_pose_with_screw(lift_pose)
|
| 126 |
+
goal_pose_A = env.cubeA.pose * sapien.Pose([0, 0, env.cube_half_size[2] * 2])
|
| 127 |
+
goal_pose_B = env.cubeB.pose * sapien.Pose([0, 0, env.cube_half_size[2] * 2])
|
| 128 |
+
goal_pose_p = (goal_pose_A.p + goal_pose_B.p) / 2
|
| 129 |
+
offset = (goal_pose_p - env.cubeC.pose.p).cpu().numpy()[0]
|
| 130 |
+
planner.move_to_pose_with_screw(sapien.Pose(lift_pose.p + offset, lift_pose.q))
|
| 131 |
+
res = planner.open_gripper()
|
| 132 |
+
planner.close()
|
| 133 |
+
return res
|
fair-comparison/p3x-liftslow-v1/code/lim/gripper_execution.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Inference-only gripper interventions around the unchanged native evaluator."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from collections import deque
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any, Literal
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import torch
|
| 10 |
+
from pydantic import BaseModel, ConfigDict, PositiveInt
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class GripperExecutionConfig(BaseModel, frozen=True):
|
| 14 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 15 |
+
aggregation: Literal["native", "latest"] = "native"
|
| 16 |
+
"""Native temporal mean, or the newest chunk's first gripper prediction only."""
|
| 17 |
+
binary: bool = False
|
| 18 |
+
"""Threshold the gripper at zero after aggregation; BCE already does this."""
|
| 19 |
+
trace: bool = False
|
| 20 |
+
"""Write every aligned chunk contribution and actual physical command."""
|
| 21 |
+
|
| 22 |
+
@property
|
| 23 |
+
def active(self):
|
| 24 |
+
return self.trace or self.binary or self.aggregation != "native"
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class GripperTraceConfig(BaseModel, frozen=True):
|
| 28 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 29 |
+
execution: GripperExecutionConfig
|
| 30 |
+
"""Execution intervention, separate from the checkpoint's training policy."""
|
| 31 |
+
output_dir: Path
|
| 32 |
+
"""Evaluation directory for gripper_steps.jsonl."""
|
| 33 |
+
num_envs: PositiveInt
|
| 34 |
+
"""Synchronous vector slots, each with exactly one model query per step."""
|
| 35 |
+
horizon: PositiveInt
|
| 36 |
+
"""Number of predicted actions per chunk."""
|
| 37 |
+
seed_start: int
|
| 38 |
+
"""Recorder's explicit initial scene seed; each batch advances num_envs."""
|
| 39 |
+
bce: bool
|
| 40 |
+
"""Whether the model output is 2*p(open)-1 rather than continuous L1 output."""
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class GripperTrace:
|
| 44 |
+
def __init__(self, config: GripperTraceConfig):
|
| 45 |
+
self.config = config
|
| 46 |
+
self.chunks = deque(maxlen=config.horizon)
|
| 47 |
+
self.step = 0
|
| 48 |
+
self.batch = 0
|
| 49 |
+
self.pending = None
|
| 50 |
+
self.command = None
|
| 51 |
+
self.rows = 0
|
| 52 |
+
self.disagreements = 0
|
| 53 |
+
self.stream = (
|
| 54 |
+
(config.output_dir / "gripper_steps.jsonl").open("x")
|
| 55 |
+
if config.execution.trace
|
| 56 |
+
else None
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
def reset(self):
|
| 60 |
+
self.chunks.clear()
|
| 61 |
+
self.step = 0
|
| 62 |
+
self.batch = 0
|
| 63 |
+
self.pending = None
|
| 64 |
+
self.command = None
|
| 65 |
+
|
| 66 |
+
def prediction(self, chunk):
|
| 67 |
+
if chunk.shape != (self.config.num_envs, self.config.horizon, 10):
|
| 68 |
+
raise ValueError("Expected one finite 10D pose chunk per vector slot")
|
| 69 |
+
if not torch.isfinite(chunk).all():
|
| 70 |
+
raise ValueError("Nonfinite policy chunk")
|
| 71 |
+
if self.chunks and self.chunks[-1][0] == self.step:
|
| 72 |
+
raise ValueError("More than one prediction for the same physical step")
|
| 73 |
+
self.chunks.append((self.step, chunk.detach().clone()))
|
| 74 |
+
|
| 75 |
+
def select(self, native_action):
|
| 76 |
+
if not self.chunks or self.chunks[-1][0] != self.step:
|
| 77 |
+
raise ValueError("Physical action must follow a fresh observation query")
|
| 78 |
+
native = np.asarray(native_action)
|
| 79 |
+
times = [time for time, _ in self.chunks]
|
| 80 |
+
aligned = torch.stack(
|
| 81 |
+
[chunk[:, self.step - time] for time, chunk in self.chunks], dim=1
|
| 82 |
+
)
|
| 83 |
+
# Exact vendor ordering: oldest to newest; older predictions get slightly
|
| 84 |
+
# larger weights. This recomputation audits; it NEVER replaces native pose.
|
| 85 |
+
weights = torch.exp(-0.01 * torch.arange(len(times), device=aligned.device))
|
| 86 |
+
weights = weights / weights.sum()
|
| 87 |
+
reconstructed = (aligned * weights[None, :, None]).sum(dim=1).cpu().numpy()
|
| 88 |
+
np.testing.assert_allclose(native, reconstructed, rtol=1e-5, atol=1e-6)
|
| 89 |
+
selected = np.array(native, copy=True)
|
| 90 |
+
latest = self.chunks[-1][1][:, 0, -1].cpu().numpy()
|
| 91 |
+
if self.config.execution.aggregation == "latest":
|
| 92 |
+
selected[:, -1] = latest
|
| 93 |
+
self.pending = {
|
| 94 |
+
"chunk_created_step0": times,
|
| 95 |
+
"chunk_action_index": [self.step - time for time in times],
|
| 96 |
+
"weights": weights.cpu().tolist(),
|
| 97 |
+
"aligned_gripper": aligned[..., -1].cpu().numpy(),
|
| 98 |
+
"native": native.copy(),
|
| 99 |
+
"selected": selected.copy(),
|
| 100 |
+
"latest": latest.copy(),
|
| 101 |
+
}
|
| 102 |
+
return selected
|
| 103 |
+
|
| 104 |
+
def physical_command(self, action):
|
| 105 |
+
if self.pending is None or self.command is not None:
|
| 106 |
+
raise ValueError("Unexpected physical command ordering")
|
| 107 |
+
self.command = np.array(action, copy=True)
|
| 108 |
+
|
| 109 |
+
def completed(self, terminated, truncated):
|
| 110 |
+
pending, command = self.pending, self.command
|
| 111 |
+
if pending is None or command is None:
|
| 112 |
+
raise ValueError("Missing prediction or physical command record")
|
| 113 |
+
expected = pending["selected"][:, -1]
|
| 114 |
+
if self.config.bce or self.config.execution.binary:
|
| 115 |
+
expected = np.where(expected >= 0, 1.0, -1.0)
|
| 116 |
+
np.testing.assert_array_equal(command[:, -1], expected)
|
| 117 |
+
for slot in range(self.config.num_envs):
|
| 118 |
+
row = {
|
| 119 |
+
"seed": self.config.seed_start
|
| 120 |
+
+ self.batch * self.config.num_envs
|
| 121 |
+
+ slot,
|
| 122 |
+
"step0": self.step,
|
| 123 |
+
"post_action_step": self.step + 1,
|
| 124 |
+
"chunk_created_step0": pending["chunk_created_step0"],
|
| 125 |
+
"chunk_action_index": pending["chunk_action_index"],
|
| 126 |
+
"weights": pending["weights"],
|
| 127 |
+
"chunk_gripper_scores": pending["aligned_gripper"][slot].tolist(),
|
| 128 |
+
"latest_gripper_score": float(pending["latest"][slot]),
|
| 129 |
+
"native_gripper_score": float(pending["native"][slot, -1]),
|
| 130 |
+
"selected_gripper_score": float(pending["selected"][slot, -1]),
|
| 131 |
+
"native_action_6d": pending["native"][slot].tolist(),
|
| 132 |
+
"selected_action_6d": pending["selected"][slot].tolist(),
|
| 133 |
+
"controller_command": command[slot].tolist(),
|
| 134 |
+
}
|
| 135 |
+
if self.config.bce:
|
| 136 |
+
row["chunk_p_open"] = (
|
| 137 |
+
(pending["aligned_gripper"][slot] + 1) / 2
|
| 138 |
+
).tolist()
|
| 139 |
+
row["latest_p_open"] = (row["latest_gripper_score"] + 1) / 2
|
| 140 |
+
row["native_p_open"] = (row["native_gripper_score"] + 1) / 2
|
| 141 |
+
self.disagreements += int(
|
| 142 |
+
(row["latest_gripper_score"] >= 0) != (row["native_gripper_score"] >= 0)
|
| 143 |
+
)
|
| 144 |
+
if self.stream is not None:
|
| 145 |
+
self.stream.write(json.dumps(row, allow_nan=False) + "\n")
|
| 146 |
+
self.rows += 1
|
| 147 |
+
self.pending = self.command = None
|
| 148 |
+
if np.asarray(truncated).any():
|
| 149 |
+
if not np.asarray(truncated).all():
|
| 150 |
+
raise ValueError("Native ACT requires simultaneous vector truncation")
|
| 151 |
+
self.chunks.clear()
|
| 152 |
+
self.batch += 1
|
| 153 |
+
self.step = 0
|
| 154 |
+
if self.stream is not None:
|
| 155 |
+
self.stream.flush()
|
| 156 |
+
else:
|
| 157 |
+
if np.asarray(terminated).any():
|
| 158 |
+
raise ValueError("Native ACT requires ignore_terminations=True")
|
| 159 |
+
self.step += 1
|
| 160 |
+
|
| 161 |
+
def diagnostics(self):
|
| 162 |
+
return {
|
| 163 |
+
"recorded_commands": self.rows,
|
| 164 |
+
"latest_native_sign_disagreements": self.disagreements,
|
| 165 |
+
"aggregation": self.config.execution.aggregation,
|
| 166 |
+
"binary": self.config.bce or self.config.execution.binary,
|
| 167 |
+
"trace": "gripper_steps.jsonl" if self.stream is not None else None,
|
| 168 |
+
"weights": "exp(-0.01*rank), normalized; oldest prediction rank=0",
|
| 169 |
+
"scope": "controller input, before the controller's own clipping; "
|
| 170 |
+
"probabilities only for BCE; geometry is diagnostic video metadata only",
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
def close(self):
|
| 174 |
+
if self.stream is not None:
|
| 175 |
+
self.stream.close()
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class GripperBoundaryConfig(BaseModel, frozen=True):
|
| 179 |
+
model_config = ConfigDict(
|
| 180 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 181 |
+
)
|
| 182 |
+
wrapped: Any
|
| 183 |
+
"""Existing agent or environment; all unrelated behavior is delegated."""
|
| 184 |
+
trace: Any
|
| 185 |
+
"""Shared per-evaluation GripperTrace; never passed into the learned policy."""
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
class GripperAgent:
|
| 189 |
+
def __init__(self, config: GripperBoundaryConfig):
|
| 190 |
+
self.config = config
|
| 191 |
+
|
| 192 |
+
def __getattr__(self, name):
|
| 193 |
+
return getattr(self.config.wrapped, name)
|
| 194 |
+
|
| 195 |
+
def get_action(self, obs):
|
| 196 |
+
chunk = self.config.wrapped.get_action(obs)
|
| 197 |
+
self.config.trace.prediction(chunk)
|
| 198 |
+
return chunk
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
class GripperDecisionEnv:
|
| 202 |
+
def __init__(self, config: GripperBoundaryConfig):
|
| 203 |
+
self.config = config
|
| 204 |
+
|
| 205 |
+
def __getattr__(self, name):
|
| 206 |
+
return getattr(self.config.wrapped, name)
|
| 207 |
+
|
| 208 |
+
def reset(self, *args, **kwargs):
|
| 209 |
+
self.config.trace.reset()
|
| 210 |
+
return self.config.wrapped.reset(*args, **kwargs)
|
| 211 |
+
|
| 212 |
+
def step(self, action):
|
| 213 |
+
selected = self.config.trace.select(action)
|
| 214 |
+
result = self.config.wrapped.step(selected)
|
| 215 |
+
self.config.trace.completed(result[2], result[3])
|
| 216 |
+
return result
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
class GripperPhysicalEnv:
|
| 220 |
+
def __init__(self, config: GripperBoundaryConfig):
|
| 221 |
+
self.config = config
|
| 222 |
+
|
| 223 |
+
def __getattr__(self, name):
|
| 224 |
+
return getattr(self.config.wrapped, name)
|
| 225 |
+
|
| 226 |
+
def step(self, action):
|
| 227 |
+
self.config.trace.physical_command(action)
|
| 228 |
+
return self.config.wrapped.step(action)
|
fair-comparison/p3x-liftslow-v1/code/lim/gripper_feedback.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Measured gripper completion and a CPU SAPIEN feedback adapter."""
|
| 2 |
+
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
from pydantic import BaseModel, ConfigDict, PositiveFloat, PositiveInt
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class GripperCompletionConfig(BaseModel, frozen=True):
|
| 11 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 12 |
+
position_tolerance_m: PositiveFloat = 0.001
|
| 13 |
+
"""Maximum absolute position error of each finger for target completion."""
|
| 14 |
+
velocity_tolerance_m_s: PositiveFloat = 0.005
|
| 15 |
+
"""Maximum absolute velocity of either finger for stable completion."""
|
| 16 |
+
stable_steps: PositiveInt = 3
|
| 17 |
+
"""Consecutive post-action feedback samples required for the same condition."""
|
| 18 |
+
timeout_steps: PositiveInt = 40
|
| 19 |
+
"""Maximum actual gripper control steps; timeout is not completion."""
|
| 20 |
+
minimum_contact_force_n: PositiveFloat = 0.5
|
| 21 |
+
"""Per-finger force threshold for bilateral contact against one external body."""
|
| 22 |
+
detect_arrest: bool = False
|
| 23 |
+
"""Recognise a driven-but-frozen finger as arrested instead of waiting out the
|
| 24 |
+
timeout. The original contract only exits a BLOCKED CLOSING, because
|
| 25 |
+
closing_against_object requires position > target; a blocked opening has no
|
| 26 |
+
exit and its finite-difference velocity reads ~0 while the joint is still
|
| 27 |
+
driven. Default false preserves every previously scored run."""
|
| 28 |
+
arrest_encoder_tolerance_m: PositiveFloat = 0.0001
|
| 29 |
+
"""Maximum encoder displacement per step still counted as frozen."""
|
| 30 |
+
arrest_drive_velocity_m_s: PositiveFloat = 0.05
|
| 31 |
+
"""Minimum instantaneous joint velocity proving the drive is still pushing."""
|
| 32 |
+
arrest_steps: PositiveInt = 5
|
| 33 |
+
"""Consecutive frozen-but-driven samples required to declare an arrest."""
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class GripperMeasurement(BaseModel, frozen=True):
|
| 37 |
+
model_config = ConfigDict(
|
| 38 |
+
extra="forbid", use_attribute_docstrings=True, allow_inf_nan=False
|
| 39 |
+
)
|
| 40 |
+
positions_m: tuple[float, float]
|
| 41 |
+
"""Measured positions of the two finger joints."""
|
| 42 |
+
velocities_m_s: tuple[float, float]
|
| 43 |
+
"""Measured encoder displacement over the last physical control interval."""
|
| 44 |
+
targets_m: tuple[float, float]
|
| 45 |
+
"""Command mapped to physical joint coordinates and clipped to joint limits."""
|
| 46 |
+
bilateral_contact: bool
|
| 47 |
+
"""Both finger inner sides currently contact the same external body."""
|
| 48 |
+
contact_forces_n: tuple[float, float] = (0.0, 0.0)
|
| 49 |
+
"""Force components along the inner-finger normals for the accepted pair."""
|
| 50 |
+
joint_velocities_m_s: tuple[float, float] = (0.0, 0.0)
|
| 51 |
+
"""Instantaneous simulator joint velocities, logged separately for diagnosis."""
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class GripperCompletion:
|
| 55 |
+
def __init__(self, config: GripperCompletionConfig):
|
| 56 |
+
self.config = config
|
| 57 |
+
self.steps = 0
|
| 58 |
+
self.streak = 0
|
| 59 |
+
self.arrested_streak = 0
|
| 60 |
+
self.condition = None
|
| 61 |
+
self.status = "running"
|
| 62 |
+
|
| 63 |
+
def update(self, measured: GripperMeasurement):
|
| 64 |
+
if self.status != "running":
|
| 65 |
+
raise RuntimeError("Completion monitor already ended")
|
| 66 |
+
self.steps += 1
|
| 67 |
+
position = np.asarray(measured.positions_m)
|
| 68 |
+
target = np.asarray(measured.targets_m)
|
| 69 |
+
error = np.abs(position - target)
|
| 70 |
+
stationary = (
|
| 71 |
+
max(abs(v) for v in measured.velocities_m_s)
|
| 72 |
+
<= self.config.velocity_tolerance_m_s
|
| 73 |
+
)
|
| 74 |
+
at_target = bool(np.all(error <= self.config.position_tolerance_m))
|
| 75 |
+
# Contact can complete a closing command, never a blocked opening.
|
| 76 |
+
closing_against_object = bool(
|
| 77 |
+
np.all(position >= target - self.config.position_tolerance_m)
|
| 78 |
+
and np.any(position > target + self.config.position_tolerance_m)
|
| 79 |
+
)
|
| 80 |
+
condition = None
|
| 81 |
+
if stationary:
|
| 82 |
+
if at_target:
|
| 83 |
+
condition = "target_reached"
|
| 84 |
+
elif closing_against_object and measured.bilateral_contact:
|
| 85 |
+
condition = "contact_stable"
|
| 86 |
+
self.streak = (
|
| 87 |
+
self.streak + 1
|
| 88 |
+
if condition is not None and condition == self.condition
|
| 89 |
+
else int(condition is not None)
|
| 90 |
+
)
|
| 91 |
+
self.condition = condition
|
| 92 |
+
# Frozen encoder while the drive still pushes: the finger is held by
|
| 93 |
+
# something. Never reported as completion, since the command was not met.
|
| 94 |
+
frozen = (
|
| 95 |
+
max(abs(v) for v in measured.velocities_m_s)
|
| 96 |
+
<= self.config.arrest_encoder_tolerance_m
|
| 97 |
+
)
|
| 98 |
+
driven = (
|
| 99 |
+
max(abs(v) for v in measured.joint_velocities_m_s)
|
| 100 |
+
>= self.config.arrest_drive_velocity_m_s
|
| 101 |
+
)
|
| 102 |
+
arrested = bool(frozen and driven and not at_target)
|
| 103 |
+
self.arrested_streak = self.arrested_streak + 1 if arrested else 0
|
| 104 |
+
if self.streak >= self.config.stable_steps:
|
| 105 |
+
self.status = "complete"
|
| 106 |
+
elif (
|
| 107 |
+
self.config.detect_arrest
|
| 108 |
+
and self.arrested_streak >= self.config.arrest_steps
|
| 109 |
+
):
|
| 110 |
+
self.status = "arrested"
|
| 111 |
+
elif self.steps >= self.config.timeout_steps:
|
| 112 |
+
self.status = "timeout"
|
| 113 |
+
return {
|
| 114 |
+
**measured.model_dump(mode="json"),
|
| 115 |
+
"position_error_m": error.tolist(),
|
| 116 |
+
"stationary": stationary,
|
| 117 |
+
"condition": condition,
|
| 118 |
+
"stable_steps": self.streak,
|
| 119 |
+
"arrested": arrested,
|
| 120 |
+
"arrested_steps": self.arrested_streak,
|
| 121 |
+
"elapsed_steps": self.steps,
|
| 122 |
+
"status": self.status,
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class FeedbackReaderConfig(BaseModel, frozen=True):
|
| 127 |
+
model_config = ConfigDict(
|
| 128 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 129 |
+
)
|
| 130 |
+
env: Any
|
| 131 |
+
"""One CPU Panda physical environment exposing encoders and contact impulses."""
|
| 132 |
+
completion: GripperCompletionConfig = GripperCompletionConfig()
|
| 133 |
+
"""Contact-force threshold shared with the completion contract."""
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class PandaGripperFeedback:
|
| 137 |
+
def __init__(self, config: FeedbackReaderConfig):
|
| 138 |
+
self.config = config
|
| 139 |
+
base = config.env.unwrapped
|
| 140 |
+
if base.gpu_sim_enabled or base.num_envs != 1:
|
| 141 |
+
raise ValueError("Feedback adapter requires a single CPU environment")
|
| 142 |
+
self.robot = base.agent.robot
|
| 143 |
+
self.fingers = (base.agent.finger1_link, base.agent.finger2_link)
|
| 144 |
+
self.finger_entities = tuple(f._bodies[0].entity for f in self.fingers)
|
| 145 |
+
self.robot_entities = {
|
| 146 |
+
link._bodies[0].entity for link in self.robot.get_links()
|
| 147 |
+
}
|
| 148 |
+
self.controller = base.agent.controller.controllers["gripper"]
|
| 149 |
+
if (
|
| 150 |
+
self.controller.config.use_delta
|
| 151 |
+
or not self.controller.config.normalize_action
|
| 152 |
+
):
|
| 153 |
+
raise ValueError("Expected normalized absolute gripper commands")
|
| 154 |
+
self.joint_indices = [
|
| 155 |
+
self.robot.active_joints_map[name].active_index[0].item()
|
| 156 |
+
for name in base.agent.gripper_joint_names
|
| 157 |
+
]
|
| 158 |
+
self.limits = self.robot.get_qlimits()[0, self.joint_indices].cpu().numpy()
|
| 159 |
+
self.previous_positions = (
|
| 160 |
+
self.robot.get_qpos()[0, self.joint_indices].cpu().numpy().copy()
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
def read(self, command):
|
| 164 |
+
base = self.config.env.unwrapped
|
| 165 |
+
# Backend contact adapter: no cube identity, task success, or geometry is
|
| 166 |
+
# used. Contact against arbitrary external bodies is tactile-style input.
|
| 167 |
+
forces = defaultdict(lambda: np.zeros((2, 3)))
|
| 168 |
+
for contact in base.scene.get_contacts():
|
| 169 |
+
entities = [body.entity for body in contact.bodies]
|
| 170 |
+
for finger, entity in enumerate(self.finger_entities):
|
| 171 |
+
if entity not in entities:
|
| 172 |
+
continue
|
| 173 |
+
index = entities.index(entity)
|
| 174 |
+
other = entities[1 - index]
|
| 175 |
+
if other in self.robot_entities:
|
| 176 |
+
continue
|
| 177 |
+
impulse = np.sum([point.impulse for point in contact.points], axis=0)
|
| 178 |
+
forces[other][finger] += (
|
| 179 |
+
impulse * (1 if index == 0 else -1) / base.scene.px.timestep
|
| 180 |
+
)
|
| 181 |
+
directions = np.stack(
|
| 182 |
+
[
|
| 183 |
+
self.fingers[0].pose.to_transformation_matrix()[0, :3, 1].cpu().numpy(),
|
| 184 |
+
-self.fingers[1]
|
| 185 |
+
.pose.to_transformation_matrix()[0, :3, 1]
|
| 186 |
+
.cpu()
|
| 187 |
+
.numpy(),
|
| 188 |
+
]
|
| 189 |
+
)
|
| 190 |
+
bilateral = False
|
| 191 |
+
magnitudes = np.zeros(2)
|
| 192 |
+
for pair in forces.values():
|
| 193 |
+
normal_forces = (pair * directions).sum(axis=1)
|
| 194 |
+
if np.all(normal_forces >= self.config.completion.minimum_contact_force_n):
|
| 195 |
+
bilateral = True
|
| 196 |
+
magnitudes = normal_forces
|
| 197 |
+
break
|
| 198 |
+
lower, upper = self.controller.config.lower, self.controller.config.upper
|
| 199 |
+
requested = (float(np.clip(command, -1, 1)) + 1) / 2 * (upper - lower) + lower
|
| 200 |
+
targets = np.clip(np.full(2, requested), self.limits[:, 0], self.limits[:, 1])
|
| 201 |
+
positions = self.robot.get_qpos()[0, self.joint_indices].cpu().numpy().copy()
|
| 202 |
+
velocity = (positions - self.previous_positions) / base.control_timestep
|
| 203 |
+
self.previous_positions = positions
|
| 204 |
+
return GripperMeasurement(
|
| 205 |
+
positions_m=tuple(positions),
|
| 206 |
+
velocities_m_s=tuple(velocity),
|
| 207 |
+
joint_velocities_m_s=tuple(
|
| 208 |
+
self.robot.get_qvel()[0, self.joint_indices].cpu().tolist()
|
| 209 |
+
),
|
| 210 |
+
targets_m=tuple(targets),
|
| 211 |
+
bilateral_contact=bilateral,
|
| 212 |
+
contact_forces_n=tuple(magnitudes),
|
| 213 |
+
)
|
fair-comparison/p3x-liftslow-v1/code/lim/job.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run one declared GPU job with durable output and measured process lifetime."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import signal
|
| 6 |
+
import subprocess
|
| 7 |
+
import time
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
from pydantic import BaseModel, ConfigDict, Field, NonNegativeInt, PositiveInt
|
| 11 |
+
from pydantic_settings import CliApp
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class JobConfig(BaseModel, frozen=True):
|
| 15 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 16 |
+
command: list[str] = Field(min_length=1)
|
| 17 |
+
"""Exact executable and arguments; executed without a shell."""
|
| 18 |
+
cwd: Path
|
| 19 |
+
"""Working directory for the program and its generated outputs."""
|
| 20 |
+
output_dir: Path
|
| 21 |
+
"""New job ledger directory containing process.log and result.json."""
|
| 22 |
+
gpu: NonNegativeInt
|
| 23 |
+
"""Physical GPU index assigned to this job through CUDA_VISIBLE_DEVICES."""
|
| 24 |
+
timeout_s: PositiveInt = 7200
|
| 25 |
+
"""Maximum allocated job duration, including startup, loading and evaluation."""
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class JobCLIConfig(BaseModel, frozen=True):
|
| 29 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 30 |
+
spec: Path
|
| 31 |
+
"""JSON file containing the single validated JobConfig."""
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def run_job(config: JobConfig):
|
| 35 |
+
config.output_dir.mkdir(parents=True, exist_ok=True)
|
| 36 |
+
if (config.output_dir / "launch.json").exists():
|
| 37 |
+
raise ValueError("Job was already launched; use a new declared run directory")
|
| 38 |
+
env = os.environ.copy()
|
| 39 |
+
env.update(CUDA_VISIBLE_DEVICES=str(config.gpu), PYTHONUNBUFFERED="1")
|
| 40 |
+
started = time.monotonic()
|
| 41 |
+
epoch = time.time()
|
| 42 |
+
result = {"config": config.model_dump(mode="json"), "started_epoch": epoch}
|
| 43 |
+
(config.output_dir / "launch.json").write_text(json.dumps(result, indent=2))
|
| 44 |
+
process = None
|
| 45 |
+
|
| 46 |
+
def interrupt(signum, frame):
|
| 47 |
+
raise KeyboardInterrupt(f"Job runner received signal {signum}")
|
| 48 |
+
|
| 49 |
+
late = []
|
| 50 |
+
previous = signal.signal(signal.SIGTERM, interrupt)
|
| 51 |
+
try:
|
| 52 |
+
with (config.output_dir / "process.log").open("w") as log:
|
| 53 |
+
process = subprocess.Popen(
|
| 54 |
+
config.command,
|
| 55 |
+
cwd=config.cwd,
|
| 56 |
+
env=env,
|
| 57 |
+
stdin=subprocess.DEVNULL,
|
| 58 |
+
stdout=log,
|
| 59 |
+
stderr=subprocess.STDOUT,
|
| 60 |
+
start_new_session=True,
|
| 61 |
+
)
|
| 62 |
+
result["pid"] = process.pid
|
| 63 |
+
result["exit_code"] = process.wait(timeout=config.timeout_s)
|
| 64 |
+
result["status"] = "complete" if result["exit_code"] == 0 else "failed"
|
| 65 |
+
except subprocess.TimeoutExpired:
|
| 66 |
+
result.update(status="timeout", exit_code=None)
|
| 67 |
+
except KeyboardInterrupt:
|
| 68 |
+
result.update(status="interrupted", exit_code=None)
|
| 69 |
+
except (OSError, ValueError) as error:
|
| 70 |
+
result.update(
|
| 71 |
+
status="failed", exit_code=None, error=f"{type(error).__name__}: {error}"
|
| 72 |
+
)
|
| 73 |
+
finally:
|
| 74 |
+
# A repeated or late SIGTERM must not abort cleanup (child kill and
|
| 75 |
+
# result.json); it is recorded here and honoured once the ledger exists.
|
| 76 |
+
signal.signal(signal.SIGTERM, lambda signum, frame: late.append(signum))
|
| 77 |
+
if process is not None and process.poll() is None:
|
| 78 |
+
os.killpg(process.pid, signal.SIGTERM)
|
| 79 |
+
try:
|
| 80 |
+
process.wait(timeout=20)
|
| 81 |
+
except subprocess.TimeoutExpired:
|
| 82 |
+
os.killpg(process.pid, signal.SIGKILL)
|
| 83 |
+
process.wait()
|
| 84 |
+
result.update(
|
| 85 |
+
ended_epoch=time.time(), allocated_device_wall_s=time.monotonic() - started
|
| 86 |
+
)
|
| 87 |
+
result["timing_scope"] = (
|
| 88 |
+
"one assigned GPU job process lifetime, including CPU startup/data/evaluation; not GPU utilization integration"
|
| 89 |
+
)
|
| 90 |
+
(config.output_dir / "result.json").write_text(json.dumps(result, indent=2))
|
| 91 |
+
signal.signal(signal.SIGTERM, signal.SIG_DFL if previous is None else previous)
|
| 92 |
+
print("JOB_COMPLETE", json.dumps(result), flush=True)
|
| 93 |
+
if result["status"] != "complete":
|
| 94 |
+
raise SystemExit(1)
|
| 95 |
+
if late:
|
| 96 |
+
# The job itself finished; the stop request still ends the caller's queue.
|
| 97 |
+
raise KeyboardInterrupt(f"Job runner received signal {late[0]} during cleanup")
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
if __name__ == "__main__":
|
| 101 |
+
args = CliApp.run(JobCLIConfig)
|
| 102 |
+
run_job(JobConfig.model_validate_json(args.spec.read_text()))
|
fair-comparison/p3x-liftslow-v1/code/lim/keypose_context.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Explicit completed-goal context for both native ACT state projections.
|
| 2 |
+
|
| 3 |
+
Training supplies the previous primitive's recorded target. Deployment must
|
| 4 |
+
supply only a model target whose path and gripper execution have completed.
|
| 5 |
+
The wrapper never infers a phase, advances a state machine, or reads task state.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from typing import Literal
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
from pydantic import BaseModel, ConfigDict
|
| 12 |
+
from torch import nn
|
| 13 |
+
|
| 14 |
+
from lim.normalization import FittedNormalizationConfig
|
| 15 |
+
|
| 16 |
+
KeyposeContextMode = Literal["none", "zero", "previous_target"]
|
| 17 |
+
STATE_DIM = 25
|
| 18 |
+
CONTEXT_DIM = 11
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ContextProjectionConfig(BaseModel, frozen=True):
|
| 22 |
+
model_config = ConfigDict(
|
| 23 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 24 |
+
)
|
| 25 |
+
state_projection: nn.Linear
|
| 26 |
+
"""Existing state25 projection; preserve its parameters and bias verbatim."""
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class StateContextProjection(nn.Module):
|
| 30 |
+
"""Project concatenated state25/context11 through separate additive paths."""
|
| 31 |
+
|
| 32 |
+
def __init__(self, config: ContextProjectionConfig):
|
| 33 |
+
super().__init__()
|
| 34 |
+
self.config = config
|
| 35 |
+
self.state = config.state_projection
|
| 36 |
+
if self.state.in_features != STATE_DIM:
|
| 37 |
+
raise ValueError(
|
| 38 |
+
"Completed-goal context requires the audited state25 projection"
|
| 39 |
+
)
|
| 40 |
+
self.in_features = STATE_DIM + CONTEXT_DIM
|
| 41 |
+
self.out_features = self.state.out_features
|
| 42 |
+
self.context = nn.Linear(
|
| 43 |
+
CONTEXT_DIM,
|
| 44 |
+
self.state.out_features,
|
| 45 |
+
bias=False,
|
| 46 |
+
device=self.state.weight.device,
|
| 47 |
+
dtype=self.state.weight.dtype,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
def forward(self, combined):
|
| 51 |
+
if combined.shape[-1] != self.in_features:
|
| 52 |
+
raise ValueError("Expected concatenated state25 and completed-target11")
|
| 53 |
+
return self.state(combined[..., :STATE_DIM]) + self.context(
|
| 54 |
+
combined[..., STATE_DIM:]
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class KeyposeContextModelConfig(BaseModel, frozen=True):
|
| 59 |
+
model_config = ConfigDict(
|
| 60 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 61 |
+
)
|
| 62 |
+
model: nn.Module
|
| 63 |
+
"""Pinned DETRVAE before NormalizedModel wraps the state/action contract."""
|
| 64 |
+
mode: KeyposeContextMode
|
| 65 |
+
"""Zero ablation or previous_target; none must keep the original model unwrapped."""
|
| 66 |
+
statistics: FittedNormalizationConfig
|
| 67 |
+
"""Original checkpoint-owned affine action statistics for the context target10."""
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class KeyposeContextModel(nn.Module):
|
| 71 |
+
def __init__(self, config: KeyposeContextModelConfig):
|
| 72 |
+
super().__init__()
|
| 73 |
+
self.config = config
|
| 74 |
+
if config.mode == "none":
|
| 75 |
+
raise ValueError(
|
| 76 |
+
"Disabled completed-goal context must not wrap the native model"
|
| 77 |
+
)
|
| 78 |
+
if len(config.statistics.action.center) != 10:
|
| 79 |
+
raise ValueError(
|
| 80 |
+
"Completed-goal context requires world keypose10 statistics"
|
| 81 |
+
)
|
| 82 |
+
self.base = config.model
|
| 83 |
+
prior = self.base.input_proj_robot_state
|
| 84 |
+
posterior = self.base.encoder_state_proj
|
| 85 |
+
if (
|
| 86 |
+
not isinstance(prior, nn.Linear)
|
| 87 |
+
or not isinstance(posterior, nn.Linear)
|
| 88 |
+
or prior.in_features != STATE_DIM
|
| 89 |
+
or posterior.in_features != STATE_DIM
|
| 90 |
+
or prior.out_features != posterior.out_features
|
| 91 |
+
or prior.weight.device != posterior.weight.device
|
| 92 |
+
):
|
| 93 |
+
raise ValueError(
|
| 94 |
+
"Expected matching native prior/posterior state25 projections"
|
| 95 |
+
)
|
| 96 |
+
devices = [prior.weight.device.index] if prior.weight.is_cuda else []
|
| 97 |
+
# One fork for both draws gives distinct context projections while
|
| 98 |
+
# preserving all caller RNG streams (native weights, EMA and sampling).
|
| 99 |
+
with torch.random.fork_rng(devices=devices):
|
| 100 |
+
self.base.input_proj_robot_state = StateContextProjection(
|
| 101 |
+
ContextProjectionConfig(state_projection=prior)
|
| 102 |
+
)
|
| 103 |
+
self.base.encoder_state_proj = StateContextProjection(
|
| 104 |
+
ContextProjectionConfig(state_projection=posterior)
|
| 105 |
+
)
|
| 106 |
+
self.register_buffer(
|
| 107 |
+
"action_center",
|
| 108 |
+
torch.tensor(config.statistics.action.center),
|
| 109 |
+
persistent=False,
|
| 110 |
+
)
|
| 111 |
+
self.register_buffer(
|
| 112 |
+
"action_scale",
|
| 113 |
+
torch.tensor(config.statistics.action.scale),
|
| 114 |
+
persistent=False,
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
def encode_context(self, obs):
|
| 118 |
+
state = obs["state"]
|
| 119 |
+
if state.ndim != 2 or state.shape[-1] != STATE_DIM:
|
| 120 |
+
raise ValueError(
|
| 121 |
+
"Expected batch x state25 before appending completed-goal context"
|
| 122 |
+
)
|
| 123 |
+
if self.config.mode == "zero":
|
| 124 |
+
# Ablation carries no completed-goal signal, including the valid bit.
|
| 125 |
+
return state.new_zeros((state.shape[0], CONTEXT_DIM))
|
| 126 |
+
if "completed_target" not in obs:
|
| 127 |
+
raise ValueError(
|
| 128 |
+
"previous_target policy requires explicit completed_target observations"
|
| 129 |
+
)
|
| 130 |
+
context = torch.as_tensor(
|
| 131 |
+
obs["completed_target"], device=state.device, dtype=state.dtype
|
| 132 |
+
)
|
| 133 |
+
if context.shape != (state.shape[0], CONTEXT_DIM):
|
| 134 |
+
raise ValueError("Expected completed_target shape batch x 11")
|
| 135 |
+
validity = context[:, -1]
|
| 136 |
+
if not ((validity == 0) | (validity == 1)).all():
|
| 137 |
+
raise ValueError("Completed-target validity must be exactly zero or one")
|
| 138 |
+
valid = validity.bool()
|
| 139 |
+
if not torch.isfinite(context[valid, :10]).all():
|
| 140 |
+
raise ValueError(
|
| 141 |
+
"A valid completed target must contain finite world keypose10"
|
| 142 |
+
)
|
| 143 |
+
# Mask before and after normalization: invalid placeholders can never
|
| 144 |
+
# leak a centering offset, NaN, or previous episode's target.
|
| 145 |
+
target = context[:, :10].masked_fill(~valid[:, None], 0)
|
| 146 |
+
target = ((target - self.action_center) / self.action_scale).masked_fill(
|
| 147 |
+
~valid[:, None], 0
|
| 148 |
+
)
|
| 149 |
+
return torch.cat([target, validity[:, None]], dim=-1)
|
| 150 |
+
|
| 151 |
+
def forward(self, obs, actions=None):
|
| 152 |
+
context = self.encode_context(obs)
|
| 153 |
+
combined = torch.cat([obs["state"], context], dim=-1)
|
| 154 |
+
# The native forward sees the combined vector in both state projections;
|
| 155 |
+
# action targets and RGB pass through unchanged. No hooks/global state.
|
| 156 |
+
return self.base({**obs, "state": combined}, actions)
|
fair-comparison/p3x-liftslow-v1/code/lim/keypose_control.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Observed TCP feedback for world-frame position/6D-orientation keypose commands."""
|
| 2 |
+
|
| 3 |
+
from typing import Any
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from mani_skill.utils.geometry.rotation_conversions import (
|
| 7 |
+
axis_angle_to_matrix,
|
| 8 |
+
matrix_to_axis_angle,
|
| 9 |
+
matrix_to_euler_angles,
|
| 10 |
+
quaternion_to_matrix,
|
| 11 |
+
)
|
| 12 |
+
from pydantic import BaseModel, ConfigDict, PositiveFloat
|
| 13 |
+
|
| 14 |
+
from lim.action_encoding import ROTATION_SCALE, matrix_to_sixd, sixd_to_matrix
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class KeyposeControlConfig(BaseModel, frozen=True):
|
| 18 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 19 |
+
max_translation_m: PositiveFloat = 0.01
|
| 20 |
+
"""Maximum requested Cartesian displacement per 20 Hz control step."""
|
| 21 |
+
max_rotation_rad: PositiveFloat = 0.05
|
| 22 |
+
"""Maximum requested SO(3) angle per control step, before controller decoding."""
|
| 23 |
+
position_tolerance_m: PositiveFloat = 0.003
|
| 24 |
+
"""Measured TCP distance required before accepting the target gripper command."""
|
| 25 |
+
rotation_tolerance_rad: PositiveFloat = 0.05
|
| 26 |
+
"""Measured angular distance required before accepting the target gripper command."""
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def encode_keypose(pose, gripper):
|
| 30 |
+
"""Input xyz,wxyz; output world xyz, continuous6D rotation, continuous gripper."""
|
| 31 |
+
if pose.shape[-1] != 7 or not torch.isfinite(pose).all():
|
| 32 |
+
raise ValueError("Expected finite world xyz,wxyz poses")
|
| 33 |
+
q = pose[..., 3:]
|
| 34 |
+
if not torch.allclose(q.norm(dim=-1), torch.ones_like(q[..., 0]), atol=1e-4):
|
| 35 |
+
raise ValueError("Keypose quaternions must be unit length")
|
| 36 |
+
return torch.cat(
|
| 37 |
+
[pose[..., :3], matrix_to_sixd(quaternion_to_matrix(q)), gripper[..., None]], -1
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def keypose_error(current, target):
|
| 42 |
+
if current.shape[-1] != 7 or target.shape[-1] != 10:
|
| 43 |
+
raise ValueError("Expected observed TCP7 and target10")
|
| 44 |
+
if not torch.isfinite(current).all() or not torch.isfinite(target).all():
|
| 45 |
+
raise ValueError("Nonfinite observed TCP or keypose target")
|
| 46 |
+
delta = target[..., :3] - current[..., :3]
|
| 47 |
+
rotation = sixd_to_matrix(target[..., 3:9]) @ quaternion_to_matrix(
|
| 48 |
+
current[..., 3:]
|
| 49 |
+
).transpose(-1, -2)
|
| 50 |
+
vector = matrix_to_axis_angle(rotation)
|
| 51 |
+
return delta, vector
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def keypose_command(current, target, previous_gripper, config: KeyposeControlConfig):
|
| 55 |
+
"""Pure observed-state controller; audited Panda root axes coincide with world."""
|
| 56 |
+
delta, rotation = keypose_error(current, target)
|
| 57 |
+
position_error = delta.norm(dim=-1)
|
| 58 |
+
rotation_error = rotation.norm(dim=-1)
|
| 59 |
+
reached = (position_error <= config.position_tolerance_m) & (
|
| 60 |
+
rotation_error <= config.rotation_tolerance_rad
|
| 61 |
+
)
|
| 62 |
+
translation = (
|
| 63 |
+
delta
|
| 64 |
+
* (config.max_translation_m / position_error.clamp_min(1e-8)).clamp(max=1)[
|
| 65 |
+
..., None
|
| 66 |
+
]
|
| 67 |
+
)
|
| 68 |
+
vector = (
|
| 69 |
+
rotation
|
| 70 |
+
* (config.max_rotation_rad / rotation_error.clamp_min(1e-8)).clamp(max=1)[
|
| 71 |
+
..., None
|
| 72 |
+
]
|
| 73 |
+
)
|
| 74 |
+
# Euler exists ONLY at the installed low-level controller boundary. Targets
|
| 75 |
+
# and SO(3) error/interpolation never learn or interpolate Euler coordinates.
|
| 76 |
+
angles = (
|
| 77 |
+
matrix_to_euler_angles(axis_angle_to_matrix(vector), "XYZ") / ROTATION_SCALE
|
| 78 |
+
)
|
| 79 |
+
angles = angles / angles.norm(dim=-1, keepdim=True).clamp(min=1)
|
| 80 |
+
gripper = torch.where(reached, target[..., -1].clamp(-1, 1), previous_gripper)
|
| 81 |
+
command = torch.cat(
|
| 82 |
+
[(translation / 0.1).clamp(-1, 1), angles, gripper[..., None]], -1
|
| 83 |
+
)
|
| 84 |
+
return command, reached, position_error, rotation_error
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class KeyposeEnvConfig(BaseModel, frozen=True):
|
| 88 |
+
model_config = ConfigDict(
|
| 89 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 90 |
+
)
|
| 91 |
+
env: Any
|
| 92 |
+
"""Physical vector environment exposing full state25 observations."""
|
| 93 |
+
control: KeyposeControlConfig = KeyposeControlConfig()
|
| 94 |
+
"""Pure keypose tracking and gripper synchronization settings."""
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class KeyposeEnv:
|
| 98 |
+
def __init__(self, config: KeyposeEnvConfig):
|
| 99 |
+
import gymnasium as gym
|
| 100 |
+
import numpy as np
|
| 101 |
+
|
| 102 |
+
self.config = config
|
| 103 |
+
self.current = None
|
| 104 |
+
self.gripper = None
|
| 105 |
+
self.action_space = gym.spaces.Box(
|
| 106 |
+
-np.inf, np.inf, (config.env.num_envs, 10), dtype=np.float32
|
| 107 |
+
)
|
| 108 |
+
self.single_action_space = gym.spaces.Box(
|
| 109 |
+
-np.inf, np.inf, (10,), dtype=np.float32
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
def __getattr__(self, name):
|
| 113 |
+
return getattr(self.config.env, name)
|
| 114 |
+
|
| 115 |
+
def remember(self, obs, reset=None):
|
| 116 |
+
state = torch.as_tensor(obs["state"], dtype=torch.float32)
|
| 117 |
+
if state.shape[-1] != 25:
|
| 118 |
+
raise ValueError("Expected audited qpos9,qvel9,TCP7 state layout")
|
| 119 |
+
self.current = state[:, 18:25].clone()
|
| 120 |
+
# Panda PDJointPosMimicController maps [-1,1] to [-.01,.04] m.
|
| 121 |
+
measured = ((state[:, 7:9].mean(-1) + 0.01) / 0.05 * 2 - 1).clamp(-1, 1)
|
| 122 |
+
if reset is None:
|
| 123 |
+
self.gripper = measured
|
| 124 |
+
else:
|
| 125 |
+
self.gripper = torch.where(torch.as_tensor(reset), measured, self.gripper)
|
| 126 |
+
|
| 127 |
+
def reset(self, *args, **kwargs):
|
| 128 |
+
obs, info = self.config.env.reset(*args, **kwargs)
|
| 129 |
+
self.remember(obs)
|
| 130 |
+
return obs, info
|
| 131 |
+
|
| 132 |
+
def step(self, target):
|
| 133 |
+
command, _, _, _ = keypose_command(
|
| 134 |
+
self.current, torch.as_tensor(target), self.gripper, self.config.control
|
| 135 |
+
)
|
| 136 |
+
self.gripper = command[:, -1].clone()
|
| 137 |
+
result = self.config.env.step(command.numpy())
|
| 138 |
+
self.remember(result[0], result[2] | result[3])
|
| 139 |
+
return result
|
fair-comparison/p3x-liftslow-v1/code/lim/keypose_data.py
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Keypose annotations with explicit pre-action/next-observation index semantics.
|
| 2 |
+
|
| 3 |
+
Dense observations and actions remain the canonical trajectory. Annotations are
|
| 4 |
+
additional supervision, never extra policy observations.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from contextlib import ExitStack
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Literal
|
| 10 |
+
|
| 11 |
+
import h5py
|
| 12 |
+
import numpy as np
|
| 13 |
+
from pydantic import (
|
| 14 |
+
BaseModel,
|
| 15 |
+
ConfigDict,
|
| 16 |
+
Field,
|
| 17 |
+
NonNegativeInt,
|
| 18 |
+
PositiveInt,
|
| 19 |
+
field_validator,
|
| 20 |
+
)
|
| 21 |
+
from pydantic_settings import CliApp
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class KeyposeSegment(BaseModel, frozen=True):
|
| 25 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 26 |
+
name: str
|
| 27 |
+
"""Human-readable expert primitive name."""
|
| 28 |
+
kind: Literal["move", "close", "open"]
|
| 29 |
+
"""Executed motion or gripper primitive; dry-run planning has no segment."""
|
| 30 |
+
start: NonNegativeInt
|
| 31 |
+
"""Inclusive action index, referring to the observation before that action."""
|
| 32 |
+
end: PositiveInt
|
| 33 |
+
"""Exclusive action index, also the achieved endpoint observation index."""
|
| 34 |
+
target_pose: tuple[float, ...] = Field(min_length=7, max_length=7)
|
| 35 |
+
"""Commanded world TCP position and quaternion in xyz,wxyz order."""
|
| 36 |
+
gripper: float = Field(ge=-1, le=1)
|
| 37 |
+
"""Command during the segment, closed < 0 < open; closing and opening are
|
| 38 |
+
explicit events. Experts command -1/1, except LiftPegUpright's, which closes
|
| 39 |
+
to -0.6 (fully closing lets the peg slip)."""
|
| 40 |
+
|
| 41 |
+
@field_validator("gripper")
|
| 42 |
+
@classmethod
|
| 43 |
+
def check_gripper(cls, value):
|
| 44 |
+
if value == 0:
|
| 45 |
+
raise ValueError("A gripper command is either closed (< 0) or open (> 0)")
|
| 46 |
+
return value
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class AnnotationConfig(BaseModel, frozen=True):
|
| 50 |
+
model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid")
|
| 51 |
+
segments: tuple[KeyposeSegment, ...]
|
| 52 |
+
"""Contiguous expert primitives in source-action coordinates."""
|
| 53 |
+
source_steps: PositiveInt
|
| 54 |
+
"""Number of source actions, before any controller conversion."""
|
| 55 |
+
target_to_source: tuple[int, ...]
|
| 56 |
+
"""Source action index for every actually executed target action."""
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def annotation_arrays(config: AnnotationConfig) -> dict[str, np.ndarray]:
|
| 60 |
+
segments = config.segments
|
| 61 |
+
if (
|
| 62 |
+
not segments
|
| 63 |
+
or segments[0].start != 0
|
| 64 |
+
or segments[-1].end != config.source_steps
|
| 65 |
+
):
|
| 66 |
+
raise ValueError("Segments must cover all source actions")
|
| 67 |
+
previous = 0
|
| 68 |
+
for segment in segments:
|
| 69 |
+
if segment.start != previous or segment.end <= segment.start:
|
| 70 |
+
raise ValueError("Segment gaps, overlap or empty primitive")
|
| 71 |
+
pose = np.asarray(segment.target_pose)
|
| 72 |
+
if not np.isfinite(pose).all() or not np.isclose(
|
| 73 |
+
np.linalg.norm(pose[3:]), 1, atol=1e-4
|
| 74 |
+
):
|
| 75 |
+
raise ValueError(
|
| 76 |
+
"Target poses must have finite values and unit quaternions"
|
| 77 |
+
)
|
| 78 |
+
previous = segment.end
|
| 79 |
+
mapping = np.asarray(config.target_to_source, dtype=np.int64)
|
| 80 |
+
if (
|
| 81 |
+
not len(mapping)
|
| 82 |
+
or mapping[0] != 0
|
| 83 |
+
or mapping[-1] != config.source_steps - 1
|
| 84 |
+
or not np.array_equal(np.unique(mapping), np.arange(config.source_steps))
|
| 85 |
+
or np.any(np.diff(mapping) < 0)
|
| 86 |
+
):
|
| 87 |
+
raise ValueError("Replay mapping must cover every source action monotonically")
|
| 88 |
+
source_ends = np.asarray([s.end for s in segments], dtype=np.int64)
|
| 89 |
+
ends = np.searchsorted(mapping, source_ends, side="left")
|
| 90 |
+
starts = np.r_[0, ends[:-1]]
|
| 91 |
+
ids = np.searchsorted(ends, np.arange(len(mapping)), side="right")
|
| 92 |
+
return {
|
| 93 |
+
"start_action": starts,
|
| 94 |
+
"end_action": ends,
|
| 95 |
+
"source_start_action": np.asarray([s.start for s in segments], dtype=np.int64),
|
| 96 |
+
"source_end_action": source_ends,
|
| 97 |
+
"target_pose_world": np.asarray(
|
| 98 |
+
[s.target_pose for s in segments], dtype=np.float32
|
| 99 |
+
),
|
| 100 |
+
"gripper_command": np.asarray([s.gripper for s in segments], dtype=np.float32),
|
| 101 |
+
"action_keyframe_index": ids,
|
| 102 |
+
"target_to_source_action": mapping,
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def write_annotations(group, config: AnnotationConfig):
|
| 107 |
+
arrays = annotation_arrays(config)
|
| 108 |
+
if len(group["actions"]) != len(arrays["action_keyframe_index"]):
|
| 109 |
+
raise ValueError("Replay trace and saved actions differ")
|
| 110 |
+
keyframes = group.create_group("keyframes")
|
| 111 |
+
keyframes.attrs.update(
|
| 112 |
+
schema_version=1,
|
| 113 |
+
pose_frame="world",
|
| 114 |
+
pose_encoding="xyz,wxyz",
|
| 115 |
+
interval="actions[start:end]; obs[end] is the achieved endpoint",
|
| 116 |
+
label_scope="supervision only; never policy input",
|
| 117 |
+
)
|
| 118 |
+
for name, data in arrays.items():
|
| 119 |
+
keyframes.create_dataset(name, data=data)
|
| 120 |
+
for name, values in {
|
| 121 |
+
"name": [s.name for s in config.segments],
|
| 122 |
+
"kind": [s.kind for s in config.segments],
|
| 123 |
+
}.items():
|
| 124 |
+
keyframes.create_dataset(name, data=values, dtype=h5py.string_dtype("utf-8"))
|
| 125 |
+
keyframes.create_dataset(
|
| 126 |
+
"achieved_pose_world", data=group["obs/extra/tcp_pose"][:][arrays["end_action"]]
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class AuditConfig(BaseModel, frozen=True):
|
| 131 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 132 |
+
dataset: Path
|
| 133 |
+
"""Annotated ManiSkill H5; neighboring JSON supplies episode metadata."""
|
| 134 |
+
output: Path
|
| 135 |
+
"""New audit JSON; no existing audit is overwritten."""
|
| 136 |
+
source_dataset: Path | None = None
|
| 137 |
+
"""Annotated joint-control source for cross-file pose replay identity checks."""
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def audit_dataset(config: AuditConfig):
|
| 141 |
+
import hashlib
|
| 142 |
+
import json
|
| 143 |
+
|
| 144 |
+
metadata = json.loads(config.dataset.with_suffix(".json").read_text())
|
| 145 |
+
rows = []
|
| 146 |
+
with ExitStack() as stack:
|
| 147 |
+
data = stack.enter_context(h5py.File(config.dataset, "r"))
|
| 148 |
+
source = None
|
| 149 |
+
source_episodes = {}
|
| 150 |
+
if config.source_dataset is not None:
|
| 151 |
+
source = stack.enter_context(h5py.File(config.source_dataset, "r"))
|
| 152 |
+
source_metadata = json.loads(
|
| 153 |
+
config.source_dataset.with_suffix(".json").read_text()
|
| 154 |
+
)
|
| 155 |
+
source_episodes = {e["episode_id"]: e for e in source_metadata["episodes"]}
|
| 156 |
+
if len(data) != len(metadata["episodes"]):
|
| 157 |
+
raise ValueError("Episode count differs from metadata")
|
| 158 |
+
for episode in metadata["episodes"]:
|
| 159 |
+
group = data[f"traj_{episode['episode_id']}"]
|
| 160 |
+
actions = group["actions"][:]
|
| 161 |
+
count = len(actions)
|
| 162 |
+
key = group["keyframes"]
|
| 163 |
+
starts, ends = key["start_action"][:], key["end_action"][:]
|
| 164 |
+
if (
|
| 165 |
+
len(starts) == 0
|
| 166 |
+
or starts[0] != 0
|
| 167 |
+
or ends[-1] != count
|
| 168 |
+
or np.any(ends <= starts)
|
| 169 |
+
or not np.array_equal(starts[1:], ends[:-1])
|
| 170 |
+
):
|
| 171 |
+
raise ValueError("Invalid segment boundaries")
|
| 172 |
+
if count != episode["elapsed_steps"] or not bool(group["success"][-1]):
|
| 173 |
+
raise ValueError("Incomplete or unsuccessful saved demonstration")
|
| 174 |
+
|
| 175 |
+
def check_observation(name, item, count=count):
|
| 176 |
+
if isinstance(item, h5py.Dataset):
|
| 177 |
+
if len(item) != count + 1:
|
| 178 |
+
raise ValueError(f"Dense observations dropped: {name}")
|
| 179 |
+
if not np.isfinite(item[:]).all():
|
| 180 |
+
raise ValueError(f"Nonfinite observations: {name}")
|
| 181 |
+
|
| 182 |
+
group["obs"].visititems(check_observation)
|
| 183 |
+
ids = key["action_keyframe_index"][:]
|
| 184 |
+
expected_ids = np.repeat(np.arange(len(ends)), ends - starts)
|
| 185 |
+
if not np.array_equal(ids, expected_ids):
|
| 186 |
+
raise ValueError("Pre-action target labels are misaligned")
|
| 187 |
+
for field in [
|
| 188 |
+
"name",
|
| 189 |
+
"kind",
|
| 190 |
+
"gripper_command",
|
| 191 |
+
"target_pose_world",
|
| 192 |
+
"achieved_pose_world",
|
| 193 |
+
]:
|
| 194 |
+
if len(key[field]) != len(ends):
|
| 195 |
+
raise ValueError(f"Wrong number of segment labels: {field}")
|
| 196 |
+
kinds = key["kind"].asstr()[:]
|
| 197 |
+
if not set(kinds).issubset({"move", "close", "open"}):
|
| 198 |
+
raise ValueError("Unknown segment kind")
|
| 199 |
+
commands = key["gripper_command"][:]
|
| 200 |
+
if np.any(commands[kinds == "close"] >= 0) or np.any(
|
| 201 |
+
commands[kinds == "open"] <= 0
|
| 202 |
+
):
|
| 203 |
+
raise ValueError("Gripper event type disagrees with its command")
|
| 204 |
+
if not np.array_equal(actions[:, -1], key["gripper_command"][:][ids]):
|
| 205 |
+
raise ValueError("Gripper event/action mismatch")
|
| 206 |
+
actual = group["obs/extra/tcp_pose"][:][ends]
|
| 207 |
+
if not np.array_equal(actual, key["achieved_pose_world"][:]):
|
| 208 |
+
raise ValueError("Endpoint observation is misaligned")
|
| 209 |
+
mapping = key["target_to_source_action"][:]
|
| 210 |
+
source_ends = key["source_end_action"][:]
|
| 211 |
+
source_starts = key["source_start_action"][:]
|
| 212 |
+
if not np.array_equal(source_starts, np.r_[0, source_ends[:-1]]) or np.any(
|
| 213 |
+
source_ends <= source_starts
|
| 214 |
+
):
|
| 215 |
+
raise ValueError("Source segment boundaries are inconsistent")
|
| 216 |
+
if not np.array_equal(np.unique(mapping), np.arange(source_ends[-1])):
|
| 217 |
+
raise ValueError("Replay omitted source actions")
|
| 218 |
+
if np.any(np.diff(mapping) < 0) or not np.array_equal(
|
| 219 |
+
np.searchsorted(mapping, source_ends), ends
|
| 220 |
+
):
|
| 221 |
+
raise ValueError("Replay boundary mapping is invalid")
|
| 222 |
+
target = key["target_pose_world"][:]
|
| 223 |
+
if not np.isfinite(actions).all() or not np.isfinite(target).all():
|
| 224 |
+
raise ValueError("Nonfinite actions or targets")
|
| 225 |
+
if not np.allclose(np.linalg.norm(target[:, 3:], axis=1), 1, atol=1e-4):
|
| 226 |
+
raise ValueError("Invalid quaternion target")
|
| 227 |
+
image_differences = {}
|
| 228 |
+
if source is not None:
|
| 229 |
+
source_id = episode["source_episode_id"]
|
| 230 |
+
source_group = source[f"traj_{source_id}"]
|
| 231 |
+
if not (
|
| 232 |
+
episode["episode_seed"]
|
| 233 |
+
== episode["source_episode_seed"]
|
| 234 |
+
== source_episodes[source_id]["episode_seed"]
|
| 235 |
+
):
|
| 236 |
+
raise ValueError("Source and target seed metadata disagree")
|
| 237 |
+
for path in ["obs/agent/qpos", "obs/agent/qvel", "obs/extra/tcp_pose"]:
|
| 238 |
+
np.testing.assert_allclose(
|
| 239 |
+
group[path][0], source_group[path][0], rtol=0, atol=1e-6
|
| 240 |
+
)
|
| 241 |
+
for camera in ["base_camera", "hand_camera"]:
|
| 242 |
+
path = f"obs/sensor_data/{camera}/rgb"
|
| 243 |
+
difference = np.abs(
|
| 244 |
+
group[path][0].astype(np.int16)
|
| 245 |
+
- source_group[path][0].astype(np.int16)
|
| 246 |
+
)
|
| 247 |
+
image_differences[camera] = {
|
| 248 |
+
"bitwise_equal": not bool(difference.any()),
|
| 249 |
+
"changed_channels": int(np.count_nonzero(difference)),
|
| 250 |
+
"mean_abs_0_255": float(difference.mean()),
|
| 251 |
+
"max_abs_0_255": int(difference.max()),
|
| 252 |
+
}
|
| 253 |
+
for parameter in ["cam2world_gl", "extrinsic_cv", "intrinsic_cv"]:
|
| 254 |
+
path = f"obs/sensor_param/{camera}/{parameter}"
|
| 255 |
+
np.testing.assert_allclose(
|
| 256 |
+
group[path][0], source_group[path][0], rtol=0, atol=1e-6
|
| 257 |
+
)
|
| 258 |
+
for category in ["actors", "articulations"]:
|
| 259 |
+
for entity in source_group[f"env_states/{category}"]:
|
| 260 |
+
path = f"env_states/{category}/{entity}"
|
| 261 |
+
np.testing.assert_array_equal(
|
| 262 |
+
group[path][0], source_group[path][0]
|
| 263 |
+
)
|
| 264 |
+
for field in ["name", "kind"]:
|
| 265 |
+
np.testing.assert_array_equal(
|
| 266 |
+
key[field].asstr()[:],
|
| 267 |
+
source_group[f"keyframes/{field}"].asstr()[:],
|
| 268 |
+
)
|
| 269 |
+
np.testing.assert_array_equal(
|
| 270 |
+
source_starts, source_group["keyframes/start_action"][:]
|
| 271 |
+
)
|
| 272 |
+
np.testing.assert_array_equal(
|
| 273 |
+
target, source_group["keyframes/target_pose_world"][:]
|
| 274 |
+
)
|
| 275 |
+
np.testing.assert_array_equal(
|
| 276 |
+
source_ends, source_group["keyframes/end_action"][:]
|
| 277 |
+
)
|
| 278 |
+
np.testing.assert_array_equal(
|
| 279 |
+
actions[:, -1], source_group["actions"][:, -1][mapping]
|
| 280 |
+
)
|
| 281 |
+
position_error = np.linalg.norm(actual[:, :3] - target[:, :3], axis=1)
|
| 282 |
+
quat_a = actual[:, 3:] / np.linalg.norm(
|
| 283 |
+
actual[:, 3:], axis=1, keepdims=True
|
| 284 |
+
)
|
| 285 |
+
quat_b = target[:, 3:] / np.linalg.norm(
|
| 286 |
+
target[:, 3:], axis=1, keepdims=True
|
| 287 |
+
)
|
| 288 |
+
rotation_error = 2 * np.arccos(
|
| 289 |
+
np.clip(np.abs((quat_a * quat_b).sum(1)), 0, 1)
|
| 290 |
+
)
|
| 291 |
+
rows.append(
|
| 292 |
+
{
|
| 293 |
+
"episode_id": episode["episode_id"],
|
| 294 |
+
"seed": episode["episode_seed"],
|
| 295 |
+
"actions": count,
|
| 296 |
+
"keyframes": len(ends),
|
| 297 |
+
"position_error_m": position_error.tolist(),
|
| 298 |
+
"rotation_error_deg": np.rad2deg(rotation_error).tolist(),
|
| 299 |
+
"segments": key["name"].asstr()[:].tolist(),
|
| 300 |
+
"initial_rgb_diagnostics": image_differences,
|
| 301 |
+
}
|
| 302 |
+
)
|
| 303 |
+
digest = hashlib.sha256()
|
| 304 |
+
with config.dataset.open("rb") as f:
|
| 305 |
+
for chunk in iter(lambda: f.read(8 * 1024 * 1024), b""):
|
| 306 |
+
digest.update(chunk)
|
| 307 |
+
result = {
|
| 308 |
+
"status": "passed",
|
| 309 |
+
"dataset": str(config.dataset),
|
| 310 |
+
"sha256": digest.hexdigest(),
|
| 311 |
+
"episodes": len(rows),
|
| 312 |
+
"dense_actions": sum(r["actions"] for r in rows),
|
| 313 |
+
"keyframes": sum(r["keyframes"] for r in rows),
|
| 314 |
+
"source_identity_checked": config.source_dataset is not None,
|
| 315 |
+
"rgb_bitwise_identity": all(
|
| 316 |
+
d["bitwise_equal"]
|
| 317 |
+
for row in rows
|
| 318 |
+
for d in row["initial_rgb_diagnostics"].values()
|
| 319 |
+
)
|
| 320 |
+
if config.source_dataset is not None
|
| 321 |
+
else None,
|
| 322 |
+
"rows": rows,
|
| 323 |
+
"scope": "record integrity and endpoint error; no learned policy or sparse execution result",
|
| 324 |
+
}
|
| 325 |
+
config.output.parent.mkdir(parents=True, exist_ok=True)
|
| 326 |
+
with config.output.open("x") as f:
|
| 327 |
+
f.write(json.dumps(result, indent=2) + "\n")
|
| 328 |
+
return result
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
if __name__ == "__main__":
|
| 332 |
+
result = audit_dataset(CliApp.run(AuditConfig))
|
| 333 |
+
print({k: v for k, v in result.items() if k != "rows"})
|
fair-comparison/p3x-liftslow-v1/code/lim/keypose_dense.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dense future supervision sharing the decoder; never a deployed control branch."""
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from types import SimpleNamespace
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from pydantic import BaseModel, ConfigDict, PositiveInt
|
| 10 |
+
from torch import nn
|
| 11 |
+
from torch.utils.data import Dataset
|
| 12 |
+
|
| 13 |
+
from lim.action_encoding import controller_to_sixd
|
| 14 |
+
from lim.normalization import (
|
| 15 |
+
FitNormalizationConfig,
|
| 16 |
+
NormalizationConfig,
|
| 17 |
+
fit_normalization,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class DenseAuxiliaryHeadConfig(BaseModel, frozen=True):
|
| 22 |
+
model_config = ConfigDict(
|
| 23 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 24 |
+
)
|
| 25 |
+
primary: nn.Module
|
| 26 |
+
"""Existing action/stop projections, preserving their parameters and output."""
|
| 27 |
+
hidden_size: PositiveInt
|
| 28 |
+
"""Native decoder feature width; the experiment retains 256."""
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class DenseAuxiliaryHead(nn.Module):
|
| 32 |
+
def __init__(self, config: DenseAuxiliaryHeadConfig):
|
| 33 |
+
super().__init__()
|
| 34 |
+
self.config = config
|
| 35 |
+
self.primary = config.primary
|
| 36 |
+
parameter = next(self.primary.parameters())
|
| 37 |
+
devices = [parameter.device.index] if parameter.is_cuda else []
|
| 38 |
+
with torch.random.fork_rng(devices=devices):
|
| 39 |
+
self.dense = nn.Linear(
|
| 40 |
+
config.hidden_size, 10, device=parameter.device, dtype=parameter.dtype
|
| 41 |
+
)
|
| 42 |
+
self.dense_actions = None
|
| 43 |
+
|
| 44 |
+
def forward(self, features):
|
| 45 |
+
if features.ndim != 3 or features.shape[-1] != self.config.hidden_size:
|
| 46 |
+
raise ValueError("Expected native batch x query x hidden decoder features")
|
| 47 |
+
output = self.primary(features)
|
| 48 |
+
self.dense_actions = self.dense(features)
|
| 49 |
+
return output
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def read_dense_actions(model):
|
| 53 |
+
heads = [part for part in model.modules() if isinstance(part, DenseAuxiliaryHead)]
|
| 54 |
+
if len(heads) != 1 or heads[0].dense_actions is None:
|
| 55 |
+
raise ValueError(
|
| 56 |
+
"Expected exactly one dense auxiliary head with a completed forward"
|
| 57 |
+
)
|
| 58 |
+
return heads[0].dense_actions
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def primary_state_sha256(model):
|
| 62 |
+
"""Recover the existing stop model's full initial state without the dense head."""
|
| 63 |
+
result = hashlib.sha256()
|
| 64 |
+
for name, value in model.state_dict().items():
|
| 65 |
+
if ".action_head.dense." in name:
|
| 66 |
+
continue
|
| 67 |
+
name = name.replace(".action_head.primary.", ".action_head.")
|
| 68 |
+
result.update(name.encode())
|
| 69 |
+
result.update(value.detach().cpu().contiguous().numpy().tobytes())
|
| 70 |
+
return result.hexdigest()
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class DenseAuxiliaryDatasetConfig(BaseModel, frozen=True):
|
| 74 |
+
model_config = ConfigDict(
|
| 75 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 76 |
+
)
|
| 77 |
+
dataset: Any
|
| 78 |
+
"""Unnormalized current-keypose dataset; its native dataset retains raw control7."""
|
| 79 |
+
source: Path
|
| 80 |
+
"""Same H5 used for primary keyposes; no extra demonstration or observation."""
|
| 81 |
+
normalization: NormalizationConfig
|
| 82 |
+
"""The original dense action-zscore algorithm, separately fitted from raw actions."""
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class DenseAuxiliaryDataset(Dataset):
|
| 86 |
+
def __init__(self, config: DenseAuxiliaryDatasetConfig):
|
| 87 |
+
self.config = config
|
| 88 |
+
self.dataset = config.dataset
|
| 89 |
+
native = self.dataset.dataset
|
| 90 |
+
if (
|
| 91 |
+
self.dataset.slices != native.slices
|
| 92 |
+
or self.dataset.num_queries != 30
|
| 93 |
+
or not native.delta_control
|
| 94 |
+
or native.norm_stats is not None
|
| 95 |
+
or config.normalization.method != "action_zscore"
|
| 96 |
+
):
|
| 97 |
+
raise ValueError(
|
| 98 |
+
"Dense auxiliary requires all original Q30 raw delta observations"
|
| 99 |
+
)
|
| 100 |
+
self.dense = [
|
| 101 |
+
controller_to_sixd(action) for action in native.trajectories["actions"]
|
| 102 |
+
]
|
| 103 |
+
population = SimpleNamespace(
|
| 104 |
+
delta_control=True,
|
| 105 |
+
norm_stats=None,
|
| 106 |
+
trajectories={**native.trajectories, "actions": self.dense},
|
| 107 |
+
)
|
| 108 |
+
self.dense_statistics = fit_normalization(
|
| 109 |
+
FitNormalizationConfig(
|
| 110 |
+
dataset=population,
|
| 111 |
+
normalization=config.normalization,
|
| 112 |
+
action_encoding="rotation6d",
|
| 113 |
+
source=config.source,
|
| 114 |
+
)
|
| 115 |
+
)
|
| 116 |
+
self.center = torch.tensor(self.dense_statistics.action.center)
|
| 117 |
+
self.scale = torch.tensor(self.dense_statistics.action.scale)
|
| 118 |
+
|
| 119 |
+
def __getattr__(self, name):
|
| 120 |
+
return getattr(self.dataset, name)
|
| 121 |
+
|
| 122 |
+
def __len__(self):
|
| 123 |
+
return len(self.dataset)
|
| 124 |
+
|
| 125 |
+
def __getitem__(self, index):
|
| 126 |
+
sample = self.dataset[index]
|
| 127 |
+
trajectory, step = self.dataset.slices[index]
|
| 128 |
+
actions = self.dense[trajectory][step : step + self.num_queries]
|
| 129 |
+
if len(actions) < self.num_queries:
|
| 130 |
+
# Native delta padding: zero arm motion, retain last continuous gripper.
|
| 131 |
+
pad = torch.cat([actions.new_zeros(9), actions[-1, -1:]])
|
| 132 |
+
actions = torch.cat(
|
| 133 |
+
[actions, pad.repeat(self.num_queries - len(actions), 1)]
|
| 134 |
+
)
|
| 135 |
+
return {**sample, "dense_actions": (actions - self.center) / self.scale}
|
fair-comparison/p3x-liftslow-v1/code/lim/keypose_diagnostics.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ose diagnostics only."""
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import gymnasium as gym
|
| 9 |
+
import h5py
|
| 10 |
+
import numpy as np
|
| 11 |
+
import torch
|
| 12 |
+
from pydantic import BaseModel, ConfigDict, Field
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def predict_action_chunk(agent, observation):
|
| 16 |
+
"""Batch-one inference, including the checkpoint's native denormalization."""
|
| 17 |
+
with torch.inference_mode():
|
| 18 |
+
inputs = {
|
| 19 |
+
k: torch.as_tensor(v, device="cuda")[None] for k, v in observation.items()
|
| 20 |
+
}
|
| 21 |
+
return agent.get_action(inputs)[0].cpu()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def predict_keypose(agent, observation):
|
| 25 |
+
"""The same batch-one/query-zero entrypoint for probes and closed-loop runs."""
|
| 26 |
+
return predict_action_chunk(agent, observation)[0]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def first_target_intervention(predicted, *, query, cube_xy=None):
|
| 30 |
+
"""Privileged XY only, on query one only; never mutate raw model output."""
|
| 31 |
+
target = predicted.clone()
|
| 32 |
+
if cube_xy is not None:
|
| 33 |
+
if query != 1:
|
| 34 |
+
raise ValueError("First-target diagnostic must not affect later queries")
|
| 35 |
+
xy = torch.as_tensor(cube_xy, dtype=target.dtype)
|
| 36 |
+
if xy.shape != (2,) or not torch.isfinite(xy).all():
|
| 37 |
+
raise ValueError("Expected finite cube center XY")
|
| 38 |
+
target[:2] = xy
|
| 39 |
+
return target
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class FirstTargetXYZConfig(BaseModel, frozen=True):
|
| 43 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 44 |
+
dataset: Path
|
| 45 |
+
"""Annotated training H5 whose adjacent JSON maps seed to episode_id."""
|
| 46 |
+
alpha: float = Field(ge=0, le=1, allow_inf_nan=False)
|
| 47 |
+
"""Retained fraction of first predicted XYZ residual relative to expert XYZ."""
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class TrainingFirstTargetXYZ:
|
| 51 |
+
"""First-query oracle intervention; never a phase selector or model input."""
|
| 52 |
+
|
| 53 |
+
def __init__(self, config: FirstTargetXYZConfig):
|
| 54 |
+
self.config = config
|
| 55 |
+
metadata_path = config.dataset.with_suffix(".json")
|
| 56 |
+
metadata_bytes = metadata_path.read_bytes()
|
| 57 |
+
metadata = json.loads(metadata_bytes)
|
| 58 |
+
self.episodes = {e["episode_seed"]: e for e in metadata["episodes"]}
|
| 59 |
+
if len(self.episodes) != len(metadata["episodes"]):
|
| 60 |
+
raise ValueError("Ambiguous training scene seeds")
|
| 61 |
+
with config.dataset.open("rb") as stream:
|
| 62 |
+
dataset_hash = hashlib.file_digest(stream, "sha256").hexdigest()
|
| 63 |
+
self.source = {
|
| 64 |
+
"dataset": str(config.dataset.resolve()),
|
| 65 |
+
"dataset_sha256": dataset_hash,
|
| 66 |
+
"metadata": str(metadata_path.resolve()),
|
| 67 |
+
"metadata_sha256": hashlib.sha256(metadata_bytes).hexdigest(),
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
def apply(self, predicted, *, query, seed):
|
| 71 |
+
if query < 1:
|
| 72 |
+
raise ValueError("Expected a positive query index")
|
| 73 |
+
target = predicted.clone()
|
| 74 |
+
# Later decisions must not read labels, change targets, or choose phases.
|
| 75 |
+
if query != 1:
|
| 76 |
+
return target, None
|
| 77 |
+
if target.shape != (10,) or not torch.isfinite(target).all():
|
| 78 |
+
raise ValueError("Expected a finite ten-dimensional keypose prediction")
|
| 79 |
+
if seed not in self.episodes:
|
| 80 |
+
raise ValueError(f"No saved training demonstration for seed {seed}")
|
| 81 |
+
episode = self.episodes[seed]
|
| 82 |
+
group_name = f"traj_{episode['episode_id']}/keyframes"
|
| 83 |
+
with h5py.File(self.config.dataset, "r") as data:
|
| 84 |
+
key = data[group_name]
|
| 85 |
+
if (
|
| 86 |
+
key.attrs.get("pose_frame") != "world"
|
| 87 |
+
or key["name"].asstr()[0] != "approach"
|
| 88 |
+
or key["kind"].asstr()[0] != "move"
|
| 89 |
+
or int(key["start_action"][0]) != 0
|
| 90 |
+
or int(key["action_keyframe_index"][0]) != 0
|
| 91 |
+
):
|
| 92 |
+
raise ValueError("Expected the initial world-frame approach target")
|
| 93 |
+
expert_pose = np.asarray(key["target_pose_world"][0])
|
| 94 |
+
if expert_pose.shape != (7,) or not np.isfinite(expert_pose).all():
|
| 95 |
+
raise ValueError("Expected a finite saved world pose7")
|
| 96 |
+
expert_xyz = torch.as_tensor(
|
| 97 |
+
expert_pose[:3], dtype=target.dtype, device=target.device
|
| 98 |
+
)
|
| 99 |
+
alpha = self.config.alpha
|
| 100 |
+
if alpha == 0:
|
| 101 |
+
target[:3] = expert_xyz
|
| 102 |
+
elif alpha != 1:
|
| 103 |
+
target[:3] = expert_xyz + alpha * (predicted[:3] - expert_xyz)
|
| 104 |
+
# alpha=1 deliberately performs no arithmetic on the executed target.
|
| 105 |
+
return target, {
|
| 106 |
+
**self.source,
|
| 107 |
+
"seed": seed,
|
| 108 |
+
"episode_id": episode["episode_id"],
|
| 109 |
+
"h5_target_path": f"{group_name}/target_pose_world",
|
| 110 |
+
"h5_target_index": 0,
|
| 111 |
+
"primitive": "approach",
|
| 112 |
+
"alpha": alpha,
|
| 113 |
+
"expert_xyz": expert_xyz.tolist(),
|
| 114 |
+
"predicted_xyz": predicted[:3].tolist(),
|
| 115 |
+
"executed_xyz": target[:3].tolist(),
|
| 116 |
+
"residual_before_m": (predicted[:3] - expert_xyz).tolist(),
|
| 117 |
+
"residual_after_m": (target[:3] - expert_xyz).tolist(),
|
| 118 |
+
"scope": "Privileged first-query XYZ diagnostic, including alpha=1 identity; not learned-policy performance",
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def nearest_cube_intervention(predicted, *, cubes):
|
| 123 |
+
"""Privileged XY on every query, snapped to the cube the model already chose.
|
| 124 |
+
|
| 125 |
+
Replaces XY precision ONLY. Height, orientation, continuous gripper and the
|
| 126 |
+
decision of when to advance stay exactly as predicted, so this isolates
|
| 127 |
+
localization error from phase advancement. The model's own object choice is
|
| 128 |
+
preserved by selecting the nearest center; the margin is recorded so that
|
| 129 |
+
ambiguous cases stay visible instead of being silently attributed.
|
| 130 |
+
"""
|
| 131 |
+
target = predicted.clone()
|
| 132 |
+
if not torch.isfinite(target).all():
|
| 133 |
+
raise ValueError("Cannot intervene on a nonfinite prediction")
|
| 134 |
+
if not cubes:
|
| 135 |
+
raise ValueError("Expected at least one named cube center")
|
| 136 |
+
names = sorted(cubes)
|
| 137 |
+
centers = torch.stack(
|
| 138 |
+
[torch.as_tensor(cubes[name], dtype=target.dtype).reshape(-1) for name in names]
|
| 139 |
+
)
|
| 140 |
+
if centers.shape != (len(names), 2) or not torch.isfinite(centers).all():
|
| 141 |
+
raise ValueError("Expected finite cube center XY per cube")
|
| 142 |
+
distances = (centers - target[:2]).norm(dim=-1)
|
| 143 |
+
order = distances.argsort()
|
| 144 |
+
chosen = int(order[0])
|
| 145 |
+
target[:2] = centers[chosen]
|
| 146 |
+
return target, {
|
| 147 |
+
"intervened_cube": names[chosen],
|
| 148 |
+
"correction_mm": float(distances[chosen]) * 1000,
|
| 149 |
+
"runner_up_cube": names[int(order[1])] if len(names) > 1 else None,
|
| 150 |
+
"selection_margin_mm": float(distances[int(order[1])] - distances[chosen])
|
| 151 |
+
* 1000
|
| 152 |
+
if len(names) > 1
|
| 153 |
+
else None,
|
| 154 |
+
"cube_centers_m": {name: centers[i].tolist() for i, name in enumerate(names)},
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class TrainingResetConfig(BaseModel, frozen=True):
|
| 159 |
+
model_config = ConfigDict(
|
| 160 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 161 |
+
)
|
| 162 |
+
env: Any
|
| 163 |
+
"""Physical environment before observation, recording and metric wrappers."""
|
| 164 |
+
dataset: Path
|
| 165 |
+
"""Saved training trajectories; only initial physical states are restored."""
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class TrainingSceneReset(gym.Wrapper):
|
| 169 |
+
def __init__(self, config: TrainingResetConfig):
|
| 170 |
+
super().__init__(config.env)
|
| 171 |
+
self.config = config
|
| 172 |
+
metadata = json.loads(config.dataset.with_suffix(".json").read_text())
|
| 173 |
+
self.episodes = {e["episode_seed"]: e for e in metadata["episodes"]}
|
| 174 |
+
if len(self.episodes) != len(metadata["episodes"]):
|
| 175 |
+
raise ValueError("Ambiguous training scene seeds")
|
| 176 |
+
|
| 177 |
+
def reset(self, *, seed=None, options=None):
|
| 178 |
+
episode = self.episodes[seed]
|
| 179 |
+
_, _ = self.env.reset(**episode["reset_kwargs"])
|
| 180 |
+
|
| 181 |
+
def first(group):
|
| 182 |
+
return {
|
| 183 |
+
k: first(v) if isinstance(v, h5py.Group) else v[0]
|
| 184 |
+
for k, v in group.items()
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
with h5py.File(self.config.dataset, "r") as data:
|
| 188 |
+
group = data[f"traj_{episode['episode_id']}"]
|
| 189 |
+
state = first(group["env_states"])
|
| 190 |
+
base = self.unwrapped
|
| 191 |
+
base.set_state_dict(state)
|
| 192 |
+
# Joint targets must start at restored joints, not random reset joints.
|
| 193 |
+
base.agent.controller.reset()
|
| 194 |
+
obs = base.get_obs()
|
| 195 |
+
np.testing.assert_allclose(
|
| 196 |
+
obs["agent"]["qpos"].cpu()[0], group["obs/agent/qpos"][0], atol=1e-6
|
| 197 |
+
)
|
| 198 |
+
np.testing.assert_allclose(
|
| 199 |
+
obs["extra"]["tcp_pose"].cpu()[0],
|
| 200 |
+
group["obs/extra/tcp_pose"][0],
|
| 201 |
+
atol=1e-6,
|
| 202 |
+
)
|
| 203 |
+
info = base.get_info()
|
| 204 |
+
info["diagnostic_training_episode_id"] = episode["episode_id"]
|
| 205 |
+
return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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Execute recorded expert keyposes, without using their dense action trajectories.
|
| 2 |
+
|
| 3 |
+
This is an oracle controller diagnostic on demonstration initial states, NOT a
|
| 4 |
+
learned-policy evaluation. Saved keypose order and targets are privileged labels.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import hashlib
|
| 8 |
+
import json
|
| 9 |
+
import time
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
import gymnasium as gym
|
| 13 |
+
import h5py
|
| 14 |
+
import mani_skill.envs # noqa: F401
|
| 15 |
+
import numpy as np
|
| 16 |
+
import torch
|
| 17 |
+
from mani_skill.utils import common
|
| 18 |
+
from pydantic import BaseModel, ConfigDict, PositiveInt
|
| 19 |
+
from pydantic_settings import CliApp
|
| 20 |
+
|
| 21 |
+
from lim.keypose_control import KeyposeControlConfig, encode_keypose, keypose_command
|
| 22 |
+
from lim.replay_pose import tree_first
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class OracleConfig(BaseModel, frozen=True):
|
| 26 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 27 |
+
dataset: Path
|
| 28 |
+
"""Annotated pose demonstration H5; only initial state and keypose labels read."""
|
| 29 |
+
output_dir: Path
|
| 30 |
+
"""New diagnostic directory; all attempts and step records retained."""
|
| 31 |
+
episodes: PositiveInt = 10
|
| 32 |
+
"""First numerically ordered demonstrations, never a selected successful subset."""
|
| 33 |
+
max_steps: PositiveInt = 200
|
| 34 |
+
"""Same finite episode horizon as policy evaluation."""
|
| 35 |
+
event_steps: PositiveInt = 6
|
| 36 |
+
"""Fixed open/close dwell after measured arrival, matching native expert duration."""
|
| 37 |
+
control: KeyposeControlConfig = KeyposeControlConfig()
|
| 38 |
+
"""Frozen TCP tracking parameters, also used by the learned policy transport."""
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def run(config: OracleConfig):
|
| 42 |
+
torch.set_num_threads(4)
|
| 43 |
+
config.output_dir.mkdir(parents=True, exist_ok=False)
|
| 44 |
+
metadata = json.loads(config.dataset.with_suffix(".json").read_text())
|
| 45 |
+
episodes = sorted(metadata["episodes"], key=lambda e: e["episode_id"])[
|
| 46 |
+
: config.episodes
|
| 47 |
+
]
|
| 48 |
+
if len(episodes) != config.episodes:
|
| 49 |
+
raise ValueError("Insufficient annotated episodes")
|
| 50 |
+
kwargs = metadata["env_info"]["env_kwargs"] | {
|
| 51 |
+
"max_episode_steps": config.max_steps
|
| 52 |
+
}
|
| 53 |
+
env = gym.make(metadata["env_info"]["env_id"], **kwargs)
|
| 54 |
+
results = []
|
| 55 |
+
started = time.time()
|
| 56 |
+
try:
|
| 57 |
+
with (
|
| 58 |
+
h5py.File(config.dataset, "r") as data,
|
| 59 |
+
(config.output_dir / "steps.jsonl").open("x") as steps,
|
| 60 |
+
):
|
| 61 |
+
for episode in episodes:
|
| 62 |
+
group = data[f"traj_{episode['episode_id']}"]
|
| 63 |
+
env.reset(**episode["reset_kwargs"])
|
| 64 |
+
base = env.unwrapped
|
| 65 |
+
base.set_state_dict(tree_first(group["env_states"]))
|
| 66 |
+
obs = base.get_obs()
|
| 67 |
+
arm = base.agent.controller.controllers["arm"]
|
| 68 |
+
if (
|
| 69 |
+
arm.config.frame != "root_translation:root_aligned_body_rotation"
|
| 70 |
+
or arm.config.use_target
|
| 71 |
+
or not arm.config.use_delta
|
| 72 |
+
or not arm.config.normalize_action
|
| 73 |
+
or not np.isclose(arm.config.rot_lower, -0.1)
|
| 74 |
+
):
|
| 75 |
+
raise ValueError("Unexpected controller semantics")
|
| 76 |
+
np.testing.assert_allclose(
|
| 77 |
+
base.agent.robot.pose.q.cpu(), [[1, 0, 0, 0]], atol=1e-6
|
| 78 |
+
)
|
| 79 |
+
np.testing.assert_allclose(
|
| 80 |
+
arm.action_space_high[:3].cpu(), [0.1] * 3, atol=1e-7
|
| 81 |
+
)
|
| 82 |
+
np.testing.assert_allclose(
|
| 83 |
+
arm.action_space_low[:3].cpu(), [-0.1] * 3, atol=1e-7
|
| 84 |
+
)
|
| 85 |
+
key = group["keyframes"]
|
| 86 |
+
targets = encode_keypose(
|
| 87 |
+
torch.from_numpy(key["target_pose_world"][:]),
|
| 88 |
+
torch.from_numpy(key["gripper_command"][:]),
|
| 89 |
+
)
|
| 90 |
+
kinds = key["kind"].asstr()[:]
|
| 91 |
+
current = torch.as_tensor(obs["extra"]["tcp_pose"])
|
| 92 |
+
grip = (
|
| 93 |
+
(torch.as_tensor(obs["agent"]["qpos"])[..., 7:9].mean(-1) + 0.01)
|
| 94 |
+
/ 0.05
|
| 95 |
+
* 2
|
| 96 |
+
- 1
|
| 97 |
+
).clamp(-1, 1)
|
| 98 |
+
index, dwell, once, end = 0, 0, False, False
|
| 99 |
+
transitions = []
|
| 100 |
+
for step in range(config.max_steps):
|
| 101 |
+
executed_index = min(index, len(targets) - 1)
|
| 102 |
+
target = targets[executed_index][None]
|
| 103 |
+
command, reached, pe, re = keypose_command(
|
| 104 |
+
current, target, grip, config.control
|
| 105 |
+
)
|
| 106 |
+
before = current.clone()
|
| 107 |
+
obs, _, _terminated, truncated, info = env.step(command)
|
| 108 |
+
grip = command[:, -1].clone()
|
| 109 |
+
current = torch.as_tensor(obs["extra"]["tcp_pose"])
|
| 110 |
+
end = bool(info["success"].item())
|
| 111 |
+
once |= end
|
| 112 |
+
reached_before = bool(reached.item())
|
| 113 |
+
if index < len(targets):
|
| 114 |
+
# Once started, an event lasts its fixed six steps even
|
| 115 |
+
# if contact briefly moves the TCP outside tolerance.
|
| 116 |
+
dwell = dwell + 1 if (reached_before or dwell > 0) else 0
|
| 117 |
+
needed = 1 if kinds[index] == "move" else config.event_steps
|
| 118 |
+
if dwell >= needed:
|
| 119 |
+
transitions.append(
|
| 120 |
+
{
|
| 121 |
+
"keyframe": index,
|
| 122 |
+
"after_step": step + 1,
|
| 123 |
+
"position_error_m": pe.item(),
|
| 124 |
+
"rotation_error_rad": re.item(),
|
| 125 |
+
}
|
| 126 |
+
)
|
| 127 |
+
index += 1
|
| 128 |
+
dwell = 0
|
| 129 |
+
steps.write(
|
| 130 |
+
json.dumps(
|
| 131 |
+
{
|
| 132 |
+
"seed": episode["episode_seed"],
|
| 133 |
+
"step": step + 1,
|
| 134 |
+
"target_index_executed": executed_index,
|
| 135 |
+
"target": target[0].tolist(),
|
| 136 |
+
"tcp_before": before[0].tolist(),
|
| 137 |
+
"command": command[0].tolist(),
|
| 138 |
+
"tcp_after": current[0].tolist(),
|
| 139 |
+
"position_error_m": pe.item(),
|
| 140 |
+
"rotation_error_rad": re.item(),
|
| 141 |
+
"success": end,
|
| 142 |
+
"cubeA_pose": common.to_numpy(base.cubeA.pose.raw_pose)[
|
| 143 |
+
0
|
| 144 |
+
].tolist(),
|
| 145 |
+
"cubeB_pose": common.to_numpy(base.cubeB.pose.raw_pose)[
|
| 146 |
+
0
|
| 147 |
+
].tolist(),
|
| 148 |
+
}
|
| 149 |
+
)
|
| 150 |
+
+ "\n"
|
| 151 |
+
)
|
| 152 |
+
if bool(truncated.item()):
|
| 153 |
+
if step + 1 != config.max_steps:
|
| 154 |
+
raise ValueError("Unexpected truncation")
|
| 155 |
+
break
|
| 156 |
+
row = {
|
| 157 |
+
"seed": episode["episode_seed"],
|
| 158 |
+
"episode_id": episode["episode_id"],
|
| 159 |
+
"success_once": once,
|
| 160 |
+
"success_at_end": end,
|
| 161 |
+
"steps": step + 1,
|
| 162 |
+
"completed_keyframes": index,
|
| 163 |
+
"keyframes": len(targets),
|
| 164 |
+
"transitions": transitions,
|
| 165 |
+
}
|
| 166 |
+
results.append(row)
|
| 167 |
+
with (config.output_dir / "episodes.jsonl").open("a") as output:
|
| 168 |
+
output.write(json.dumps(row) + "\n")
|
| 169 |
+
print("ORACLE_EPISODE", json.dumps(row), flush=True)
|
| 170 |
+
finally:
|
| 171 |
+
env.close()
|
| 172 |
+
result = {
|
| 173 |
+
"config": config.model_dump(mode="json"),
|
| 174 |
+
"episodes": len(results),
|
| 175 |
+
"success_once": sum(r["success_once"] for r in results),
|
| 176 |
+
"success_at_end": sum(r["success_at_end"] for r in results),
|
| 177 |
+
"all_keyframes_completed": sum(
|
| 178 |
+
r["completed_keyframes"] == r["keyframes"] for r in results
|
| 179 |
+
),
|
| 180 |
+
"started_epoch": started,
|
| 181 |
+
"ended_epoch": time.time(),
|
| 182 |
+
"scope": "Privileged annotated goals and ordered stages on demonstration initial states; no learned policy, no heldout task score",
|
| 183 |
+
}
|
| 184 |
+
with config.dataset.open("rb") as stream:
|
| 185 |
+
result["dataset_sha256"] = hashlib.file_digest(stream, "sha256").hexdigest()
|
| 186 |
+
(config.output_dir / "result.json").write_text(json.dumps(result, indent=2) + "\n")
|
| 187 |
+
print("KEYPOSE_ORACLE_COMPLETE", json.dumps(result), flush=True)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
if __name__ == "__main__":
|
| 191 |
+
run(CliApp.run(OracleConfig))
|
fair-comparison/p3x-liftslow-v1/code/lim/keypose_phase.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Auxiliary primitive classification from the same ACT decoder forward.
|
| 2 |
+
|
| 3 |
+
Training features include the native CVAE posterior; inference uses its zero
|
| 4 |
+
latent prior. Classification accuracy on training forwards is therefore not a
|
| 5 |
+
substitute for prior-mode phase accuracy. Phase labels never enter either branch
|
| 6 |
+
as observations, conditioning, or an execution state machine.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from pydantic import BaseModel, ConfigDict
|
| 11 |
+
from torch import nn
|
| 12 |
+
|
| 13 |
+
KEYPOSE_PHASE_NAMES = (
|
| 14 |
+
"approach",
|
| 15 |
+
"grasp_pose",
|
| 16 |
+
"close_gripper",
|
| 17 |
+
"lift",
|
| 18 |
+
"place_pose",
|
| 19 |
+
"open_gripper",
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class KeyposePhaseHeadConfig(BaseModel, frozen=True):
|
| 24 |
+
model_config = ConfigDict(
|
| 25 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 26 |
+
)
|
| 27 |
+
action_head: nn.Linear
|
| 28 |
+
"""Existing native action projection, reused without reinitialization."""
|
| 29 |
+
all_queries: bool = False
|
| 30 |
+
"""Classify every future action; false retains the original query-zero head."""
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class KeyposePhaseHead(nn.Module):
|
| 34 |
+
def __init__(self, config: KeyposePhaseHeadConfig):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.config = config
|
| 37 |
+
self.action = config.action_head
|
| 38 |
+
device = self.action.weight.device
|
| 39 |
+
devices = [device.index] if device.type == "cuda" else []
|
| 40 |
+
# The extra head must not perturb later model/EMA construction, dropout,
|
| 41 |
+
# native posterior sampling, or the training sample-order RNG.
|
| 42 |
+
with torch.random.fork_rng(devices=devices):
|
| 43 |
+
self.phase = nn.Linear(
|
| 44 |
+
self.action.in_features,
|
| 45 |
+
len(KEYPOSE_PHASE_NAMES),
|
| 46 |
+
device=device,
|
| 47 |
+
dtype=self.action.weight.dtype,
|
| 48 |
+
)
|
| 49 |
+
self.phase_logits = None
|
| 50 |
+
|
| 51 |
+
def forward(self, features):
|
| 52 |
+
if features.ndim != 3 or features.shape[1] < 1:
|
| 53 |
+
raise ValueError(
|
| 54 |
+
"Expected ACT decoder features with shape batch, query, hidden"
|
| 55 |
+
)
|
| 56 |
+
actions = self.action(features)
|
| 57 |
+
self.phase_logits = self.phase(
|
| 58 |
+
features if self.config.all_queries else features[:, 0]
|
| 59 |
+
)
|
| 60 |
+
return actions
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def read_phase_logits(model):
|
| 64 |
+
"""Return six raw class logits from the latest forward, before/after normalization.
|
| 65 |
+
|
| 66 |
+
Accept the native agent or any registered model wrapper. Does not invoke the
|
| 67 |
+
network, sample a latent, detach gradients, or change the action output.
|
| 68 |
+
"""
|
| 69 |
+
heads = [part for part in model.modules() if isinstance(part, KeyposePhaseHead)]
|
| 70 |
+
if len(heads) != 1:
|
| 71 |
+
raise ValueError("Expected exactly one enabled keypose phase head")
|
| 72 |
+
logits = heads[0].phase_logits
|
| 73 |
+
if logits is None:
|
| 74 |
+
raise RuntimeError("Phase logits require a completed policy forward")
|
| 75 |
+
return logits
|
fair-comparison/p3x-liftslow-v1/code/lim/keypose_policy.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Next-keypose supervision with optional training-only observation selection."""
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import h5py
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
from pydantic import BaseModel, ConfigDict, NonNegativeFloat
|
| 12 |
+
from torch.utils.data import Dataset
|
| 13 |
+
|
| 14 |
+
from lim.keypose_context import CONTEXT_DIM, KeyposeContextMode
|
| 15 |
+
from lim.keypose_control import encode_keypose
|
| 16 |
+
from lim.keypose_phase import KEYPOSE_PHASE_NAMES
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class KeyposeSamplingConfig(BaseModel, frozen=True):
|
| 20 |
+
model_config = ConfigDict(
|
| 21 |
+
extra="forbid", use_attribute_docstrings=True, allow_inf_nan=False
|
| 22 |
+
)
|
| 23 |
+
gripper_initial_only: bool = False
|
| 24 |
+
"""Keep only obs[start] of each close/open primitive; retain original labels."""
|
| 25 |
+
motion_endpoint_radius_m: NonNegativeFloat = 0
|
| 26 |
+
"""Exclude all move observations within this XYZ radius of obs[end]; zero disables."""
|
| 27 |
+
|
| 28 |
+
@property
|
| 29 |
+
def active(self):
|
| 30 |
+
return self.gripper_initial_only or self.motion_endpoint_radius_m > 0
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class KeyposeDatasetConfig(BaseModel, frozen=True):
|
| 34 |
+
model_config = ConfigDict(
|
| 35 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 36 |
+
)
|
| 37 |
+
dataset: Any
|
| 38 |
+
"""Native preprocessed RGB dataset; full observations and sample order retained."""
|
| 39 |
+
source: Path
|
| 40 |
+
"""Annotated H5 used to construct the native dataset in numeric trajectory order."""
|
| 41 |
+
sampling: KeyposeSamplingConfig = KeyposeSamplingConfig()
|
| 42 |
+
"""Training-only subset; full stored trajectories remain the normalization population."""
|
| 43 |
+
phase_supervision: bool = False
|
| 44 |
+
"""Return the six-class primitive index separately from observations/actions."""
|
| 45 |
+
context: KeyposeContextMode = "none"
|
| 46 |
+
"""Add completed_target11 without changing state/RGB, actions or selected slices."""
|
| 47 |
+
stop_supervision: bool = False
|
| 48 |
+
"""Return final-primitive terminal intent separately from observations/actions."""
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class KeyposeDataset(Dataset):
|
| 52 |
+
def __init__(self, config: KeyposeDatasetConfig):
|
| 53 |
+
self.config = config
|
| 54 |
+
self.dataset = config.dataset
|
| 55 |
+
self.trajectories = {**self.dataset.trajectories, "actions": []}
|
| 56 |
+
self.phase_labels = []
|
| 57 |
+
self.stop_labels = []
|
| 58 |
+
self.completed_targets = []
|
| 59 |
+
if config.stop_supervision and (
|
| 60 |
+
config.context != "previous_target"
|
| 61 |
+
or config.sampling.active
|
| 62 |
+
or config.phase_supervision
|
| 63 |
+
):
|
| 64 |
+
raise ValueError(
|
| 65 |
+
"Stop supervision preserves the full previous-target dataset without phase"
|
| 66 |
+
)
|
| 67 |
+
selected = []
|
| 68 |
+
records = []
|
| 69 |
+
with h5py.File(config.source, "r") as file:
|
| 70 |
+
names = sorted(file, key=lambda name: int(name.split("_")[-1]))[
|
| 71 |
+
: self.dataset.num_traj
|
| 72 |
+
]
|
| 73 |
+
if len(names) != self.dataset.num_traj:
|
| 74 |
+
raise ValueError(
|
| 75 |
+
"Keypose and native datasets select different trajectories"
|
| 76 |
+
)
|
| 77 |
+
for name, dense in zip(
|
| 78 |
+
names, self.dataset.trajectories["actions"], strict=True
|
| 79 |
+
):
|
| 80 |
+
key = file[name]["keyframes"]
|
| 81 |
+
indices = torch.from_numpy(key["action_keyframe_index"][:]).long()
|
| 82 |
+
if config.phase_supervision or config.stop_supervision:
|
| 83 |
+
if (
|
| 84 |
+
"name" not in key
|
| 85 |
+
or tuple(key["name"].asstr()[:]) != KEYPOSE_PHASE_NAMES
|
| 86 |
+
or indices.ndim != 1
|
| 87 |
+
or not (
|
| 88 |
+
(indices >= 0) & (indices < len(KEYPOSE_PHASE_NAMES))
|
| 89 |
+
).all()
|
| 90 |
+
):
|
| 91 |
+
raise ValueError(
|
| 92 |
+
"Phase supervision requires the canonical six primitive labels"
|
| 93 |
+
)
|
| 94 |
+
if config.phase_supervision:
|
| 95 |
+
self.phase_labels.append(indices)
|
| 96 |
+
if config.stop_supervision:
|
| 97 |
+
self.stop_labels.append(
|
| 98 |
+
(indices == len(key["name"]) - 1).float()
|
| 99 |
+
)
|
| 100 |
+
poses = torch.from_numpy(key["target_pose_world"][:])
|
| 101 |
+
gripper = torch.from_numpy(key["gripper_command"][:])
|
| 102 |
+
if len(indices) != len(dense) or dense.shape[-1] != 7:
|
| 103 |
+
raise ValueError("Expected aligned unencoded dense pose actions")
|
| 104 |
+
if not torch.equal(gripper[indices], dense[:, -1]):
|
| 105 |
+
raise ValueError("Keypose event and dense gripper labels disagree")
|
| 106 |
+
targets = encode_keypose(poses, gripper)
|
| 107 |
+
self.trajectories["actions"].append(targets[indices])
|
| 108 |
+
if config.context != "none":
|
| 109 |
+
starts = key["start_action"][:]
|
| 110 |
+
ends = key["end_action"][:]
|
| 111 |
+
if (
|
| 112 |
+
indices.ndim != 1
|
| 113 |
+
or len(starts) != len(targets)
|
| 114 |
+
or len(ends) != len(targets)
|
| 115 |
+
or not len(starts)
|
| 116 |
+
or starts[0] != 0
|
| 117 |
+
or ends[-1] != len(dense)
|
| 118 |
+
or np.any(ends <= starts)
|
| 119 |
+
or not np.array_equal(starts[1:], ends[:-1])
|
| 120 |
+
or not np.array_equal(
|
| 121 |
+
indices.numpy(),
|
| 122 |
+
np.searchsorted(ends, np.arange(len(dense)), side="right"),
|
| 123 |
+
)
|
| 124 |
+
):
|
| 125 |
+
raise ValueError(
|
| 126 |
+
"Completed-goal context requires contiguous pre-action primitive indices"
|
| 127 |
+
)
|
| 128 |
+
context = targets.new_zeros((len(indices), CONTEXT_DIM))
|
| 129 |
+
if config.context == "previous_target":
|
| 130 |
+
valid = indices > 0
|
| 131 |
+
context[valid, :10] = targets[indices[valid] - 1]
|
| 132 |
+
context[valid, -1] = 1
|
| 133 |
+
self.completed_targets.append(context)
|
| 134 |
+
keep = np.ones(len(dense), dtype=bool)
|
| 135 |
+
protected_starts = []
|
| 136 |
+
if config.sampling.active:
|
| 137 |
+
starts, ends = key["start_action"][:], key["end_action"][:]
|
| 138 |
+
kinds = key["kind"].asstr()[:]
|
| 139 |
+
if (
|
| 140 |
+
not len(starts)
|
| 141 |
+
or len(starts) != len(ends)
|
| 142 |
+
or len(kinds) != len(starts)
|
| 143 |
+
or starts[0] != 0
|
| 144 |
+
or ends[-1] != len(dense)
|
| 145 |
+
or np.any(ends <= starts)
|
| 146 |
+
or not np.array_equal(starts[1:], ends[:-1])
|
| 147 |
+
or not np.array_equal(
|
| 148 |
+
indices.numpy(),
|
| 149 |
+
np.searchsorted(ends, np.arange(len(dense)), side="right"),
|
| 150 |
+
)
|
| 151 |
+
):
|
| 152 |
+
raise ValueError("Invalid primitive boundaries for sampling")
|
| 153 |
+
tcp = file[name]["obs/extra/tcp_pose"][:].astype(np.float64)
|
| 154 |
+
if len(tcp) != len(dense) + 1 or not np.isfinite(tcp).all():
|
| 155 |
+
raise ValueError(
|
| 156 |
+
"Expected finite pre-action and terminal TCP observations"
|
| 157 |
+
)
|
| 158 |
+
for start, end, kind in zip(starts, ends, kinds, strict=True):
|
| 159 |
+
if kind in ("close", "open"):
|
| 160 |
+
if config.sampling.gripper_initial_only:
|
| 161 |
+
keep[start + 1 : end] = False
|
| 162 |
+
elif kind == "move":
|
| 163 |
+
if config.sampling.motion_endpoint_radius_m > 0:
|
| 164 |
+
near = (
|
| 165 |
+
np.linalg.norm(
|
| 166 |
+
tcp[start:end, :3] - tcp[end, :3], axis=1
|
| 167 |
+
)
|
| 168 |
+
<= config.sampling.motion_endpoint_radius_m
|
| 169 |
+
)
|
| 170 |
+
keep[start:end] &= ~near
|
| 171 |
+
else:
|
| 172 |
+
raise ValueError(f"Unknown primitive kind: {kind}")
|
| 173 |
+
protected_starts = starts[~keep[starts]].tolist()
|
| 174 |
+
keep[starts] = True
|
| 175 |
+
selected.append(keep)
|
| 176 |
+
records.append(
|
| 177 |
+
{
|
| 178 |
+
"trajectory": name,
|
| 179 |
+
"original_samples": len(dense),
|
| 180 |
+
"retained_indices": np.flatnonzero(keep).tolist(),
|
| 181 |
+
"protected_segment_starts": protected_starts,
|
| 182 |
+
}
|
| 183 |
+
)
|
| 184 |
+
self.slices = [
|
| 185 |
+
(trajectory, step)
|
| 186 |
+
for trajectory, step in self.dataset.slices
|
| 187 |
+
if selected[trajectory][step]
|
| 188 |
+
]
|
| 189 |
+
expected = sum(int(mask.sum()) for mask in selected)
|
| 190 |
+
if len(self.slices) != expected or len(set(self.slices)) != expected:
|
| 191 |
+
raise ValueError(
|
| 192 |
+
"Native sample index does not cover each obs_t exactly once"
|
| 193 |
+
)
|
| 194 |
+
encoded_indices = json.dumps(self.slices, separators=(",", ":")).encode()
|
| 195 |
+
self.sample_selection = {
|
| 196 |
+
"config": config.sampling.model_dump(mode="json"),
|
| 197 |
+
"original_samples": sum(len(mask) for mask in selected),
|
| 198 |
+
"retained_samples": len(self.slices),
|
| 199 |
+
"normalization_population": "all original unfiltered obs_t and keypose targets",
|
| 200 |
+
"index_sha256": hashlib.sha256(encoded_indices).hexdigest(),
|
| 201 |
+
"trajectories": records,
|
| 202 |
+
}
|
| 203 |
+
if config.stop_supervision:
|
| 204 |
+
labels = torch.cat(self.stop_labels)
|
| 205 |
+
self.stop_label_summary = {
|
| 206 |
+
"contract": "stop_after_target = original action_keyframe_index equals final primitive index; label only, no terminal observation or success input",
|
| 207 |
+
"samples": len(labels),
|
| 208 |
+
"positive": int(labels.sum()),
|
| 209 |
+
"negative": int((labels == 0).sum()),
|
| 210 |
+
"labels_sha256": hashlib.sha256(labels.numpy().tobytes()).hexdigest(),
|
| 211 |
+
"sample_index_sha256": self.sample_selection["index_sha256"],
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
def __getattr__(self, name):
|
| 215 |
+
return getattr(self.dataset, name)
|
| 216 |
+
|
| 217 |
+
def __len__(self):
|
| 218 |
+
return len(self.slices)
|
| 219 |
+
|
| 220 |
+
def __getitem__(self, index):
|
| 221 |
+
trajectory, step = self.slices[index]
|
| 222 |
+
observation = {
|
| 223 |
+
k: v[step] for k, v in self.trajectories["observations"][trajectory].items()
|
| 224 |
+
}
|
| 225 |
+
if self.config.context != "none":
|
| 226 |
+
observation["completed_target"] = self.completed_targets[trajectory][
|
| 227 |
+
step
|
| 228 |
+
].clone()
|
| 229 |
+
target = self.trajectories["actions"][trajectory][step]
|
| 230 |
+
# Preserve the native query embeddings/parameter count and loss averaging.
|
| 231 |
+
# All queries predict the SAME next primitive target, not future timed deltas.
|
| 232 |
+
# No terminal padding or future-frame observation is needed for this target.
|
| 233 |
+
sample = {
|
| 234 |
+
"observations": observation,
|
| 235 |
+
"actions": target[None].repeat(self.num_queries, 1),
|
| 236 |
+
}
|
| 237 |
+
if self.config.phase_supervision:
|
| 238 |
+
sample["phase"] = self.phase_labels[trajectory][step]
|
| 239 |
+
if self.config.stop_supervision:
|
| 240 |
+
sample["stop_after_target"] = self.stop_labels[trajectory][step]
|
| 241 |
+
return sample
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
class FirstKeyposeAgentConfig(BaseModel, frozen=True):
|
| 245 |
+
model_config = ConfigDict(
|
| 246 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 247 |
+
)
|
| 248 |
+
agent: Any
|
| 249 |
+
"""Frozen ACT whose queries all supervise the next world-frame keypose."""
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
class FirstKeyposeAgent:
|
| 253 |
+
def __init__(self, config: FirstKeyposeAgentConfig):
|
| 254 |
+
self.config = config
|
| 255 |
+
|
| 256 |
+
def __getattr__(self, name):
|
| 257 |
+
return getattr(self.config.agent, name)
|
| 258 |
+
|
| 259 |
+
def get_action(self, obs):
|
| 260 |
+
return self.config.agent.get_action(obs)[:, :1]
|
fair-comparison/p3x-liftslow-v1/code/lim/keypose_sequence.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Future-timestep keypose supervision from the existing annotated trajectories.
|
| 2 |
+
|
| 3 |
+
Query i receives the primitive target attached to demonstration time t + i,
|
| 4 |
+
rather than another copy of time t's primitive target. Observations and optional
|
| 5 |
+
phase supervision still describe only time t. Wrap KeyposeDataset before action
|
| 6 |
+
normalization so its original per-timestep population continues to define stats.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from pydantic import BaseModel, ConfigDict
|
| 11 |
+
from torch.utils.data import Dataset
|
| 12 |
+
|
| 13 |
+
from lim.keypose_policy import KeyposeDataset
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class KeyposeSequenceDatasetConfig(BaseModel, frozen=True):
|
| 17 |
+
model_config = ConfigDict(
|
| 18 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 19 |
+
)
|
| 20 |
+
dataset: KeyposeDataset
|
| 21 |
+
"""Unnormalized keypose dataset owning observations, slices, and full targets."""
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class KeyposeSequenceDataset(Dataset):
|
| 25 |
+
def __init__(self, config: KeyposeSequenceDatasetConfig):
|
| 26 |
+
self.config = config
|
| 27 |
+
self.dataset = config.dataset
|
| 28 |
+
|
| 29 |
+
def __getattr__(self, name):
|
| 30 |
+
return getattr(self.dataset, name)
|
| 31 |
+
|
| 32 |
+
def __len__(self):
|
| 33 |
+
return len(self.dataset)
|
| 34 |
+
|
| 35 |
+
def __getitem__(self, index):
|
| 36 |
+
sample = self.dataset[index]
|
| 37 |
+
trajectory, step = self.dataset.slices[index]
|
| 38 |
+
targets = self.dataset.trajectories["actions"][trajectory]
|
| 39 |
+
times = torch.arange(
|
| 40 |
+
step, step + self.dataset.num_queries, device=targets.device
|
| 41 |
+
).clamp_max(len(targets) - 1)
|
| 42 |
+
# Padding holds the final world keypose and its gripper command. It is
|
| 43 |
+
# deliberately not the zero-increment stop padding used by dense actions.
|
| 44 |
+
# Use original physical timesteps, including filtered-out observations;
|
| 45 |
+
# the selected slice list controls obs_t sampling, not future label time.
|
| 46 |
+
return {**sample, "actions": targets.index_select(0, times)}
|
fair-comparison/p3x-liftslow-v1/code/lim/keypose_stop.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Terminal intent from query-zero features, without changing action10 semantics.
|
| 2 |
+
|
| 3 |
+
Labels supervise whether to hold after this request completes. They are never
|
| 4 |
+
model observations or a success signal. Training uses posterior features;
|
| 5 |
+
inference logits must be read from the latest native zero-latent prior forward.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import hashlib
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
from pydantic import BaseModel, ConfigDict
|
| 12 |
+
from torch import nn
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class KeyposeStopHeadConfig(BaseModel, frozen=True):
|
| 16 |
+
model_config = ConfigDict(
|
| 17 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 18 |
+
)
|
| 19 |
+
action_head: nn.Linear
|
| 20 |
+
"""Original native action10 projection, reused without reinitialization."""
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class KeyposeStopHead(nn.Module):
|
| 24 |
+
def __init__(self, config: KeyposeStopHeadConfig):
|
| 25 |
+
super().__init__()
|
| 26 |
+
self.config = config
|
| 27 |
+
self.action = config.action_head
|
| 28 |
+
if self.action.out_features != 10:
|
| 29 |
+
raise ValueError("Stop intent requires the original keypose10 projection")
|
| 30 |
+
device = self.action.weight.device
|
| 31 |
+
devices = [device.index] if device.type == "cuda" else []
|
| 32 |
+
# Preserve subsequent context/EMA initialization and sampling/dropout RNG.
|
| 33 |
+
with torch.random.fork_rng(devices=devices):
|
| 34 |
+
self.stop = nn.Linear(
|
| 35 |
+
self.action.in_features,
|
| 36 |
+
1,
|
| 37 |
+
device=device,
|
| 38 |
+
dtype=self.action.weight.dtype,
|
| 39 |
+
)
|
| 40 |
+
self.stop_logits = None
|
| 41 |
+
|
| 42 |
+
def forward(self, features):
|
| 43 |
+
if features.ndim != 3 or features.shape[1] < 1:
|
| 44 |
+
raise ValueError("Expected ACT decoder features batch x query x hidden")
|
| 45 |
+
actions = self.action(features)
|
| 46 |
+
self.stop_logits = self.stop(features[:, 0]).squeeze(-1)
|
| 47 |
+
return actions
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def read_stop_logits(model):
|
| 51 |
+
"""Return batch logits from the latest forward without detaching or rerunning it."""
|
| 52 |
+
heads = [part for part in model.modules() if isinstance(part, KeyposeStopHead)]
|
| 53 |
+
if len(heads) != 1:
|
| 54 |
+
raise ValueError("Expected exactly one enabled keypose stop head")
|
| 55 |
+
logits = heads[0].stop_logits
|
| 56 |
+
if logits is None:
|
| 57 |
+
raise RuntimeError("Stop logits require a completed policy forward")
|
| 58 |
+
return logits
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def original_state_sha256(model):
|
| 62 |
+
"""Hash original parameters/buffers in native order, excluding only the new head.
|
| 63 |
+
|
| 64 |
+
The complete state_dict hash intentionally changes when the head is present.
|
| 65 |
+
Reversing the action wrapper's key prefix permits comparison with precision.
|
| 66 |
+
"""
|
| 67 |
+
digest = hashlib.sha256()
|
| 68 |
+
for name, tensor in model.state_dict().items():
|
| 69 |
+
if ".action_head.dense." in name:
|
| 70 |
+
continue
|
| 71 |
+
name = name.replace(".action_head.primary.", ".action_head.")
|
| 72 |
+
if ".action_head.stop." in name:
|
| 73 |
+
continue
|
| 74 |
+
original = name.replace(".action_head.action.", ".action_head.")
|
| 75 |
+
digest.update(original.encode())
|
| 76 |
+
digest.update(tensor.detach().cpu().contiguous().numpy().tobytes())
|
| 77 |
+
return digest.hexdigest()
|
fair-comparison/p3x-liftslow-v1/code/lim/keypose_trace.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Read-only diagnostics around the existing keypose execution boundary."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
from pydantic import BaseModel, ConfigDict
|
| 9 |
+
|
| 10 |
+
from lim.keypose_control import KeyposeEnv, keypose_command
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class KeyposeTraceConfig(BaseModel, frozen=True):
|
| 14 |
+
model_config = ConfigDict(
|
| 15 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 16 |
+
)
|
| 17 |
+
env: KeyposeEnv
|
| 18 |
+
"""Unmodified observed-state keypose executor."""
|
| 19 |
+
path: Path
|
| 20 |
+
"""New JSONL file of pre-action diagnostics, one row per scene and step."""
|
| 21 |
+
seed_start: int
|
| 22 |
+
"""First seed in the recorder's consecutive synchronous episode batches."""
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class KeyposeTraceEnv:
|
| 26 |
+
def __init__(self, config: KeyposeTraceConfig):
|
| 27 |
+
self.config = config
|
| 28 |
+
self.stream = config.path.open("x")
|
| 29 |
+
self.batch = 0
|
| 30 |
+
self.step_index = 0
|
| 31 |
+
|
| 32 |
+
def __getattr__(self, name):
|
| 33 |
+
return getattr(self.config.env, name)
|
| 34 |
+
|
| 35 |
+
def step(self, target):
|
| 36 |
+
env = self.config.env
|
| 37 |
+
target_tensor = torch.as_tensor(target)
|
| 38 |
+
command, reached, position_error, rotation_error = keypose_command(
|
| 39 |
+
env.current, target_tensor, env.gripper, env.config.control
|
| 40 |
+
)
|
| 41 |
+
values = {
|
| 42 |
+
"target": target_tensor,
|
| 43 |
+
"tcp_before": env.current,
|
| 44 |
+
"previous_gripper": env.gripper,
|
| 45 |
+
"recomputed_command": command,
|
| 46 |
+
"reached": reached,
|
| 47 |
+
"position_error_m": position_error,
|
| 48 |
+
"rotation_error_rad": rotation_error,
|
| 49 |
+
}
|
| 50 |
+
values = {k: v.detach().cpu().tolist() for k, v in values.items()}
|
| 51 |
+
result = env.step(target)
|
| 52 |
+
done = np.asarray(result[2]) | np.asarray(result[3])
|
| 53 |
+
if done.any() and not done.all():
|
| 54 |
+
raise ValueError("Keypose trace requires synchronous episode batches")
|
| 55 |
+
for slot in range(env.num_envs):
|
| 56 |
+
row = {key: value[slot] for key, value in values.items()}
|
| 57 |
+
row.update(
|
| 58 |
+
seed=self.config.seed_start + self.batch * env.num_envs + slot,
|
| 59 |
+
step=self.step_index,
|
| 60 |
+
done=bool(done[slot]),
|
| 61 |
+
)
|
| 62 |
+
self.stream.write(json.dumps(row, allow_nan=False) + "\n")
|
| 63 |
+
self.step_index += 1
|
| 64 |
+
if done.all():
|
| 65 |
+
self.batch += 1
|
| 66 |
+
self.step_index = 0
|
| 67 |
+
self.stream.flush()
|
| 68 |
+
return result
|
| 69 |
+
|
| 70 |
+
def finish(self):
|
| 71 |
+
self.stream.close()
|
fair-comparison/p3x-liftslow-v1/code/lim/lift_peg_env.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LiftPegUpright with the wrist-camera Panda used by every other task.
|
| 2 |
+
|
| 3 |
+
`LiftPegUprightWristcam-v1` is LiftPegUpright-v1 with `robot_uids` defaulting
|
| 4 |
+
to `panda_wristcam` instead of `panda`: the same arm with the hand camera
|
| 5 |
+
mounted, so observations are the usual base_camera + hand_camera RGB and
|
| 6 |
+
state25. Scene, randomization, base camera, success rule and the native
|
| 7 |
+
motion-planning expert are unchanged.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from mani_skill.envs.tasks.tabletop.lift_peg_upright import LiftPegUprightEnv
|
| 11 |
+
from mani_skill.utils.registration import register_env
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@register_env("LiftPegUprightWristcam-v1", max_episode_steps=50)
|
| 15 |
+
class LiftPegUprightWristcamEnv(LiftPegUprightEnv):
|
| 16 |
+
SUPPORTED_ROBOTS = ["panda_wristcam"]
|
| 17 |
+
|
| 18 |
+
def __init__(self, *args, robot_uids="panda_wristcam", **kwargs):
|
| 19 |
+
super().__init__(*args, robot_uids=robot_uids, **kwargs)
|
fair-comparison/p3x-liftslow-v1/code/lim/normalization.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Training-fitted affine transforms, independent of native delta-control stats."""
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Any, Literal
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from pydantic import (
|
| 9 |
+
BaseModel,
|
| 10 |
+
ConfigDict,
|
| 11 |
+
Field,
|
| 12 |
+
PositiveFloat,
|
| 13 |
+
PositiveInt,
|
| 14 |
+
model_validator,
|
| 15 |
+
)
|
| 16 |
+
from torch import nn
|
| 17 |
+
from torch.utils.data import Dataset
|
| 18 |
+
|
| 19 |
+
from lim.action_encoding import ActionEncoding
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class NormalizationConfig(BaseModel, frozen=True):
|
| 23 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 24 |
+
method: Literal["none", "state_zscore", "action_zscore", "action_quantile"] = "none"
|
| 25 |
+
"""One independent transform; RGB and gripper retain their native treatment."""
|
| 26 |
+
state_floor: tuple[PositiveFloat, ...] = (
|
| 27 |
+
(0.01,) * 7
|
| 28 |
+
+ (0.001,) * 2
|
| 29 |
+
+ (0.01,) * 7
|
| 30 |
+
+ (0.001,) * 2
|
| 31 |
+
+ (0.001,) * 3
|
| 32 |
+
+ (0.01,) * 4
|
| 33 |
+
)
|
| 34 |
+
"""State25 scale floors: joint rad/rad/s .01, finger m/m/s .001, TCP m .001, quaternion .01."""
|
| 35 |
+
action_floor: PositiveFloat = 0.01
|
| 36 |
+
"""Minimum std or quantile half-span in ENCODED action coordinates, not physical units."""
|
| 37 |
+
|
| 38 |
+
@model_validator(mode="after")
|
| 39 |
+
def check_layout(self):
|
| 40 |
+
if len(self.state_floor) != 25:
|
| 41 |
+
raise ValueError(
|
| 42 |
+
"State floors must follow qpos9, qvel9, TCP position3/quaternion4"
|
| 43 |
+
)
|
| 44 |
+
return self
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class AffineConfig(BaseModel, frozen=True):
|
| 48 |
+
model_config = ConfigDict(
|
| 49 |
+
extra="forbid", allow_inf_nan=False, use_attribute_docstrings=True
|
| 50 |
+
)
|
| 51 |
+
center: tuple[float, ...]
|
| 52 |
+
"""Training mean or q01/q99 midpoint, with gripper center fixed to zero."""
|
| 53 |
+
scale: tuple[PositiveFloat, ...]
|
| 54 |
+
"""Floored std or half-span, with gripper scale fixed to one."""
|
| 55 |
+
|
| 56 |
+
@model_validator(mode="after")
|
| 57 |
+
def check_lengths(self):
|
| 58 |
+
if not self.center or len(self.center) != len(self.scale):
|
| 59 |
+
raise ValueError(
|
| 60 |
+
"Affine center and scale must have matching nonempty shapes"
|
| 61 |
+
)
|
| 62 |
+
return self
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class FittedNormalizationConfig(BaseModel, frozen=True):
|
| 66 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 67 |
+
config: NormalizationConfig
|
| 68 |
+
"""Exact fitting recipe; compared against the declared policy on reload."""
|
| 69 |
+
action_encoding: ActionEncoding
|
| 70 |
+
"""Coordinates in which action statistics were fitted."""
|
| 71 |
+
source_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
|
| 72 |
+
"""Training HDF5 identity, never evaluation data."""
|
| 73 |
+
trajectories: PositiveInt
|
| 74 |
+
"""Number of loaded training trajectories used to fit statistics."""
|
| 75 |
+
samples: PositiveInt
|
| 76 |
+
"""Number of unpadded encoded targets fitted; default is one per original obs_t."""
|
| 77 |
+
state: AffineConfig
|
| 78 |
+
"""State25 transform; identity for action-only candidates."""
|
| 79 |
+
action: AffineConfig
|
| 80 |
+
"""Encoded action transform; identity for the state-only candidate."""
|
| 81 |
+
|
| 82 |
+
@model_validator(mode="after")
|
| 83 |
+
def check_contract(self):
|
| 84 |
+
dim = len(self.action.center)
|
| 85 |
+
if len(self.state.center) != 25 or dim not in (
|
| 86 |
+
(10,) if self.action_encoding == "rotation6d" else (4, 7)
|
| 87 |
+
):
|
| 88 |
+
raise ValueError(
|
| 89 |
+
"Fitted statistics differ from the supported state/action layout"
|
| 90 |
+
)
|
| 91 |
+
if self.config.method == "none":
|
| 92 |
+
raise ValueError("The unnormalized control must not have fitted statistics")
|
| 93 |
+
if self.action.center[-1] != 0 or self.action.scale[-1] != 1:
|
| 94 |
+
raise ValueError("Gripper must remain unchanged")
|
| 95 |
+
identity = self.action if self.config.method == "state_zscore" else self.state
|
| 96 |
+
if any(identity.center) or any(s != 1 for s in identity.scale):
|
| 97 |
+
raise ValueError(
|
| 98 |
+
"An independent candidate must leave the other modality unchanged"
|
| 99 |
+
)
|
| 100 |
+
return self
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class FitNormalizationConfig(BaseModel, frozen=True):
|
| 104 |
+
model_config = ConfigDict(
|
| 105 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 106 |
+
)
|
| 107 |
+
dataset: Any
|
| 108 |
+
"""Native delta dataset after action encoding, before chunk/padding normalization."""
|
| 109 |
+
normalization: NormalizationConfig
|
| 110 |
+
"""Single-factor fitting recipe."""
|
| 111 |
+
action_encoding: ActionEncoding
|
| 112 |
+
"""Coordinates of the dataset actions."""
|
| 113 |
+
source: Path
|
| 114 |
+
"""Training HDF5 used by this dataset."""
|
| 115 |
+
action_samples: Any | None = None
|
| 116 |
+
"""Explicit encoded population for sample-dependent labels; excludes padding."""
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def fit_normalization(config: FitNormalizationConfig):
|
| 120 |
+
if config.normalization.method == "none":
|
| 121 |
+
return None
|
| 122 |
+
dataset = config.dataset
|
| 123 |
+
if not dataset.delta_control or dataset.norm_stats is not None:
|
| 124 |
+
raise ValueError(
|
| 125 |
+
"Normalization requires raw native delta-control observations/actions"
|
| 126 |
+
)
|
| 127 |
+
actions, states = [], []
|
| 128 |
+
for action, obs in zip(
|
| 129 |
+
dataset.trajectories["actions"],
|
| 130 |
+
dataset.trajectories["observations"],
|
| 131 |
+
strict=True,
|
| 132 |
+
):
|
| 133 |
+
state = obs["state"]
|
| 134 |
+
if not len(action) or len(state) != len(action) + 1:
|
| 135 |
+
raise ValueError("Expected one terminal observation per trajectory")
|
| 136 |
+
actions.append(action.double())
|
| 137 |
+
states.append(state[: len(action)].double())
|
| 138 |
+
action = torch.cat(actions)
|
| 139 |
+
if config.action_samples is not None:
|
| 140 |
+
action = torch.as_tensor(config.action_samples).double()
|
| 141 |
+
if action.ndim != 2 or not len(action):
|
| 142 |
+
raise ValueError("Expected nonempty encoded action population")
|
| 143 |
+
state = torch.cat(states)
|
| 144 |
+
if not torch.isfinite(action).all() or not torch.isfinite(state).all():
|
| 145 |
+
raise ValueError("Nonfinite training data")
|
| 146 |
+
state_center, state_scale = (
|
| 147 |
+
torch.zeros(state.shape[-1]),
|
| 148 |
+
torch.ones(state.shape[-1]),
|
| 149 |
+
)
|
| 150 |
+
action_center, action_scale = (
|
| 151 |
+
torch.zeros(action.shape[-1]),
|
| 152 |
+
torch.ones(action.shape[-1]),
|
| 153 |
+
)
|
| 154 |
+
method = config.normalization.method
|
| 155 |
+
if method == "state_zscore":
|
| 156 |
+
state_center = state.mean(0)
|
| 157 |
+
state_scale = torch.maximum(
|
| 158 |
+
state.std(0, correction=0),
|
| 159 |
+
state.new_tensor(config.normalization.state_floor),
|
| 160 |
+
)
|
| 161 |
+
elif method == "action_zscore":
|
| 162 |
+
action_center = action.mean(0)
|
| 163 |
+
action_scale = action.std(0, correction=0).clamp_min(
|
| 164 |
+
config.normalization.action_floor
|
| 165 |
+
)
|
| 166 |
+
else:
|
| 167 |
+
low, high = torch.quantile(action, action.new_tensor([0.01, 0.99]), dim=0)
|
| 168 |
+
action_center = (low + high) / 2
|
| 169 |
+
action_scale = ((high - low) / 2).clamp_min(config.normalization.action_floor)
|
| 170 |
+
action_center[-1], action_scale[-1] = 0, 1
|
| 171 |
+
with config.source.open("rb") as stream:
|
| 172 |
+
source_sha256 = hashlib.file_digest(stream, "sha256").hexdigest()
|
| 173 |
+
return FittedNormalizationConfig(
|
| 174 |
+
config=config.normalization,
|
| 175 |
+
action_encoding=config.action_encoding,
|
| 176 |
+
source_sha256=source_sha256,
|
| 177 |
+
trajectories=len(actions),
|
| 178 |
+
samples=len(action),
|
| 179 |
+
state=AffineConfig(center=state_center.tolist(), scale=state_scale.tolist()),
|
| 180 |
+
action=AffineConfig(center=action_center.tolist(), scale=action_scale.tolist()),
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class NormalizedDatasetConfig(BaseModel, frozen=True):
|
| 185 |
+
model_config = ConfigDict(
|
| 186 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 187 |
+
)
|
| 188 |
+
dataset: Any
|
| 189 |
+
"""Encoded native dataset, still owning physical stop padding."""
|
| 190 |
+
statistics: FittedNormalizationConfig
|
| 191 |
+
"""Training-only fitted affine parameters."""
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class NormalizedDataset(Dataset):
|
| 195 |
+
def __init__(self, config: NormalizedDatasetConfig):
|
| 196 |
+
self.config = config
|
| 197 |
+
self.dataset = config.dataset
|
| 198 |
+
self.center = torch.tensor(config.statistics.action.center)
|
| 199 |
+
self.scale = torch.tensor(config.statistics.action.scale)
|
| 200 |
+
|
| 201 |
+
def __getattr__(self, name):
|
| 202 |
+
return getattr(self.dataset, name)
|
| 203 |
+
|
| 204 |
+
def __len__(self):
|
| 205 |
+
return len(self.dataset)
|
| 206 |
+
|
| 207 |
+
def __getitem__(self, index):
|
| 208 |
+
sample = self.dataset[index]
|
| 209 |
+
# Native dataset has already padded zero motion and held the last gripper.
|
| 210 |
+
return {**sample, "actions": (sample["actions"] - self.center) / self.scale}
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
class NormalizedModelConfig(BaseModel, frozen=True):
|
| 214 |
+
model_config = ConfigDict(
|
| 215 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 216 |
+
)
|
| 217 |
+
model: Any
|
| 218 |
+
"""Native CVAE; receives normalized labels and the same normalized state in both branches."""
|
| 219 |
+
statistics: FittedNormalizationConfig
|
| 220 |
+
"""Checkpoint-owned transforms; these do not consume random initialization draws."""
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
class NormalizedModel(nn.Module):
|
| 224 |
+
def __init__(self, config: NormalizedModelConfig):
|
| 225 |
+
super().__init__()
|
| 226 |
+
self.config = config
|
| 227 |
+
self.base = config.model
|
| 228 |
+
# Saved once as checkpoint metadata, not averaged as EMA parameters/buffers.
|
| 229 |
+
for name, values in (
|
| 230 |
+
("state_center", config.statistics.state.center),
|
| 231 |
+
("state_scale", config.statistics.state.scale),
|
| 232 |
+
("action_center", config.statistics.action.center),
|
| 233 |
+
("action_scale", config.statistics.action.scale),
|
| 234 |
+
):
|
| 235 |
+
self.register_buffer(name, torch.tensor(values), persistent=False)
|
| 236 |
+
|
| 237 |
+
def forward(self, obs, actions=None):
|
| 238 |
+
obs = {**obs, "state": (obs["state"] - self.state_center) / self.state_scale}
|
| 239 |
+
prediction, latent = self.base(obs, actions)
|
| 240 |
+
if actions is None:
|
| 241 |
+
# Invert BEFORE native time ensembling and Rotation6DEnv projection.
|
| 242 |
+
# No clipping, including predictions outside q01/q99.
|
| 243 |
+
prediction = prediction * self.action_scale + self.action_center
|
| 244 |
+
return prediction, latent
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def checked_statistics(raw, normalization, encoding):
|
| 248 |
+
if normalization.method == "none":
|
| 249 |
+
if raw is not None:
|
| 250 |
+
raise ValueError(
|
| 251 |
+
"Unnormalized control unexpectedly contains fitted statistics"
|
| 252 |
+
)
|
| 253 |
+
return None
|
| 254 |
+
if raw is None:
|
| 255 |
+
raise ValueError(
|
| 256 |
+
"Normalized policy requires its training-fitted checkpoint statistics"
|
| 257 |
+
)
|
| 258 |
+
fitted = FittedNormalizationConfig.model_validate(raw)
|
| 259 |
+
if fitted.config != normalization or fitted.action_encoding != encoding:
|
| 260 |
+
raise ValueError(
|
| 261 |
+
"Fitted statistics differ from the policy normalization contract"
|
| 262 |
+
)
|
| 263 |
+
return fitted
|
fair-comparison/p3x-liftslow-v1/code/lim/observations.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Measured observations shared by all policy variants; no simulator labels."""
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
from pydantic import BaseModel, ConfigDict, PositiveInt
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class ObservationConfig(BaseModel, frozen=True):
|
| 8 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 9 |
+
points: PositiveInt = 256
|
| 10 |
+
"""Total points, split equally between visible role colors and context."""
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def as_numpy(value):
|
| 14 |
+
if hasattr(value, "detach"):
|
| 15 |
+
return value.detach().cpu().numpy()
|
| 16 |
+
return np.asarray(value)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def sample_points(points: np.ndarray, count: int) -> np.ndarray:
|
| 20 |
+
if len(points) == 0:
|
| 21 |
+
return np.zeros((count, 6), dtype=np.float32)
|
| 22 |
+
# Deterministic sampling; independent of labels, episode seed, and test set.
|
| 23 |
+
indices = np.linspace(0, len(points) - 1, count).astype(np.int64)
|
| 24 |
+
return points[indices].astype(np.float32)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def cloud_from_rgbd(obs: dict) -> tuple[np.ndarray, np.ndarray]:
|
| 28 |
+
"""Unproject millimeter optical depth using calibrated CV cameras."""
|
| 29 |
+
coordinates, colors = [], []
|
| 30 |
+
for name, view in obs["sensor_data"].items():
|
| 31 |
+
depth = as_numpy(view["depth"]).squeeze().astype(np.float32) / 1000
|
| 32 |
+
rgb = as_numpy(view["rgb"]).reshape(-1, 3)
|
| 33 |
+
height, width = depth.shape
|
| 34 |
+
v, u = np.mgrid[:height, :width]
|
| 35 |
+
pixels = np.stack([u + 0.5, v + 0.5, np.ones_like(u)], axis=-1).reshape(-1, 3)
|
| 36 |
+
params = obs["sensor_param"][name]
|
| 37 |
+
intrinsic = as_numpy(params["intrinsic_cv"]).reshape(3, 3)
|
| 38 |
+
extrinsic = as_numpy(params["extrinsic_cv"]).reshape(3, 4)
|
| 39 |
+
camera_xyz = (pixels @ np.linalg.inv(intrinsic).T) * depth.reshape(-1, 1)
|
| 40 |
+
world_xyz = (camera_xyz - extrinsic[:, 3]) @ extrinsic[:, :3]
|
| 41 |
+
coordinates.append(np.c_[world_xyz, depth.reshape(-1) > 0].astype(np.float32))
|
| 42 |
+
colors.append(rgb)
|
| 43 |
+
return np.concatenate(coordinates), np.concatenate(colors)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def encode_observation(obs: dict, config: ObservationConfig) -> dict[str, np.ndarray]:
|
| 47 |
+
"""Only camera point XYZ/RGB, joint positions/velocities and measured TCP pose."""
|
| 48 |
+
if obs.get("sensor_data") and "depth" in next(iter(obs["sensor_data"].values())):
|
| 49 |
+
xyzw, raw_rgb = cloud_from_rgbd(obs)
|
| 50 |
+
else:
|
| 51 |
+
xyzw = as_numpy(obs["pointcloud"]["xyzw"]).reshape(-1, 4)
|
| 52 |
+
raw_rgb = as_numpy(obs["pointcloud"]["rgb"]).reshape(-1, 3)
|
| 53 |
+
rgb = raw_rgb.astype(np.float32) / 255
|
| 54 |
+
tcp = as_numpy(obs["extra"]["tcp_pose"]).reshape(-1, 7)[0]
|
| 55 |
+
qpos = as_numpy(obs["agent"]["qpos"]).reshape(-1, 9)[0]
|
| 56 |
+
qvel = as_numpy(obs["agent"]["qvel"]).reshape(-1, 9)[0]
|
| 57 |
+
valid = (xyzw[:, 3] > 0) & np.isfinite(xyzw).all(axis=1)
|
| 58 |
+
xyz = xyzw[:, :3]
|
| 59 |
+
valid &= (xyz[:, 2] > 0.005) & (xyz[:, 2] < 0.6)
|
| 60 |
+
valid &= (abs(xyz[:, 0]) < 0.5) & (abs(xyz[:, 1]) < 0.5)
|
| 61 |
+
xyz, rgb = xyz[valid], rgb[valid]
|
| 62 |
+
source = (
|
| 63 |
+
(rgb[:, 0] > 0.25)
|
| 64 |
+
& (rgb[:, 0] > 1.8 * rgb[:, 1])
|
| 65 |
+
& (rgb[:, 0] > 1.8 * rgb[:, 2])
|
| 66 |
+
)
|
| 67 |
+
target = (
|
| 68 |
+
(rgb[:, 1] > 0.25)
|
| 69 |
+
& (rgb[:, 1] > 1.8 * rgb[:, 0])
|
| 70 |
+
& (rgb[:, 1] > 1.8 * rgb[:, 2])
|
| 71 |
+
)
|
| 72 |
+
target_center = xyz[target].mean(axis=0) if target.any() else np.zeros(3)
|
| 73 |
+
points = np.concatenate([(xyz - tcp[:3]) / 0.3, rgb], axis=1)
|
| 74 |
+
role_count = config.points // 4
|
| 75 |
+
selected = np.concatenate(
|
| 76 |
+
[
|
| 77 |
+
sample_points(points[source], role_count),
|
| 78 |
+
sample_points(points[target], role_count),
|
| 79 |
+
sample_points(points, config.points - 2 * role_count),
|
| 80 |
+
]
|
| 81 |
+
)
|
| 82 |
+
state = np.concatenate([qpos, qvel, tcp, target_center, [float(target.any())]])
|
| 83 |
+
return {
|
| 84 |
+
"points": selected,
|
| 85 |
+
"state": state.astype(np.float32),
|
| 86 |
+
"tcp": tcp.astype(np.float32),
|
| 87 |
+
"target": np.asarray(target_center, dtype=np.float32),
|
| 88 |
+
"counts": np.array([len(xyzw), len(xyz), int(source.sum()), int(target.sum())]),
|
| 89 |
+
}
|
fair-comparison/p3x-liftslow-v1/code/lim/ood_env.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Out-of-distribution StackCube variants for evaluation only.
|
| 2 |
+
|
| 3 |
+
`StackCubeOOD-v1` is StackCube-v1 with two optional changes:
|
| 4 |
+
- `ood_position`: both cubes start in a ring outside the training placement
|
| 5 |
+
box (x in [-0.2, 0.2], y in [-0.3, 0.3]) but inside x in [-0.25, 0.25],
|
| 6 |
+
y in [-0.35, 0.35] and within `reach_m` of the robot base; draws come from
|
| 7 |
+
the episode seed, independent of the native sampler.
|
| 8 |
+
- `cube_scale`: both cube edge lengths scaled; spacing and the success
|
| 9 |
+
tolerance follow the scaled size exactly as the native task defines them.
|
| 10 |
+
Everything else (robot, cameras, rotations, success rule) is unchanged.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
import sapien
|
| 15 |
+
import torch
|
| 16 |
+
from mani_skill.envs.tasks.tabletop.stack_cube import StackCubeEnv
|
| 17 |
+
from mani_skill.envs.utils import randomization
|
| 18 |
+
from mani_skill.utils import common
|
| 19 |
+
from mani_skill.utils.building import actors
|
| 20 |
+
from mani_skill.utils.registration import register_env
|
| 21 |
+
from mani_skill.utils.scene_builder.table import TableSceneBuilder
|
| 22 |
+
from mani_skill.utils.structs.pose import Pose
|
| 23 |
+
|
| 24 |
+
INNER = ((-0.2, 0.2), (-0.3, 0.3))
|
| 25 |
+
OUTER = ((-0.25, 0.25), (-0.35, 0.35))
|
| 26 |
+
BASE_XY = np.array([-0.615, 0.0])
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def ring_positions(seed, spacing, reach_m=0.8):
|
| 30 |
+
"""Two cube xy positions in the OOD ring, at least `spacing` apart."""
|
| 31 |
+
rng = np.random.default_rng([20261005, seed])
|
| 32 |
+
chosen = []
|
| 33 |
+
while len(chosen) < 2:
|
| 34 |
+
xy = np.array([rng.uniform(*OUTER[0]), rng.uniform(*OUTER[1])])
|
| 35 |
+
inside = INNER[0][0] <= xy[0] <= INNER[0][1] and INNER[1][0] <= xy[1] <= INNER[1][1]
|
| 36 |
+
if inside or np.linalg.norm(xy - BASE_XY) > reach_m:
|
| 37 |
+
continue
|
| 38 |
+
if chosen and np.linalg.norm(xy - chosen[0]) <= spacing:
|
| 39 |
+
continue
|
| 40 |
+
chosen.append(xy)
|
| 41 |
+
return np.stack(chosen)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@register_env("StackCubeOOD-v1", max_episode_steps=50)
|
| 45 |
+
class StackCubeOODEnv(StackCubeEnv):
|
| 46 |
+
def __init__(self, *args, ood_position=False, cube_scale=1.0, **kwargs):
|
| 47 |
+
self.ood_position = ood_position
|
| 48 |
+
self.cube_scale = float(cube_scale)
|
| 49 |
+
self.ood_seed = None
|
| 50 |
+
super().__init__(*args, **kwargs)
|
| 51 |
+
|
| 52 |
+
def reset(self, seed=None, options=None):
|
| 53 |
+
self.ood_seed = seed
|
| 54 |
+
return super().reset(seed=seed, options=options)
|
| 55 |
+
|
| 56 |
+
def _load_scene(self, options: dict):
|
| 57 |
+
half = 0.02 * self.cube_scale
|
| 58 |
+
self.cube_half_size = common.to_tensor([half] * 3, device=self.device)
|
| 59 |
+
self.table_scene = TableSceneBuilder(
|
| 60 |
+
env=self, robot_init_qpos_noise=self.robot_init_qpos_noise
|
| 61 |
+
)
|
| 62 |
+
self.table_scene.build()
|
| 63 |
+
self.cubeA = actors.build_cube(self.scene, half_size=half, color=[1, 0, 0, 1],
|
| 64 |
+
name="cubeA", initial_pose=sapien.Pose(p=[0, 0, 0.1]))
|
| 65 |
+
self.cubeB = actors.build_cube(self.scene, half_size=half, color=[0, 1, 0, 1],
|
| 66 |
+
name="cubeB", initial_pose=sapien.Pose(p=[1, 0, 0.1]))
|
| 67 |
+
|
| 68 |
+
def _initialize_episode(self, env_idx: torch.Tensor, options: dict):
|
| 69 |
+
with torch.device(self.device):
|
| 70 |
+
b = len(env_idx)
|
| 71 |
+
self.table_scene.initialize(env_idx)
|
| 72 |
+
half = 0.02 * self.cube_scale
|
| 73 |
+
radius = torch.linalg.norm(torch.tensor([half, half])) + 0.001
|
| 74 |
+
xyz = torch.zeros((b, 3))
|
| 75 |
+
xyz[:, 2] = half
|
| 76 |
+
# Construction resets once without a seed; every evaluated episode
|
| 77 |
+
# passes its scene seed, which then fixes the OOD placement.
|
| 78 |
+
if self.ood_position and self.ood_seed is not None:
|
| 79 |
+
if b != 1:
|
| 80 |
+
raise ValueError("OOD placement draws one scene per episode seed")
|
| 81 |
+
placed = torch.as_tensor(ring_positions(self.ood_seed, 2 * float(radius)),
|
| 82 |
+
dtype=torch.float32)
|
| 83 |
+
cubeA_xy, cubeB_xy = placed[:1], placed[1:]
|
| 84 |
+
else:
|
| 85 |
+
xy = torch.rand((b, 2)) * 0.2 - 0.1
|
| 86 |
+
sampler = randomization.UniformPlacementSampler(
|
| 87 |
+
bounds=[[-0.1, -0.2], [0.1, 0.2]], batch_size=b, device=self.device
|
| 88 |
+
)
|
| 89 |
+
cubeA_xy = xy + sampler.sample(radius, 100)
|
| 90 |
+
cubeB_xy = xy + sampler.sample(radius, 100, verbose=False)
|
| 91 |
+
for actor, cube_xy in ((self.cubeA, cubeA_xy), (self.cubeB, cubeB_xy)):
|
| 92 |
+
xyz[:, :2] = cube_xy
|
| 93 |
+
qs = randomization.random_quaternions(b, lock_x=True, lock_y=True, lock_z=False)
|
| 94 |
+
actor.set_pose(Pose.create_from_pq(p=xyz.clone(), q=qs))
|
fair-comparison/p3x-liftslow-v1/code/lim/planned_keypose.py
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Latch a predicted world pose through its path and measured gripper completion."""
|
| 2 |
+
|
| 3 |
+
from collections import deque
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
from pydantic import (
|
| 9 |
+
BaseModel,
|
| 10 |
+
ConfigDict,
|
| 11 |
+
NonNegativeInt,
|
| 12 |
+
PositiveFloat,
|
| 13 |
+
model_validator,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
from lim.gripper_feedback import (
|
| 17 |
+
GripperCompletion,
|
| 18 |
+
GripperCompletionConfig,
|
| 19 |
+
GripperMeasurement,
|
| 20 |
+
)
|
| 21 |
+
from lim.keypose_control import KeyposeControlConfig, keypose_error
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class PlannerConfig(BaseModel, frozen=True):
|
| 25 |
+
model_config = ConfigDict(
|
| 26 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 27 |
+
)
|
| 28 |
+
env: Any
|
| 29 |
+
"""Single physical Panda environment; only robot state is used by planning."""
|
| 30 |
+
joint_velocity_scale: PositiveFloat = 0.9
|
| 31 |
+
"""Multiplier on MPLib's robot joint velocity limits, matching the expert."""
|
| 32 |
+
joint_acceleration_scale: PositiveFloat = 0.9
|
| 33 |
+
"""Multiplier on joint acceleration limits, matching the expert."""
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class MplibKeyposePlanner:
|
| 37 |
+
def __init__(self, config: PlannerConfig):
|
| 38 |
+
from mani_skill.examples.motionplanning.panda.motionplanner import (
|
| 39 |
+
PandaArmMotionPlanningSolver,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
self.config = config
|
| 43 |
+
self.last_status = "not_planned"
|
| 44 |
+
self.solver = PandaArmMotionPlanningSolver(
|
| 45 |
+
config.env,
|
| 46 |
+
debug=False,
|
| 47 |
+
vis=False,
|
| 48 |
+
base_pose=config.env.unwrapped.agent.robot.pose,
|
| 49 |
+
visualize_target_grasp_pose=False,
|
| 50 |
+
print_env_info=False,
|
| 51 |
+
joint_vel_limits=config.joint_velocity_scale,
|
| 52 |
+
joint_acc_limits=config.joint_acceleration_scale,
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
def plan(self, target):
|
| 56 |
+
import sapien
|
| 57 |
+
from mani_skill.utils.geometry.rotation_conversions import matrix_to_quaternion
|
| 58 |
+
|
| 59 |
+
from lim.action_encoding import sixd_to_matrix
|
| 60 |
+
|
| 61 |
+
target = torch.as_tensor(target, dtype=torch.float32)
|
| 62 |
+
if target.shape != (10,) or not torch.isfinite(target).all():
|
| 63 |
+
raise ValueError("Expected a finite world keypose10")
|
| 64 |
+
quaternion = matrix_to_quaternion(sixd_to_matrix(target[3:9])).numpy()
|
| 65 |
+
pose = sapien.Pose(target[:3].numpy(), quaternion)
|
| 66 |
+
# Same screw planner and native retry as collection. No object geometry,
|
| 67 |
+
# expert phase, grasp labels, extra obstacles or fallback goals supplied.
|
| 68 |
+
result = self.solver.move_to_pose_with_screw(pose, dry_run=True)
|
| 69 |
+
if isinstance(result, int):
|
| 70 |
+
self.last_status = "native_planning_failed"
|
| 71 |
+
return None
|
| 72 |
+
position = np.asarray(result["position"], dtype=np.float32)
|
| 73 |
+
if position.ndim == 2 and position.shape == (0, 7):
|
| 74 |
+
# Native TOPP can sample zero points when duration < one control
|
| 75 |
+
# interval. There is no trajectory to execute; record a failed plan.
|
| 76 |
+
self.last_status = "native_empty_trajectory"
|
| 77 |
+
return None
|
| 78 |
+
if (
|
| 79 |
+
position.ndim != 2
|
| 80 |
+
or position.shape[1] != 7
|
| 81 |
+
or len(position) == 0
|
| 82 |
+
or not np.isfinite(position).all()
|
| 83 |
+
):
|
| 84 |
+
raise ValueError("Invalid planned joint trajectory")
|
| 85 |
+
self.last_status = "Success"
|
| 86 |
+
return result
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class PlannedExecutorConfig(BaseModel, frozen=True):
|
| 90 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 91 |
+
control: KeyposeControlConfig = KeyposeControlConfig()
|
| 92 |
+
"""Original pose tolerances for diagnostics only; they do not block completion."""
|
| 93 |
+
gripper_completion: GripperCompletionConfig = GripperCompletionConfig()
|
| 94 |
+
"""Measured finger target/contact stability required before querying again."""
|
| 95 |
+
initial_gripper: float = 1.0
|
| 96 |
+
"""Measured initial finger position mapped to the continuous command range."""
|
| 97 |
+
resume_after_incomplete: bool = False
|
| 98 |
+
"""Return to prediction after a gripper timeout or arrest instead of ending the
|
| 99 |
+
episode. The original contract has no path back from gripper_timeout, so a
|
| 100 |
+
single unmet gripper command freezes the remaining budget with zero further
|
| 101 |
+
queries. Default false preserves every previously scored run."""
|
| 102 |
+
carry_gripper_feedback: bool = False
|
| 103 |
+
"""Reuse fresh stable feedback from the motion only when the next gripper
|
| 104 |
+
command is exactly the same executed float32 command after clipping.
|
| 105 |
+
A changed command retains the original post-path feedback protocol."""
|
| 106 |
+
motion_replan_steps: NonNegativeInt = 0
|
| 107 |
+
"""Actual motion steps between fresh target/plan attempts; zero keeps full paths."""
|
| 108 |
+
|
| 109 |
+
@model_validator(mode="after")
|
| 110 |
+
def check_motion_replan(self):
|
| 111 |
+
if self.motion_replan_steps and (
|
| 112 |
+
self.resume_after_incomplete or self.carry_gripper_feedback
|
| 113 |
+
):
|
| 114 |
+
raise ValueError("Motion replanning requires isolated completion semantics")
|
| 115 |
+
return self
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class PlannedKeyposeExecutor:
|
| 119 |
+
def __init__(self, config: PlannedExecutorConfig):
|
| 120 |
+
self.config = config
|
| 121 |
+
self.gripper = float(config.initial_gripper)
|
| 122 |
+
self.phase = "ready"
|
| 123 |
+
self.target = None
|
| 124 |
+
self.path = None
|
| 125 |
+
self.index = 0
|
| 126 |
+
self.completion = None
|
| 127 |
+
# Cumulative, because resuming clears the phase that used to record it.
|
| 128 |
+
self.gripper_timeouts = 0
|
| 129 |
+
self.gripper_arrests = 0
|
| 130 |
+
self.gripper_feedback_carried = 0
|
| 131 |
+
self.motion_feedback = deque(maxlen=config.gripper_completion.stable_steps)
|
| 132 |
+
self.motion_observed_steps = 0
|
| 133 |
+
self.motion_command = None
|
| 134 |
+
self.completed_target = None
|
| 135 |
+
self.completed_target_query = None
|
| 136 |
+
self.completed_goals = 0
|
| 137 |
+
self.active_query = None
|
| 138 |
+
self.goal_id = 0
|
| 139 |
+
self.path_revision = 0
|
| 140 |
+
self.accepted_paths = 0
|
| 141 |
+
self.replan_attempts = 0
|
| 142 |
+
self.replan_failures = 0
|
| 143 |
+
self.goal_replan_attempts = 0
|
| 144 |
+
self.motion_steps_since_attempt = 0
|
| 145 |
+
self.goal_motion_steps = 0
|
| 146 |
+
self.total_motion_steps = 0
|
| 147 |
+
self._motion_step_pending = False
|
| 148 |
+
|
| 149 |
+
@property
|
| 150 |
+
def needs_prediction(self):
|
| 151 |
+
return self.phase == "ready"
|
| 152 |
+
|
| 153 |
+
@property
|
| 154 |
+
def needs_motion_replan(self):
|
| 155 |
+
return bool(
|
| 156 |
+
self.config.motion_replan_steps
|
| 157 |
+
and self.phase == "trajectory"
|
| 158 |
+
and self.index < len(self.path)
|
| 159 |
+
and not self._motion_step_pending
|
| 160 |
+
and self.motion_steps_since_attempt >= self.config.motion_replan_steps
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
@staticmethod
|
| 164 |
+
def _checked_target(target):
|
| 165 |
+
target = torch.as_tensor(target, dtype=torch.float32).clone()
|
| 166 |
+
if target.shape != (10,) or not torch.isfinite(target).all():
|
| 167 |
+
raise ValueError("Expected a finite world keypose10")
|
| 168 |
+
return target
|
| 169 |
+
|
| 170 |
+
@staticmethod
|
| 171 |
+
def _checked_path(path):
|
| 172 |
+
path = np.asarray(path, dtype=np.float32).copy()
|
| 173 |
+
if (
|
| 174 |
+
path.ndim != 2
|
| 175 |
+
or path.shape[1] != 7
|
| 176 |
+
or not len(path)
|
| 177 |
+
or not np.isfinite(path).all()
|
| 178 |
+
):
|
| 179 |
+
raise ValueError("Expected a nonempty finite N x 7 planned trajectory")
|
| 180 |
+
return path
|
| 181 |
+
|
| 182 |
+
def begin(self, target, path, current_qpos, *, source_query=None):
|
| 183 |
+
if not self.needs_prediction:
|
| 184 |
+
raise RuntimeError("Cannot replace an unfinished keypose trajectory")
|
| 185 |
+
self.target = self._checked_target(target)
|
| 186 |
+
self.active_query = source_query
|
| 187 |
+
self.goal_id += 1
|
| 188 |
+
self.path_revision = 0
|
| 189 |
+
self.goal_replan_attempts = 0
|
| 190 |
+
self.motion_steps_since_attempt = 0
|
| 191 |
+
self.goal_motion_steps = 0
|
| 192 |
+
self._motion_step_pending = False
|
| 193 |
+
self.index = 0
|
| 194 |
+
self.completion = None
|
| 195 |
+
self.motion_feedback.clear()
|
| 196 |
+
self.motion_observed_steps = 0
|
| 197 |
+
self.motion_command = None
|
| 198 |
+
if path is None:
|
| 199 |
+
self.path = np.asarray(current_qpos, dtype=np.float32)[None, :7].copy()
|
| 200 |
+
self.phase = "planning_failed"
|
| 201 |
+
else:
|
| 202 |
+
self.path = self._checked_path(path)
|
| 203 |
+
self.accepted_paths += 1
|
| 204 |
+
self.phase = "trajectory"
|
| 205 |
+
|
| 206 |
+
def replace_motion_plan(self, target, path, *, source_query):
|
| 207 |
+
"""Resolve one due dry-run attempt without completing the active goal.
|
| 208 |
+
|
| 209 |
+
None means planner failure: preserve target/path/index/gripper and only
|
| 210 |
+
reset the retry interval. Invalid numeric output raises before mutation.
|
| 211 |
+
"""
|
| 212 |
+
if not self.needs_motion_replan:
|
| 213 |
+
raise RuntimeError("Motion replanning requires a due unfinished trajectory")
|
| 214 |
+
candidate = self._checked_target(target)
|
| 215 |
+
candidate_path = None if path is None else self._checked_path(path)
|
| 216 |
+
self.replan_attempts += 1
|
| 217 |
+
self.goal_replan_attempts += 1
|
| 218 |
+
self.motion_steps_since_attempt = 0
|
| 219 |
+
if candidate_path is None:
|
| 220 |
+
self.replan_failures += 1
|
| 221 |
+
return False
|
| 222 |
+
self.target, self.path = candidate, candidate_path
|
| 223 |
+
self.active_query = source_query
|
| 224 |
+
self.index = 0
|
| 225 |
+
self.path_revision += 1
|
| 226 |
+
self.accepted_paths += 1
|
| 227 |
+
return True
|
| 228 |
+
|
| 229 |
+
def observe_motion_step(self):
|
| 230 |
+
"""Acknowledge env.step, never an inference call or merely built command."""
|
| 231 |
+
if not self.config.motion_replan_steps or not self._motion_step_pending:
|
| 232 |
+
raise RuntimeError(
|
| 233 |
+
"Motion accounting requires one executed pending command"
|
| 234 |
+
)
|
| 235 |
+
self._motion_step_pending = False
|
| 236 |
+
self.motion_steps_since_attempt += 1
|
| 237 |
+
self.goal_motion_steps += 1
|
| 238 |
+
self.total_motion_steps += 1
|
| 239 |
+
|
| 240 |
+
def _publish_completed_target(self):
|
| 241 |
+
self.completed_target = self.target.clone()
|
| 242 |
+
self.completed_target_query = self.active_query
|
| 243 |
+
self.completed_goals += 1
|
| 244 |
+
|
| 245 |
+
def command(self, current_tcp):
|
| 246 |
+
if self.needs_prediction:
|
| 247 |
+
raise RuntimeError("Predict before requesting the next command")
|
| 248 |
+
if self.config.motion_replan_steps and self._motion_step_pending:
|
| 249 |
+
raise RuntimeError(
|
| 250 |
+
"Acknowledge the physical motion step before a new command"
|
| 251 |
+
)
|
| 252 |
+
delta, rotation = keypose_error(torch.as_tensor(current_tcp), self.target)
|
| 253 |
+
position_error, rotation_error = float(delta.norm()), float(rotation.norm())
|
| 254 |
+
reached = (
|
| 255 |
+
position_error <= self.config.control.position_tolerance_m
|
| 256 |
+
and rotation_error <= self.config.control.rotation_tolerance_rad
|
| 257 |
+
)
|
| 258 |
+
if self.phase == "path_complete":
|
| 259 |
+
self.phase = "gripper"
|
| 260 |
+
self.gripper = float(self.target[-1].clamp(-1, 1))
|
| 261 |
+
self.completion = GripperCompletion(self.config.gripper_completion)
|
| 262 |
+
phase = self.phase
|
| 263 |
+
index = self.index if phase == "trajectory" else len(self.path) - 1
|
| 264 |
+
command = np.r_[self.path[index], self.gripper].astype(np.float32)
|
| 265 |
+
if phase == "trajectory":
|
| 266 |
+
self._motion_step_pending = bool(self.config.motion_replan_steps)
|
| 267 |
+
self.motion_command = float(command[-1])
|
| 268 |
+
self.index += 1
|
| 269 |
+
if self.index == len(self.path):
|
| 270 |
+
self.phase = "path_complete"
|
| 271 |
+
return command, {
|
| 272 |
+
"phase": phase,
|
| 273 |
+
"path_index": index,
|
| 274 |
+
"path_length": len(self.path),
|
| 275 |
+
"reached": reached,
|
| 276 |
+
"position_error_m": position_error,
|
| 277 |
+
"rotation_error_rad": rotation_error,
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
def begin_gripper(self, target, current_qpos, *, source_query=None):
|
| 281 |
+
"""Execute a predicted gripper event while holding the measured arm.
|
| 282 |
+
|
| 283 |
+
No trajectory step or pose correction precedes the command. Feedback and
|
| 284 |
+
timeout semantics are exactly the same as the ordinary post-path phase.
|
| 285 |
+
"""
|
| 286 |
+
self.begin(
|
| 287 |
+
target,
|
| 288 |
+
np.asarray(current_qpos)[None, :7],
|
| 289 |
+
current_qpos,
|
| 290 |
+
source_query=source_query,
|
| 291 |
+
)
|
| 292 |
+
self.phase = "gripper"
|
| 293 |
+
self.gripper = float(self.target[-1].clamp(-1, 1))
|
| 294 |
+
self.completion = GripperCompletion(self.config.gripper_completion)
|
| 295 |
+
|
| 296 |
+
def observe_motion_gripper(self, measured: GripperMeasurement):
|
| 297 |
+
"""Observe one executed path step, without ever interrupting its trajectory.
|
| 298 |
+
|
| 299 |
+
Replay the most recent stability window through the existing predicate.
|
| 300 |
+
A fresh monitor makes a previously complete window revocable when contact
|
| 301 |
+
is lost; it never calls update() on an already ended completion monitor.
|
| 302 |
+
Motion timeout/arrest cannot prematurely stop the remaining arm path.
|
| 303 |
+
"""
|
| 304 |
+
if not self.config.carry_gripper_feedback:
|
| 305 |
+
raise RuntimeError("Motion feedback carry is not enabled")
|
| 306 |
+
if self.phase not in ("trajectory", "path_complete") or (
|
| 307 |
+
self.motion_observed_steps != self.index - 1
|
| 308 |
+
):
|
| 309 |
+
raise RuntimeError("Motion feedback requires one newly executed path step")
|
| 310 |
+
self.motion_observed_steps += 1
|
| 311 |
+
if self.motion_feedback and (
|
| 312 |
+
self.motion_feedback[-1].targets_m != measured.targets_m
|
| 313 |
+
):
|
| 314 |
+
self.motion_feedback.clear()
|
| 315 |
+
self.motion_feedback.append(measured)
|
| 316 |
+
completion_config = self.config.gripper_completion
|
| 317 |
+
monitor = GripperCompletion(
|
| 318 |
+
completion_config.model_copy(
|
| 319 |
+
update={
|
| 320 |
+
"timeout_steps": max(
|
| 321 |
+
completion_config.timeout_steps, completion_config.stable_steps
|
| 322 |
+
),
|
| 323 |
+
"detect_arrest": False,
|
| 324 |
+
}
|
| 325 |
+
)
|
| 326 |
+
)
|
| 327 |
+
for sample in self.motion_feedback:
|
| 328 |
+
row = monitor.update(sample)
|
| 329 |
+
# Compare the actual actuator command values, not gripper sign, measured
|
| 330 |
+
# finger opening, or a tolerance that could erase a real command change.
|
| 331 |
+
requested = float(np.float32(float(self.target[-1].clamp(-1, 1))))
|
| 332 |
+
unchanged = requested == self.motion_command
|
| 333 |
+
carried = (
|
| 334 |
+
self.phase == "path_complete" and unchanged and row["status"] == "complete"
|
| 335 |
+
)
|
| 336 |
+
if carried:
|
| 337 |
+
self._publish_completed_target()
|
| 338 |
+
self.phase = "ready"
|
| 339 |
+
self.gripper_feedback_carried += 1
|
| 340 |
+
return {
|
| 341 |
+
**row,
|
| 342 |
+
"window_samples": len(self.motion_feedback),
|
| 343 |
+
"motion_steps_observed": self.motion_observed_steps,
|
| 344 |
+
"motion_gripper_command": self.motion_command,
|
| 345 |
+
"target_gripper_command": requested,
|
| 346 |
+
"same_gripper_command": unchanged,
|
| 347 |
+
"carried_to_path_completion": carried,
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
def observe_gripper(self, measured: GripperMeasurement):
|
| 351 |
+
"""Consume feedback ONLY after a physical gripper command has executed."""
|
| 352 |
+
if self.phase != "gripper":
|
| 353 |
+
raise RuntimeError("Gripper feedback requires an executed gripper step")
|
| 354 |
+
row = self.completion.update(measured)
|
| 355 |
+
if row["status"] == "complete":
|
| 356 |
+
self._publish_completed_target()
|
| 357 |
+
self.phase = "ready"
|
| 358 |
+
elif row["status"] in ("timeout", "arrested"):
|
| 359 |
+
if row["status"] == "timeout":
|
| 360 |
+
self.gripper_timeouts += 1
|
| 361 |
+
else:
|
| 362 |
+
self.gripper_arrests += 1
|
| 363 |
+
# Resuming records the unmet command and keeps the loop alive; it never
|
| 364 |
+
# claims the gripper reached its target.
|
| 365 |
+
self.phase = (
|
| 366 |
+
"ready"
|
| 367 |
+
if self.config.resume_after_incomplete
|
| 368 |
+
else f"gripper_{row['status']}"
|
| 369 |
+
)
|
| 370 |
+
return row
|
fair-comparison/p3x-liftslow-v1/code/lim/policy.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The identical compact point policy used for all action-coordinate arms."""
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from pydantic import BaseModel, ConfigDict, PositiveInt
|
| 5 |
+
from torch import nn
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class PolicyConfig(BaseModel, frozen=True):
|
| 9 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 10 |
+
width: PositiveInt = 128
|
| 11 |
+
"""Shared point and action feature width."""
|
| 12 |
+
horizon: PositiveInt = 8
|
| 13 |
+
"""Predicted actions; only the first is executed before observing again."""
|
| 14 |
+
state_dim: PositiveInt = 29
|
| 15 |
+
"""Joint position/velocity, TCP pose, observed target centroid and validity."""
|
| 16 |
+
use_velocity: bool = True
|
| 17 |
+
"""Include measured joint velocities; disabled only in the registered shortcut diagnostic."""
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class PointChunkPolicy(nn.Module):
|
| 21 |
+
def __init__(self, config: PolicyConfig):
|
| 22 |
+
super().__init__()
|
| 23 |
+
self.config = config
|
| 24 |
+
w = config.width
|
| 25 |
+
self.point_encoder = nn.Sequential(
|
| 26 |
+
nn.Linear(6, w), nn.ReLU(), nn.Linear(w, w), nn.ReLU(), nn.Linear(w, w)
|
| 27 |
+
)
|
| 28 |
+
self.state_encoder = nn.Sequential(
|
| 29 |
+
nn.Linear(config.state_dim, w), nn.ReLU(), nn.Linear(w, w)
|
| 30 |
+
)
|
| 31 |
+
self.query = nn.Parameter(torch.randn(config.horizon, w) * 0.02)
|
| 32 |
+
self.decoder = nn.TransformerDecoder(
|
| 33 |
+
nn.TransformerDecoderLayer(
|
| 34 |
+
w, 4, 4 * w, dropout=0.0, batch_first=True, norm_first=True
|
| 35 |
+
),
|
| 36 |
+
num_layers=2,
|
| 37 |
+
)
|
| 38 |
+
self.output = nn.Linear(w, 10)
|
| 39 |
+
|
| 40 |
+
def forward(self, points, state):
|
| 41 |
+
if not self.config.use_velocity:
|
| 42 |
+
state = torch.cat(
|
| 43 |
+
[state[:, :9], torch.zeros_like(state[:, 9:18]), state[:, 18:]], dim=-1
|
| 44 |
+
)
|
| 45 |
+
features = self.point_encoder(points)
|
| 46 |
+
# Identical global aggregation for the three coordinate arms.
|
| 47 |
+
memory = torch.stack(
|
| 48 |
+
[features.amax(dim=1), features.mean(dim=1), self.state_encoder(state)],
|
| 49 |
+
dim=1,
|
| 50 |
+
)
|
| 51 |
+
queries = self.query[None].expand(points.shape[0], -1, -1)
|
| 52 |
+
return self.output(self.decoder(queries, memory))
|
fair-comparison/p3x-liftslow-v1/code/lim/policy_video.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Record selected evaluation episodes without changing policy observations."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
import gymnasium as gym
|
| 8 |
+
import imageio.v2 as imageio
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 12 |
+
from pydantic import BaseModel, ConfigDict, PositiveInt
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class PolicyVideoConfig(BaseModel, frozen=True):
|
| 16 |
+
model_config = ConfigDict(
|
| 17 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 18 |
+
)
|
| 19 |
+
env: Any
|
| 20 |
+
"""Raw observation environment, inside the visual preprocessing wrapper."""
|
| 21 |
+
output_dir: Path
|
| 22 |
+
"""Directory for selected episode videos and per-frame measurements."""
|
| 23 |
+
seeds: tuple[int, ...]
|
| 24 |
+
"""Explicit reset seeds to record; unseeded automatic resets are excluded."""
|
| 25 |
+
label: str
|
| 26 |
+
"""Policy name displayed on the video."""
|
| 27 |
+
max_steps: PositiveInt | None = None
|
| 28 |
+
"""Optional episode budget for display only; the environment owns truncation."""
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def as_array(value):
|
| 32 |
+
if isinstance(value, torch.Tensor):
|
| 33 |
+
return value.detach().cpu().numpy().copy()
|
| 34 |
+
return np.asarray(value).copy()
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class PolicyVideo(gym.Wrapper):
|
| 38 |
+
def __init__(self, config: PolicyVideoConfig):
|
| 39 |
+
super().__init__(config.env)
|
| 40 |
+
self.config = config
|
| 41 |
+
self.writer = None
|
| 42 |
+
self.rows = []
|
| 43 |
+
self.seed = None
|
| 44 |
+
self.step_index = 0
|
| 45 |
+
self.success_once = False
|
| 46 |
+
font_path = Path("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf")
|
| 47 |
+
self.font = (
|
| 48 |
+
ImageFont.truetype(str(font_path), 16)
|
| 49 |
+
if font_path.exists()
|
| 50 |
+
else ImageFont.load_default()
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
def reset(self, **kwargs):
|
| 54 |
+
self.finish(complete=False)
|
| 55 |
+
obs, info = self.env.reset(**kwargs)
|
| 56 |
+
self.seed = kwargs.get("seed")
|
| 57 |
+
self.step_index = 0
|
| 58 |
+
self.success_once = False
|
| 59 |
+
self.rows = []
|
| 60 |
+
if self.seed in self.config.seeds:
|
| 61 |
+
self.config.output_dir.mkdir(parents=True, exist_ok=True)
|
| 62 |
+
path = self.config.output_dir / f"seed{self.seed}.mp4"
|
| 63 |
+
if path.exists():
|
| 64 |
+
raise FileExistsError(path)
|
| 65 |
+
self.writer = imageio.get_writer(
|
| 66 |
+
str(path),
|
| 67 |
+
fps=self.unwrapped.control_freq,
|
| 68 |
+
codec="libx264",
|
| 69 |
+
quality=8,
|
| 70 |
+
macro_block_size=1,
|
| 71 |
+
ffmpeg_params=["-pix_fmt", "yuv420p", "-movflags", "+faststart"],
|
| 72 |
+
)
|
| 73 |
+
self.capture(obs, info, action=None)
|
| 74 |
+
return obs, info
|
| 75 |
+
|
| 76 |
+
def step(self, action):
|
| 77 |
+
obs, reward, terminated, truncated, info = self.env.step(action)
|
| 78 |
+
self.step_index += 1
|
| 79 |
+
if self.writer is not None:
|
| 80 |
+
self.capture(obs, info, action=action)
|
| 81 |
+
if bool(as_array(truncated).item()):
|
| 82 |
+
self.finish(complete=True)
|
| 83 |
+
return obs, reward, terminated, truncated, info
|
| 84 |
+
|
| 85 |
+
def capture(self, obs, info, action):
|
| 86 |
+
# Copy policy RGB before rendering the independent observer camera.
|
| 87 |
+
cameras = {
|
| 88 |
+
name: as_array(data["rgb"])[0] for name, data in obs["sensor_data"].items()
|
| 89 |
+
}
|
| 90 |
+
if set(cameras) != {"base_camera", "hand_camera"}:
|
| 91 |
+
raise ValueError("This video layout requires base and hand RGB cameras")
|
| 92 |
+
success = bool(as_array(info.get("success", False)).item())
|
| 93 |
+
# As in CPUGymWrapper, success_once counts completed actions, not reset.
|
| 94 |
+
if self.step_index:
|
| 95 |
+
self.success_once |= success
|
| 96 |
+
fps = self.unwrapped.control_freq
|
| 97 |
+
row = {
|
| 98 |
+
"step": self.step_index,
|
| 99 |
+
"sim_time_s": self.step_index / fps,
|
| 100 |
+
"success": success,
|
| 101 |
+
"success_once": self.success_once,
|
| 102 |
+
"action": None if action is None else as_array(action).tolist(),
|
| 103 |
+
"qpos": as_array(obs["agent"]["qpos"]).tolist(),
|
| 104 |
+
"tcp_pose": as_array(obs["extra"]["tcp_pose"]).tolist(),
|
| 105 |
+
"cubeA_pose": as_array(self.unwrapped.cubeA.pose.raw_pose).tolist(),
|
| 106 |
+
"cubeB_pose": as_array(self.unwrapped.cubeB.pose.raw_pose).tolist(),
|
| 107 |
+
}
|
| 108 |
+
for key in ("audit_release_once", "audit_release_at_end"):
|
| 109 |
+
row[key] = bool(as_array(info.get(key, False)).item())
|
| 110 |
+
self.rows.append(row)
|
| 111 |
+
observer = as_array(self.unwrapped.render_rgb_array())
|
| 112 |
+
if observer.ndim == 4:
|
| 113 |
+
observer = observer[0]
|
| 114 |
+
canvas = Image.new("RGB", (768, 592), (20, 23, 28))
|
| 115 |
+
canvas.paste(Image.fromarray(observer).resize((512, 512)), (0, 64))
|
| 116 |
+
for index, name in enumerate(("base_camera", "hand_camera")):
|
| 117 |
+
camera = Image.fromarray(cameras[name]).resize(
|
| 118 |
+
(256, 256), Image.Resampling.NEAREST
|
| 119 |
+
)
|
| 120 |
+
canvas.paste(camera, (512, 64 + index * 256))
|
| 121 |
+
draw = ImageDraw.Draw(canvas)
|
| 122 |
+
step_label = str(self.step_index)
|
| 123 |
+
if self.config.max_steps is not None:
|
| 124 |
+
step_label += f"/{self.config.max_steps}"
|
| 125 |
+
draw.text(
|
| 126 |
+
(8, 5),
|
| 127 |
+
f"{self.config.label} | seed {self.seed} | step {step_label}"
|
| 128 |
+
f" | t={self.step_index / fps:.2f}s",
|
| 129 |
+
font=self.font,
|
| 130 |
+
fill="white",
|
| 131 |
+
)
|
| 132 |
+
draw.text(
|
| 133 |
+
(8, 27),
|
| 134 |
+
f"Official success now: {int(success)} | success once: {int(self.success_once)}",
|
| 135 |
+
font=self.font,
|
| 136 |
+
fill=(100, 235, 140) if success else (255, 200, 120),
|
| 137 |
+
)
|
| 138 |
+
for x, y, text in (
|
| 139 |
+
(8, 68, "Observer view (not a policy input)"),
|
| 140 |
+
(516, 68, "Policy: base RGB 128x128"),
|
| 141 |
+
(516, 324, "Policy: wrist RGB 128x128"),
|
| 142 |
+
):
|
| 143 |
+
box = draw.textbbox((x, y), text, font=self.font)
|
| 144 |
+
draw.rectangle(box, fill=(20, 23, 28))
|
| 145 |
+
draw.text((x, y), text, font=self.font, fill="white")
|
| 146 |
+
self.writer.append_data(np.asarray(canvas))
|
| 147 |
+
|
| 148 |
+
def finish(self, complete):
|
| 149 |
+
if self.writer is None:
|
| 150 |
+
return
|
| 151 |
+
self.writer.close()
|
| 152 |
+
self.writer = None
|
| 153 |
+
stem = self.config.output_dir / f"seed{self.seed}"
|
| 154 |
+
stem.with_suffix(".jsonl").write_text(
|
| 155 |
+
"".join(json.dumps(row) + "\n" for row in self.rows)
|
| 156 |
+
)
|
| 157 |
+
stem.with_suffix(".json").write_text(
|
| 158 |
+
json.dumps(
|
| 159 |
+
{
|
| 160 |
+
"seed": self.seed,
|
| 161 |
+
"policy": self.config.label,
|
| 162 |
+
"complete": complete,
|
| 163 |
+
"steps": self.step_index,
|
| 164 |
+
"max_steps": self.config.max_steps,
|
| 165 |
+
"frames": len(self.rows),
|
| 166 |
+
"fps": self.unwrapped.control_freq,
|
| 167 |
+
"success_once": self.success_once,
|
| 168 |
+
"success_at_end": self.rows[-1]["success"],
|
| 169 |
+
"first_success_step": next(
|
| 170 |
+
(r["step"] for r in self.rows if r["step"] and r["success"]),
|
| 171 |
+
None,
|
| 172 |
+
),
|
| 173 |
+
"scope": "New recorded rollout; full initial and terminal frames. "
|
| 174 |
+
"Left: observer only. Right: raw policy RGB enlarged 2x.",
|
| 175 |
+
},
|
| 176 |
+
indent=2,
|
| 177 |
+
)
|
| 178 |
+
+ "\n"
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
def close(self):
|
| 182 |
+
self.finish(complete=False)
|
| 183 |
+
return self.env.close()
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def policy_video_wrapper(env, output_dir, seeds, label):
|
| 187 |
+
return PolicyVideo(
|
| 188 |
+
PolicyVideoConfig(env=env, output_dir=output_dir, seeds=seeds, label=label)
|
| 189 |
+
)
|
fair-comparison/p3x-liftslow-v1/code/lim/profile.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Simulator-free, batch-one RGB-D-to-action deployment measurement."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pynvml
|
| 10 |
+
import torch
|
| 11 |
+
from pydantic import BaseModel, ConfigDict, PositiveInt
|
| 12 |
+
from pydantic_settings import CliApp
|
| 13 |
+
|
| 14 |
+
from lim.action import decode_action
|
| 15 |
+
from lim.observations import ObservationConfig, encode_observation
|
| 16 |
+
from lim.policy import PointChunkPolicy, PolicyConfig
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class ProfileConfig(BaseModel, frozen=True):
|
| 20 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 21 |
+
checkpoint: Path
|
| 22 |
+
"""A trained fixed-final-update policy checkpoint."""
|
| 23 |
+
observations: Path
|
| 24 |
+
"""Recorded CPU RGB-D arrays with camera calibration and measured proprioception."""
|
| 25 |
+
output_dir: Path
|
| 26 |
+
"""New directory for full per-iteration measurements."""
|
| 27 |
+
iterations: PositiveInt = 500
|
| 28 |
+
"""Measured fresh-observation inference iterations after warmup."""
|
| 29 |
+
warmup: PositiveInt = 30
|
| 30 |
+
"""Unmeasured warmup iterations; cold first call is separately recorded."""
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def process_gpu_memory():
|
| 34 |
+
total = 0
|
| 35 |
+
for index in range(pynvml.nvmlDeviceGetCount()):
|
| 36 |
+
handle = pynvml.nvmlDeviceGetHandleByIndex(index)
|
| 37 |
+
for process in pynvml.nvmlDeviceGetComputeRunningProcesses(handle):
|
| 38 |
+
if process.pid == os.getpid():
|
| 39 |
+
total += process.usedGpuMemory
|
| 40 |
+
return total
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def run_profile(config: ProfileConfig):
|
| 44 |
+
config.output_dir.mkdir(parents=True, exist_ok=False)
|
| 45 |
+
torch.set_num_threads(4)
|
| 46 |
+
checkpoint = torch.load(config.checkpoint, map_location="cpu", weights_only=False)
|
| 47 |
+
observations = torch.load(
|
| 48 |
+
config.observations, map_location="cpu", weights_only=False
|
| 49 |
+
)
|
| 50 |
+
model = PointChunkPolicy(PolicyConfig(**checkpoint["policy_config"])).cuda().eval()
|
| 51 |
+
model.load_state_dict(checkpoint["state_dict"])
|
| 52 |
+
pynvml.nvmlInit()
|
| 53 |
+
samples = []
|
| 54 |
+
peak_process_bytes = 0
|
| 55 |
+
cold_ms = None
|
| 56 |
+
with torch.inference_mode():
|
| 57 |
+
for index in range(config.warmup + config.iterations):
|
| 58 |
+
obs = observations[index % len(observations)]
|
| 59 |
+
torch.cuda.synchronize()
|
| 60 |
+
start = time.perf_counter()
|
| 61 |
+
encoded = encode_observation(obs, ObservationConfig())
|
| 62 |
+
prepared = time.perf_counter()
|
| 63 |
+
points = torch.as_tensor(encoded["points"][None], device="cuda")
|
| 64 |
+
state = torch.as_tensor(encoded["state"][None], device="cuda")
|
| 65 |
+
torch.cuda.synchronize()
|
| 66 |
+
transferred = time.perf_counter()
|
| 67 |
+
predicted = model(points, state)[0, 0].cpu().numpy()
|
| 68 |
+
inferred = time.perf_counter()
|
| 69 |
+
action = decode_action(
|
| 70 |
+
predicted, encoded["tcp"], encoded["target"], checkpoint["frame"]
|
| 71 |
+
)
|
| 72 |
+
torch.cuda.synchronize()
|
| 73 |
+
finished = time.perf_counter()
|
| 74 |
+
if not np.isfinite(action).all():
|
| 75 |
+
raise FloatingPointError("Nonfinite deployment action")
|
| 76 |
+
row = {
|
| 77 |
+
"preprocess_ms": (prepared - start) * 1000,
|
| 78 |
+
"transfer_ms": (transferred - prepared) * 1000,
|
| 79 |
+
"model_ms": (inferred - transferred) * 1000,
|
| 80 |
+
"action_ms": (finished - inferred) * 1000,
|
| 81 |
+
"total_ms": (finished - start) * 1000,
|
| 82 |
+
}
|
| 83 |
+
if index == 0:
|
| 84 |
+
cold_ms = row["total_ms"]
|
| 85 |
+
if index >= config.warmup:
|
| 86 |
+
samples.append(row)
|
| 87 |
+
peak_process_bytes = max(peak_process_bytes, process_gpu_memory())
|
| 88 |
+
fields = samples[0]
|
| 89 |
+
percentiles = {
|
| 90 |
+
key: {
|
| 91 |
+
str(p): float(np.percentile([row[key] for row in samples], p))
|
| 92 |
+
for p in [50, 95, 99]
|
| 93 |
+
}
|
| 94 |
+
for key in fields
|
| 95 |
+
}
|
| 96 |
+
result = {
|
| 97 |
+
"config": config.model_dump(mode="json"),
|
| 98 |
+
"gpu": torch.cuda.get_device_name(),
|
| 99 |
+
"torch": torch.__version__,
|
| 100 |
+
"parameters": sum(p.numel() for p in model.parameters()),
|
| 101 |
+
"observations": len(observations),
|
| 102 |
+
"cold_ms": cold_ms,
|
| 103 |
+
"latency_ms": percentiles,
|
| 104 |
+
"peak_allocated_bytes": torch.cuda.max_memory_allocated(),
|
| 105 |
+
"peak_reserved_bytes": torch.cuda.max_memory_reserved(),
|
| 106 |
+
"peak_process_bytes": peak_process_bytes,
|
| 107 |
+
"median_hz": 1000 / percentiles["total_ms"]["50"],
|
| 108 |
+
"p95_budget_hz": 1000 / percentiles["total_ms"]["95"],
|
| 109 |
+
"meets_7GB": 0 < peak_process_bytes <= 7_000_000_000,
|
| 110 |
+
"meets_20Hz_p95": percentiles["total_ms"]["95"] <= 50,
|
| 111 |
+
"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",
|
| 112 |
+
}
|
| 113 |
+
(config.output_dir / "result.json").write_text(json.dumps(result, indent=2))
|
| 114 |
+
with (config.output_dir / "iterations.jsonl").open("w") as out:
|
| 115 |
+
for row in samples:
|
| 116 |
+
out.write(json.dumps(row) + "\n")
|
| 117 |
+
print("PROFILE_COMPLETE", json.dumps(result), flush=True)
|
| 118 |
+
pynvml.nvmlShutdown()
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
if __name__ == "__main__":
|
| 122 |
+
run_profile(CliApp.run(ProfileConfig))
|
fair-comparison/p3x-liftslow-v1/code/lim/reference_act.py
ADDED
|
@@ -0,0 +1,855 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Load the pinned official ACT and audit its unmodified evaluation path."""
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import importlib.util
|
| 5 |
+
import io
|
| 6 |
+
import json
|
| 7 |
+
import math
|
| 8 |
+
import sys
|
| 9 |
+
import time
|
| 10 |
+
from functools import partial
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from types import SimpleNamespace
|
| 13 |
+
from typing import Any, Literal
|
| 14 |
+
|
| 15 |
+
import gymnasium as gym
|
| 16 |
+
import numpy as np
|
| 17 |
+
import pynvml
|
| 18 |
+
import torch
|
| 19 |
+
from pydantic import BaseModel, ConfigDict, PositiveInt, model_validator
|
| 20 |
+
from pydantic_settings import CliApp
|
| 21 |
+
|
| 22 |
+
from lim.act_policy import ACTPolicyConfig, build_policy, evaluation_transport
|
| 23 |
+
from lim.action_encoding import encoded_dimension, sixd_to_controller
|
| 24 |
+
from lim.chunk_coordinates import pose_target_contract
|
| 25 |
+
from lim.gripper_execution import GripperExecutionConfig
|
| 26 |
+
from lim.normalization import checked_statistics
|
| 27 |
+
from lim.profile import process_gpu_memory
|
| 28 |
+
from lim.tasks import TASKS
|
| 29 |
+
|
| 30 |
+
PROFILE_SCOPE = (
|
| 31 |
+
"batch1 raw CPU RGB/proprioception through official resize, transfers, normalization, "
|
| 32 |
+
"ResNet, configured policy and native temporal aggregation (with target conversion "
|
| 33 |
+
"for chunk_relative); simulator-free replay of saved raw "
|
| 34 |
+
"inputs; excludes camera acquisition/transport and low-level physical control; "
|
| 35 |
+
"NVML sampled after each iteration"
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
ACTControlMode = Literal["pd_ee_delta_pos", "pd_ee_delta_pose"]
|
| 39 |
+
ACTION_DIMENSIONS = {"pd_ee_delta_pos": 4, "pd_ee_delta_pose": 7}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def load_checkpoint(path):
|
| 43 |
+
raw = path.read_bytes()
|
| 44 |
+
checkpoint = torch.load(io.BytesIO(raw), map_location="cpu", weights_only=False)
|
| 45 |
+
if "ema_agent" not in checkpoint or checkpoint["norm_stats"] is not None:
|
| 46 |
+
raise ValueError("Expected official delta-control EMA checkpoint")
|
| 47 |
+
return checkpoint, {
|
| 48 |
+
"checkpoint_sha256": hashlib.sha256(raw).hexdigest(),
|
| 49 |
+
"loaded_weight_key": "ema_agent",
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def check_policy_checkpoint(checkpoint, config):
|
| 54 |
+
declared = ACTPolicyConfig.model_validate(checkpoint.get("policy", {}))
|
| 55 |
+
if (
|
| 56 |
+
declared != config.policy
|
| 57 |
+
or checkpoint.get("num_queries", 30) != config.num_queries
|
| 58 |
+
or checkpoint.get("control_mode", "pd_ee_delta_pos") != config.control_mode
|
| 59 |
+
):
|
| 60 |
+
raise ValueError(
|
| 61 |
+
"Checkpoint policy, control mode or prediction horizon differs from evaluation"
|
| 62 |
+
)
|
| 63 |
+
if "ema_agent" in checkpoint:
|
| 64 |
+
# Metadata alone must not relabel a Q30 network as Q1. Wrappers add
|
| 65 |
+
# prefixes, but every supported ACT variant owns one query embedding.
|
| 66 |
+
weights = checkpoint["ema_agent"]
|
| 67 |
+
queries = [
|
| 68 |
+
value
|
| 69 |
+
for name, value in weights.items()
|
| 70 |
+
if name.endswith("query_embed.weight")
|
| 71 |
+
]
|
| 72 |
+
if len(queries) != 1 or tuple(queries[0].shape) != (
|
| 73 |
+
config.num_queries,
|
| 74 |
+
config.architecture.hidden_dim,
|
| 75 |
+
):
|
| 76 |
+
raise ValueError(
|
| 77 |
+
"Checkpoint query embedding disagrees with prediction horizon"
|
| 78 |
+
)
|
| 79 |
+
for name, value in weights.items():
|
| 80 |
+
if name.endswith("pos_table") and tuple(value.shape) != (
|
| 81 |
+
1,
|
| 82 |
+
config.num_queries + 2,
|
| 83 |
+
config.architecture.hidden_dim,
|
| 84 |
+
):
|
| 85 |
+
raise ValueError(
|
| 86 |
+
"Checkpoint posterior position table disagrees with prediction horizon"
|
| 87 |
+
)
|
| 88 |
+
checked_statistics(
|
| 89 |
+
checkpoint.get("normalization"),
|
| 90 |
+
declared.normalization,
|
| 91 |
+
declared.action_encoding,
|
| 92 |
+
)
|
| 93 |
+
if declared.method == "chunk_relative" and declared.action_encoding == "rotation6d":
|
| 94 |
+
# The contract must match the checkpoint's own label frame, so a model is
|
| 95 |
+
# never evaluated in a frame it was not trained in.
|
| 96 |
+
expected = pose_target_contract(
|
| 97 |
+
declared.chunk_anchor,
|
| 98 |
+
declared.chunk_pose_supervision,
|
| 99 |
+
declared.chunk_gripper_supervision,
|
| 100 |
+
declared.chunk_padding,
|
| 101 |
+
declared.chunk_normalization_population,
|
| 102 |
+
declared.chunk_label_offset,
|
| 103 |
+
declared.chunk_waypoint_threshold_m,
|
| 104 |
+
)
|
| 105 |
+
if checkpoint.get("action_target_contract") != expected:
|
| 106 |
+
raise ValueError(
|
| 107 |
+
"Checkpoint contract does not match its anchor, pose or gripper supervision"
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def source_provenance(config):
|
| 112 |
+
declared = json.loads(Path("round2/reference-source.json").read_text())
|
| 113 |
+
source = Path("third_party/ManiSkill/examples/baselines/act/train_rgbd.py")
|
| 114 |
+
if config.source.resolve() != source.resolve():
|
| 115 |
+
raise ValueError("Reference source must match the pinned official loader")
|
| 116 |
+
actual = {
|
| 117 |
+
p: hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in declared["sha256"]
|
| 118 |
+
}
|
| 119 |
+
if actual != declared["sha256"]:
|
| 120 |
+
raise ValueError("Official source differs from audited hashes")
|
| 121 |
+
return {"official_source_sha256": actual, "reference_commit": declared["commit"]}
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class ACTArchitectureConfig(BaseModel, frozen=True):
|
| 125 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 126 |
+
hidden_dim: PositiveInt = 256
|
| 127 |
+
"""Official ACT transformer hidden width."""
|
| 128 |
+
dim_feedforward: PositiveInt = 512
|
| 129 |
+
"""Official transformer feed-forward width."""
|
| 130 |
+
enc_layers: PositiveInt = 2
|
| 131 |
+
"""Encoder layers in the official architecture."""
|
| 132 |
+
dec_layers: PositiveInt = 4
|
| 133 |
+
"""Decoder layers in the official architecture."""
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class ReferenceConfig(BaseModel, frozen=True):
|
| 137 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 138 |
+
mode: Literal["witness", "evaluate", "profile"] = "witness"
|
| 139 |
+
"""Environment witness, fixed-checkpoint evaluation, or simulator-free profile."""
|
| 140 |
+
source: Path = Path("third_party/ManiSkill/examples/baselines/act/train_rgbd.py")
|
| 141 |
+
"""Pinned, unmodified official implementation containing Agent and preprocessing."""
|
| 142 |
+
checkpoint: Path | None = None
|
| 143 |
+
"""Official final checkpoint; evaluation and profile load its ema_agent entry."""
|
| 144 |
+
output_dir: Path = Path("artifacts/round2/witness")
|
| 145 |
+
"""New output directory, with raw episode or timing records."""
|
| 146 |
+
episodes: PositiveInt = 100
|
| 147 |
+
"""Fixed number of complete evaluation episodes."""
|
| 148 |
+
num_envs: PositiveInt = 10
|
| 149 |
+
"""CPU physics vector environments; episodes must be divisible by this count."""
|
| 150 |
+
seed_start: int = 50000
|
| 151 |
+
"""Explicit, disjoint per-episode seed block."""
|
| 152 |
+
observations: Path | None = None
|
| 153 |
+
"""Folder with saved raw RGB/proprioceptive inputs for profiling."""
|
| 154 |
+
iterations: PositiveInt = 500
|
| 155 |
+
"""Measured warmed profile calls; 30 additional warmup calls precede these."""
|
| 156 |
+
demonstration_metadata: Path = Path(
|
| 157 |
+
"data/official-demos/StackCube-v1/motionplanning/trajectory.rgb.pd_ee_delta_pos.physx_cpu.json"
|
| 158 |
+
)
|
| 159 |
+
"""Converted demonstration metadata supplying the evaluation sensor configuration."""
|
| 160 |
+
architecture: ACTArchitectureConfig = ACTArchitectureConfig()
|
| 161 |
+
"""Explicit trained model shape; defaults preserve the Round2 small reference."""
|
| 162 |
+
policy: ACTPolicyConfig = ACTPolicyConfig()
|
| 163 |
+
"""Trained architecture/input variant; must match checkpoint metadata."""
|
| 164 |
+
num_queries: PositiveInt = 30
|
| 165 |
+
"""Actual trained decoder query count, including one for a single-target model;
|
| 166 |
+
native evaluation queries fresh observations each control step."""
|
| 167 |
+
video_seeds: tuple[int, ...] = ()
|
| 168 |
+
"""Optional explicit scene seeds to record, including raw RGB and observer view."""
|
| 169 |
+
keypose_trace: bool = False
|
| 170 |
+
"""Record read-only target, TCP error, and arrival-gate diagnostics for keyposes."""
|
| 171 |
+
control_mode: ACTControlMode = "pd_ee_delta_pos"
|
| 172 |
+
"""Controller shared by the trained action labels and online environment."""
|
| 173 |
+
gripper_execution: GripperExecutionConfig = GripperExecutionConfig()
|
| 174 |
+
"""Optional inference-only gripper intervention and chunk-level diagnostics."""
|
| 175 |
+
|
| 176 |
+
@model_validator(mode="after")
|
| 177 |
+
def validate_execution(self):
|
| 178 |
+
if self.keypose_trace and (
|
| 179 |
+
self.mode != "evaluate" or self.policy.keypose is None
|
| 180 |
+
):
|
| 181 |
+
raise ValueError("Keypose diagnostics require keypose evaluation")
|
| 182 |
+
if self.policy.keypose is not None and (
|
| 183 |
+
self.mode != "evaluate" or self.control_mode != "pd_ee_delta_pose"
|
| 184 |
+
):
|
| 185 |
+
raise ValueError(
|
| 186 |
+
"Keypose transport currently supports pose evaluation only"
|
| 187 |
+
)
|
| 188 |
+
if self.gripper_execution.active and (
|
| 189 |
+
self.mode != "evaluate"
|
| 190 |
+
or self.control_mode != "pd_ee_delta_pose"
|
| 191 |
+
or self.policy.method != "cvae"
|
| 192 |
+
or self.policy.action_encoding != "rotation6d"
|
| 193 |
+
or self.policy.keypose is not None
|
| 194 |
+
):
|
| 195 |
+
raise ValueError(
|
| 196 |
+
"Gripper execution experiments require CVAE pose6D evaluation"
|
| 197 |
+
)
|
| 198 |
+
return self
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def load_official(config):
|
| 202 |
+
source_provenance(config)
|
| 203 |
+
# The vendor's act/ is a namespace directory; its setup.find_packages()
|
| 204 |
+
# does not install it. Match direct train_rgbd.py execution's import root.
|
| 205 |
+
source_root = str(config.source.resolve().parent)
|
| 206 |
+
if source_root not in sys.path:
|
| 207 |
+
sys.path.insert(0, source_root)
|
| 208 |
+
# Use the file's importable name so forkserver CPU workers can reconstruct
|
| 209 |
+
# the official observation-wrapper class from the inherited sys.path.
|
| 210 |
+
spec = importlib.util.spec_from_file_location(config.source.stem, config.source)
|
| 211 |
+
module = importlib.util.module_from_spec(spec)
|
| 212 |
+
sys.modules[spec.name] = module
|
| 213 |
+
spec.loader.exec_module(module)
|
| 214 |
+
# Agent and Dataset reference the script's module-global args at runtime.
|
| 215 |
+
module.args = module.Args(
|
| 216 |
+
**config.architecture.model_dump(),
|
| 217 |
+
include_depth=False,
|
| 218 |
+
env_id="StackCube-v1",
|
| 219 |
+
control_mode=config.control_mode,
|
| 220 |
+
max_episode_steps=200,
|
| 221 |
+
sim_backend="physx_cpu",
|
| 222 |
+
temporal_agg=True,
|
| 223 |
+
num_queries=config.num_queries,
|
| 224 |
+
)
|
| 225 |
+
return module
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
class AuditConfig(BaseModel, frozen=True):
|
| 229 |
+
model_config = ConfigDict(
|
| 230 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 231 |
+
)
|
| 232 |
+
env: Any
|
| 233 |
+
"""Official environment, before visual preprocessing and CPU metric wrappers."""
|
| 234 |
+
snapshots: Path
|
| 235 |
+
"""Raw policy-input snapshots, saved only from the first vector slot."""
|
| 236 |
+
stride: int
|
| 237 |
+
"""Number of vector slots for deterministic snapshot ownership."""
|
| 238 |
+
seed_start: int
|
| 239 |
+
"""First held-out seed, used only for snapshot ownership."""
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
class ReleasedSupportAudit(gym.Wrapper):
|
| 243 |
+
def __init__(self, config: AuditConfig):
|
| 244 |
+
super().__init__(config.env)
|
| 245 |
+
self.config = config
|
| 246 |
+
self.streak = 0
|
| 247 |
+
self.once = False
|
| 248 |
+
self.explicit_seed = None
|
| 249 |
+
self.step_index = 0
|
| 250 |
+
|
| 251 |
+
def snapshot(self, obs):
|
| 252 |
+
if (
|
| 253 |
+
self.explicit_seed is None
|
| 254 |
+
or (self.explicit_seed - self.config.seed_start) % self.config.stride
|
| 255 |
+
):
|
| 256 |
+
return
|
| 257 |
+
if self.step_index not in (0, 10, 30, 70, 120, 199):
|
| 258 |
+
return
|
| 259 |
+
folder = self.config.snapshots
|
| 260 |
+
folder.mkdir(parents=True, exist_ok=True)
|
| 261 |
+
if len(list(folder.glob("*.pt"))) >= 12:
|
| 262 |
+
return
|
| 263 |
+
|
| 264 |
+
def cpu(value):
|
| 265 |
+
if isinstance(value, dict):
|
| 266 |
+
return {k: cpu(v) for k, v in value.items()}
|
| 267 |
+
return value.detach().cpu().clone() if torch.is_tensor(value) else value
|
| 268 |
+
|
| 269 |
+
torch.save(
|
| 270 |
+
cpu(obs), folder / f"seed{self.explicit_seed}_step{self.step_index}.pt"
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
def reset(self, **kwargs):
|
| 274 |
+
obs, info = self.env.reset(**kwargs)
|
| 275 |
+
self.streak, self.once, self.step_index = 0, False, 0
|
| 276 |
+
self.explicit_seed = kwargs.get("seed")
|
| 277 |
+
self.snapshot(obs)
|
| 278 |
+
return obs, info
|
| 279 |
+
|
| 280 |
+
def step(self, action):
|
| 281 |
+
obs, reward, terminated, truncated, info = self.env.step(action)
|
| 282 |
+
base = self.env.unwrapped
|
| 283 |
+
if base.spec.id != "StackCube-v1":
|
| 284 |
+
# The released-support audit is StackCube's cube-on-cube rule; other
|
| 285 |
+
# tasks only need the observation snapshots.
|
| 286 |
+
self.step_index += 1
|
| 287 |
+
self.snapshot(obs)
|
| 288 |
+
return obs, reward, terminated, truncated, info
|
| 289 |
+
source, target = base.cubeA, base.cubeB
|
| 290 |
+
support_force = base.scene.get_pairwise_contact_forces(source, target)
|
| 291 |
+
contact = 0.0
|
| 292 |
+
for link in base.agent.robot.get_links():
|
| 293 |
+
contact = max(
|
| 294 |
+
contact,
|
| 295 |
+
float(
|
| 296 |
+
torch.linalg.norm(
|
| 297 |
+
base.scene.get_pairwise_contact_forces(source, link), dim=-1
|
| 298 |
+
).item()
|
| 299 |
+
),
|
| 300 |
+
)
|
| 301 |
+
strict = (
|
| 302 |
+
abs(float(support_force[0, 2])) > 0.1
|
| 303 |
+
and float((source.pose.p - target.pose.p)[0, 2]) > 0.025
|
| 304 |
+
and bool(source.is_static(lin_thresh=1e-2, ang_thresh=0.5).item())
|
| 305 |
+
and contact < 0.01
|
| 306 |
+
and bool((base.agent.robot.get_qpos()[0, -2:] >= 0.035).all())
|
| 307 |
+
)
|
| 308 |
+
self.streak = self.streak + 1 if strict else 0
|
| 309 |
+
self.once = self.once or self.streak >= 20
|
| 310 |
+
info["audit_release_once"] = self.once
|
| 311 |
+
info["audit_release_at_end"] = self.streak >= 20
|
| 312 |
+
info["audit_robot_contact"] = contact
|
| 313 |
+
self.step_index += 1
|
| 314 |
+
self.snapshot(obs)
|
| 315 |
+
return obs, reward, terminated, truncated, info
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def audit_wrapper(env, snapshots, stride, seed_start):
|
| 319 |
+
return ReleasedSupportAudit(
|
| 320 |
+
AuditConfig(env=env, snapshots=snapshots, stride=stride, seed_start=seed_start)
|
| 321 |
+
)
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class RecorderConfig(BaseModel, frozen=True):
|
| 325 |
+
model_config = ConfigDict(
|
| 326 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 327 |
+
)
|
| 328 |
+
env: Any
|
| 329 |
+
"""Official CPU vector environment with SAME_STEP autoreset semantics."""
|
| 330 |
+
run: ReferenceConfig
|
| 331 |
+
"""Declared seed block and output destination."""
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
class SeededRecorder:
|
| 335 |
+
"""Record official metrics, explicitly seed each new batch, preserve ACT evaluation."""
|
| 336 |
+
|
| 337 |
+
def __init__(self, config: RecorderConfig):
|
| 338 |
+
self.config = config
|
| 339 |
+
self.rows = []
|
| 340 |
+
self.calls = 0
|
| 341 |
+
self.seed_batch = 0
|
| 342 |
+
self.model_queries = 0
|
| 343 |
+
self.previous_model_queries = 0
|
| 344 |
+
self.batch_steps = 0
|
| 345 |
+
|
| 346 |
+
def count_inference(self, module, inputs):
|
| 347 |
+
self.model_queries += 1
|
| 348 |
+
|
| 349 |
+
def __getattr__(self, name):
|
| 350 |
+
return getattr(self.config.env, name)
|
| 351 |
+
|
| 352 |
+
def reset(self):
|
| 353 |
+
start = self.config.run.seed_start + self.seed_batch * self.num_envs
|
| 354 |
+
return self.config.env.reset(seed=list(range(start, start + self.num_envs)))
|
| 355 |
+
|
| 356 |
+
def step(self, action):
|
| 357 |
+
obs, reward, terminated, truncated, info = self.config.env.step(action)
|
| 358 |
+
self.calls += 1
|
| 359 |
+
self.batch_steps += 1
|
| 360 |
+
if truncated.any():
|
| 361 |
+
assert truncated.all()
|
| 362 |
+
for slot, final in enumerate(info["final_info"]):
|
| 363 |
+
row = {k: np.asarray(v).item() for k, v in final["episode"].items()}
|
| 364 |
+
row.update(
|
| 365 |
+
seed=self.config.run.seed_start
|
| 366 |
+
+ self.seed_batch * self.num_envs
|
| 367 |
+
+ slot,
|
| 368 |
+
audit_release_once=bool(final["audit_release_once"]),
|
| 369 |
+
audit_release_at_end=bool(final["audit_release_at_end"]),
|
| 370 |
+
steps=self.batch_steps,
|
| 371 |
+
policy_calls=self.model_queries - self.previous_model_queries,
|
| 372 |
+
)
|
| 373 |
+
self.rows.append(row)
|
| 374 |
+
with (self.config.run.output_dir / "episodes.jsonl").open("a") as f:
|
| 375 |
+
f.write(json.dumps(row) + "\n")
|
| 376 |
+
print(
|
| 377 |
+
json.dumps(
|
| 378 |
+
{
|
| 379 |
+
"completed": len(self.rows),
|
| 380 |
+
"success_once": sum(r["success_once"] for r in self.rows),
|
| 381 |
+
"success_at_end": sum(r["success_at_end"] for r in self.rows),
|
| 382 |
+
}
|
| 383 |
+
),
|
| 384 |
+
flush=True,
|
| 385 |
+
)
|
| 386 |
+
self.seed_batch += 1
|
| 387 |
+
self.previous_model_queries = self.model_queries
|
| 388 |
+
self.batch_steps = 0
|
| 389 |
+
if len(self.rows) < self.config.run.episodes:
|
| 390 |
+
# SAME_STEP already performed an unseeded reset. Replace that
|
| 391 |
+
# initial state before any policy action, keeping final_info intact.
|
| 392 |
+
obs, _ = self.reset()
|
| 393 |
+
return obs, reward, terminated, truncated, info
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def create_env(module, config, count):
|
| 397 |
+
metadata = json.loads(config.demonstration_metadata.read_text())
|
| 398 |
+
info = metadata["env_info"]
|
| 399 |
+
if info["env_id"] not in TASKS:
|
| 400 |
+
raise ValueError("Demonstration metadata task mismatch")
|
| 401 |
+
sensor_configs = info["env_kwargs"]["sensor_configs"]
|
| 402 |
+
if info["env_kwargs"].get("control_mode") != config.control_mode:
|
| 403 |
+
raise ValueError("Demonstration metadata and evaluation controller differ")
|
| 404 |
+
if config.policy.method == "chunk_relative" and config.control_mode != (
|
| 405 |
+
"pd_ee_delta_pose"
|
| 406 |
+
if config.policy.action_encoding == "rotation6d"
|
| 407 |
+
else "pd_ee_delta_pos"
|
| 408 |
+
):
|
| 409 |
+
raise ValueError(
|
| 410 |
+
"Chunk-relative action encoding and physical source controller disagree"
|
| 411 |
+
)
|
| 412 |
+
wrappers = [
|
| 413 |
+
partial(
|
| 414 |
+
audit_wrapper,
|
| 415 |
+
snapshots=config.output_dir / "raw_observations",
|
| 416 |
+
stride=count,
|
| 417 |
+
seed_start=config.seed_start,
|
| 418 |
+
),
|
| 419 |
+
]
|
| 420 |
+
if config.video_seeds:
|
| 421 |
+
from lim.policy_video import policy_video_wrapper
|
| 422 |
+
|
| 423 |
+
wrappers.append(
|
| 424 |
+
partial(
|
| 425 |
+
policy_video_wrapper,
|
| 426 |
+
output_dir=config.output_dir / "videos",
|
| 427 |
+
seeds=config.video_seeds,
|
| 428 |
+
label="keypose"
|
| 429 |
+
if config.policy.keypose is not None
|
| 430 |
+
else config.policy.method,
|
| 431 |
+
)
|
| 432 |
+
)
|
| 433 |
+
wrappers.append(partial(module.FlattenRGBDObservationWrapper, depth=False))
|
| 434 |
+
return module.make_eval_envs(
|
| 435 |
+
info["env_id"],
|
| 436 |
+
count,
|
| 437 |
+
"physx_cpu",
|
| 438 |
+
{
|
| 439 |
+
"control_mode": config.control_mode,
|
| 440 |
+
"reward_mode": "sparse",
|
| 441 |
+
"obs_mode": "rgb",
|
| 442 |
+
"render_mode": "rgb_array",
|
| 443 |
+
"max_episode_steps": 200,
|
| 444 |
+
"sensor_configs": sensor_configs,
|
| 445 |
+
},
|
| 446 |
+
None,
|
| 447 |
+
wrappers=wrappers,
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def evaluate(config):
|
| 452 |
+
if config.episodes % config.num_envs:
|
| 453 |
+
raise ValueError("Episode count must be divisible by vector environment count")
|
| 454 |
+
config.output_dir.mkdir(parents=True, exist_ok=False)
|
| 455 |
+
module = load_official(config)
|
| 456 |
+
official_evaluate = module.evaluate
|
| 457 |
+
env = create_env(module, config, config.num_envs)
|
| 458 |
+
gripper_trace = None
|
| 459 |
+
keypose_trace = None
|
| 460 |
+
try:
|
| 461 |
+
ck, provenance = load_checkpoint(config.checkpoint)
|
| 462 |
+
check_policy_checkpoint(ck, config)
|
| 463 |
+
agent = build_policy(
|
| 464 |
+
module, env, module.args, config.policy, ck.get("normalization")
|
| 465 |
+
).cuda()
|
| 466 |
+
agent.load_state_dict(ck["ema_agent"])
|
| 467 |
+
recorder = SeededRecorder(RecorderConfig(env=env, run=config))
|
| 468 |
+
query_hook = agent.model.register_forward_pre_hook(recorder.count_inference)
|
| 469 |
+
kwargs = {
|
| 470 |
+
"stats": ck["norm_stats"],
|
| 471 |
+
"num_queries": 1
|
| 472 |
+
if config.policy.keypose is not None
|
| 473 |
+
else config.num_queries,
|
| 474 |
+
"temporal_agg": True,
|
| 475 |
+
"max_timesteps": 200,
|
| 476 |
+
"device": torch.device("cuda"),
|
| 477 |
+
"sim_backend": "physx_cpu",
|
| 478 |
+
}
|
| 479 |
+
start = time.monotonic()
|
| 480 |
+
physical_env = recorder
|
| 481 |
+
if config.gripper_execution.active:
|
| 482 |
+
from lim.action_objective import BinaryGripperEnv, BinaryGripperEnvConfig
|
| 483 |
+
from lim.gripper_execution import (
|
| 484 |
+
GripperAgent,
|
| 485 |
+
GripperBoundaryConfig,
|
| 486 |
+
GripperDecisionEnv,
|
| 487 |
+
GripperPhysicalEnv,
|
| 488 |
+
GripperTrace,
|
| 489 |
+
GripperTraceConfig,
|
| 490 |
+
)
|
| 491 |
+
|
| 492 |
+
gripper_trace = GripperTrace(
|
| 493 |
+
GripperTraceConfig(
|
| 494 |
+
execution=config.gripper_execution,
|
| 495 |
+
output_dir=config.output_dir,
|
| 496 |
+
num_envs=config.num_envs,
|
| 497 |
+
horizon=config.num_queries,
|
| 498 |
+
seed_start=config.seed_start,
|
| 499 |
+
bce=config.policy.action_loss.method == "gripper_bce",
|
| 500 |
+
)
|
| 501 |
+
)
|
| 502 |
+
physical_env = GripperPhysicalEnv(
|
| 503 |
+
GripperBoundaryConfig(
|
| 504 |
+
wrapped=recorder,
|
| 505 |
+
trace=gripper_trace,
|
| 506 |
+
)
|
| 507 |
+
)
|
| 508 |
+
if config.gripper_execution.binary and not gripper_trace.config.bce:
|
| 509 |
+
physical_env = BinaryGripperEnv(
|
| 510 |
+
BinaryGripperEnvConfig(env=physical_env)
|
| 511 |
+
)
|
| 512 |
+
evaluation_agent, evaluation_env = evaluation_transport(
|
| 513 |
+
agent, physical_env, config.policy
|
| 514 |
+
)
|
| 515 |
+
if config.keypose_trace:
|
| 516 |
+
from lim.keypose_trace import KeyposeTraceConfig, KeyposeTraceEnv
|
| 517 |
+
|
| 518 |
+
keypose_trace = KeyposeTraceEnv(
|
| 519 |
+
KeyposeTraceConfig(
|
| 520 |
+
env=evaluation_env,
|
| 521 |
+
path=config.output_dir / "keypose_trace.jsonl",
|
| 522 |
+
seed_start=config.seed_start,
|
| 523 |
+
)
|
| 524 |
+
)
|
| 525 |
+
evaluation_env = keypose_trace
|
| 526 |
+
if gripper_trace is not None:
|
| 527 |
+
evaluation_agent = GripperAgent(
|
| 528 |
+
GripperBoundaryConfig(
|
| 529 |
+
wrapped=evaluation_agent,
|
| 530 |
+
trace=gripper_trace,
|
| 531 |
+
)
|
| 532 |
+
)
|
| 533 |
+
evaluation_env = GripperDecisionEnv(
|
| 534 |
+
GripperBoundaryConfig(
|
| 535 |
+
wrapped=evaluation_env,
|
| 536 |
+
trace=gripper_trace,
|
| 537 |
+
)
|
| 538 |
+
)
|
| 539 |
+
metrics = official_evaluate(
|
| 540 |
+
config.episodes, evaluation_agent, evaluation_env, kwargs
|
| 541 |
+
)
|
| 542 |
+
query_hook.remove()
|
| 543 |
+
assert recorder.model_queries == recorder.calls
|
| 544 |
+
for name in ("success_once", "success_at_end"):
|
| 545 |
+
assert int(np.asarray(metrics[name]).sum()) == sum(
|
| 546 |
+
r[name] for r in recorder.rows
|
| 547 |
+
)
|
| 548 |
+
result = {
|
| 549 |
+
"provenance": provenance | source_provenance(config),
|
| 550 |
+
"sensor_configs": json.loads(config.demonstration_metadata.read_text())[
|
| 551 |
+
"env_info"
|
| 552 |
+
]["env_kwargs"]["sensor_configs"],
|
| 553 |
+
"config": config.model_dump(mode="json"),
|
| 554 |
+
"episodes": len(recorder.rows),
|
| 555 |
+
"counts": {
|
| 556 |
+
key: sum(r[key] for r in recorder.rows)
|
| 557 |
+
for key in (
|
| 558 |
+
"success_once",
|
| 559 |
+
"success_at_end",
|
| 560 |
+
"audit_release_once",
|
| 561 |
+
"audit_release_at_end",
|
| 562 |
+
)
|
| 563 |
+
},
|
| 564 |
+
"policy_vector_calls": recorder.model_queries,
|
| 565 |
+
"environment_vector_steps": recorder.calls,
|
| 566 |
+
"expected_policy_vector_calls": config.episodes // config.num_envs * 200,
|
| 567 |
+
"feedback_hz": 20,
|
| 568 |
+
"parameters": sum(p.numel() for p in agent.parameters()),
|
| 569 |
+
"wall_s": time.monotonic() - start,
|
| 570 |
+
"gpu": torch.cuda.get_device_name(),
|
| 571 |
+
"checkpoint_rule": "official final update EMA; no test checkpoint selection",
|
| 572 |
+
}
|
| 573 |
+
if config.policy.keypose is not None:
|
| 574 |
+
result["action_execution"] = (
|
| 575 |
+
"Newest first query world keypose; no temporal averaging; observed TCP controller with arrival-gated continuous gripper. No oracle stages or object states."
|
| 576 |
+
)
|
| 577 |
+
if config.policy.action_loss.method == "gripper_bce":
|
| 578 |
+
result["gripper_execution"] = evaluation_env.diagnostics()
|
| 579 |
+
if config.gripper_execution.aggregation == "latest":
|
| 580 |
+
result["gripper_execution"]["rule"] = (
|
| 581 |
+
"newest chunk first-step p(open); >=0.5 opens; no hysteresis"
|
| 582 |
+
)
|
| 583 |
+
if gripper_trace is not None:
|
| 584 |
+
result["gripper_intervention"] = gripper_trace.diagnostics()
|
| 585 |
+
(config.output_dir / "result.json").write_text(json.dumps(result, indent=2))
|
| 586 |
+
print("REFERENCE_EVAL_COMPLETE", json.dumps(result), flush=True)
|
| 587 |
+
finally:
|
| 588 |
+
if keypose_trace is not None:
|
| 589 |
+
keypose_trace.finish()
|
| 590 |
+
if gripper_trace is not None:
|
| 591 |
+
gripper_trace.close()
|
| 592 |
+
env.close()
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
def witness(config):
|
| 596 |
+
config.output_dir.mkdir(parents=True, exist_ok=True)
|
| 597 |
+
torch.manual_seed(0)
|
| 598 |
+
module = load_official(config)
|
| 599 |
+
env = create_env(module, config, 1)
|
| 600 |
+
try:
|
| 601 |
+
obs, _ = env.reset(seed=123456)
|
| 602 |
+
base = env.envs[0].unwrapped
|
| 603 |
+
agent = build_policy(module, env, module.args, config.policy).cuda()
|
| 604 |
+
state_shape, rgb_shape = list(obs["state"].shape), list(obs["rgb"].shape)
|
| 605 |
+
with torch.inference_mode():
|
| 606 |
+
pred = agent.get_action(
|
| 607 |
+
{k: torch.as_tensor(v, device="cuda") for k, v in obs.items()}
|
| 608 |
+
)
|
| 609 |
+
assert (
|
| 610 |
+
pred.shape
|
| 611 |
+
== (
|
| 612 |
+
1,
|
| 613 |
+
config.num_queries,
|
| 614 |
+
encoded_dimension(
|
| 615 |
+
ACTION_DIMENSIONS[config.control_mode],
|
| 616 |
+
config.policy.action_encoding,
|
| 617 |
+
),
|
| 618 |
+
)
|
| 619 |
+
and torch.isfinite(pred).all()
|
| 620 |
+
)
|
| 621 |
+
assert base.control_freq == 20
|
| 622 |
+
command = (
|
| 623 |
+
sixd_to_controller(pred[:, 0])
|
| 624 |
+
if config.policy.action_encoding == "rotation6d"
|
| 625 |
+
else pred[:, 0]
|
| 626 |
+
)
|
| 627 |
+
if config.policy.action_loss.method == "gripper_bce":
|
| 628 |
+
_, execution_env = evaluation_transport(agent, env, config.policy)
|
| 629 |
+
execution_env.step(pred[:, 0].cpu().numpy())
|
| 630 |
+
else:
|
| 631 |
+
env.step(command.cpu().numpy())
|
| 632 |
+
result = {
|
| 633 |
+
"status": "PASS",
|
| 634 |
+
"actual_sensor_shader_packs": {
|
| 635 |
+
k: v.config.shader_pack for k, v in base._sensors.items()
|
| 636 |
+
},
|
| 637 |
+
"gymnasium": gym.__version__,
|
| 638 |
+
"torch": torch.__version__,
|
| 639 |
+
"control_hz": base.control_freq,
|
| 640 |
+
"control_mode": base.control_mode,
|
| 641 |
+
"sim_hz": base.sim_freq,
|
| 642 |
+
"robot": base.agent.uid,
|
| 643 |
+
"state_shape": state_shape,
|
| 644 |
+
"rgb_shape": rgb_shape,
|
| 645 |
+
"action_shape": list(pred.shape),
|
| 646 |
+
"controller_action_shape": list(command.shape),
|
| 647 |
+
"action_encoding": config.policy.action_encoding,
|
| 648 |
+
"parameters": sum(p.numel() for p in agent.parameters()),
|
| 649 |
+
"gpu": torch.cuda.get_device_name(),
|
| 650 |
+
}
|
| 651 |
+
(config.output_dir / "result.json").write_text(json.dumps(result, indent=2))
|
| 652 |
+
print("REFERENCE_WITNESS", json.dumps(result), flush=True)
|
| 653 |
+
finally:
|
| 654 |
+
env.close()
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
class ReplayConfig(BaseModel, frozen=True):
|
| 658 |
+
model_config = ConfigDict(
|
| 659 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 660 |
+
)
|
| 661 |
+
module: Any
|
| 662 |
+
"""Pinned official module, supplying the exact RGB observation transformation."""
|
| 663 |
+
observations: list
|
| 664 |
+
"""Raw CPU camera and proprioceptive observations; no encoded visual features."""
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
class SensorReplay:
|
| 668 |
+
"""Feed real raw inputs through official evaluate() without a physics environment."""
|
| 669 |
+
|
| 670 |
+
def __init__(self, config: ReplayConfig):
|
| 671 |
+
self.config = config
|
| 672 |
+
self.processor = SimpleNamespace(
|
| 673 |
+
include_rgb=True,
|
| 674 |
+
include_depth=False,
|
| 675 |
+
include_state=True,
|
| 676 |
+
transforms=config.module.T.Compose(
|
| 677 |
+
[config.module.T.Resize((224, 224), antialias=True)]
|
| 678 |
+
),
|
| 679 |
+
)
|
| 680 |
+
example = self.prepare(0)
|
| 681 |
+
self.single_observation_space = gym.spaces.Dict(
|
| 682 |
+
{
|
| 683 |
+
"state": gym.spaces.Box(
|
| 684 |
+
-np.inf, np.inf, shape=example["state"].shape[1:], dtype=np.float32
|
| 685 |
+
),
|
| 686 |
+
"rgb": gym.spaces.Box(
|
| 687 |
+
0, 255, shape=example["rgb"].shape[1:], dtype=np.uint8
|
| 688 |
+
),
|
| 689 |
+
}
|
| 690 |
+
)
|
| 691 |
+
action_dim = ACTION_DIMENSIONS[config.module.args.control_mode]
|
| 692 |
+
self.single_action_space = gym.spaces.Box(
|
| 693 |
+
-1, 1, (action_dim,), dtype=np.float32
|
| 694 |
+
)
|
| 695 |
+
self.action_space = gym.spaces.Box(-1, 1, (1, action_dim), dtype=np.float32)
|
| 696 |
+
self.num_envs = 1
|
| 697 |
+
self.calls = 0
|
| 698 |
+
self.started = None
|
| 699 |
+
self.rows = []
|
| 700 |
+
|
| 701 |
+
def prepare(self, index):
|
| 702 |
+
# The official transform pops top-level keys only; preserve the raw record.
|
| 703 |
+
raw = dict(self.config.observations[index % len(self.config.observations)])
|
| 704 |
+
return self.config.module.FlattenRGBDObservationWrapper.observation(
|
| 705 |
+
self.processor, raw
|
| 706 |
+
)
|
| 707 |
+
|
| 708 |
+
def next_observation(self):
|
| 709 |
+
torch.cuda.synchronize()
|
| 710 |
+
self.started = time.perf_counter()
|
| 711 |
+
return self.prepare(self.calls)
|
| 712 |
+
|
| 713 |
+
def reset(self):
|
| 714 |
+
return self.next_observation(), {}
|
| 715 |
+
|
| 716 |
+
def step(self, action):
|
| 717 |
+
torch.cuda.synchronize()
|
| 718 |
+
elapsed = (time.perf_counter() - self.started) * 1000
|
| 719 |
+
if not np.isfinite(action).all():
|
| 720 |
+
raise FloatingPointError("Nonfinite reference policy action")
|
| 721 |
+
self.rows.append(
|
| 722 |
+
{
|
| 723 |
+
"index": self.calls,
|
| 724 |
+
"total_ms": elapsed,
|
| 725 |
+
"sampled_process_bytes": process_gpu_memory(),
|
| 726 |
+
}
|
| 727 |
+
)
|
| 728 |
+
self.calls += 1
|
| 729 |
+
truncated = np.array([self.calls % 200 == 0])
|
| 730 |
+
# Required vector episode bookkeeping, deliberately containing no task score.
|
| 731 |
+
info = (
|
| 732 |
+
{"final_info": [{"episode": {"measurement_episode": self.calls // 200}}]}
|
| 733 |
+
if truncated[0]
|
| 734 |
+
else {}
|
| 735 |
+
)
|
| 736 |
+
return (
|
| 737 |
+
self.next_observation(),
|
| 738 |
+
np.array([0.0]),
|
| 739 |
+
np.array([False]),
|
| 740 |
+
truncated,
|
| 741 |
+
info,
|
| 742 |
+
)
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
def profile(config):
|
| 746 |
+
if config.checkpoint is None or config.observations is None:
|
| 747 |
+
raise ValueError("Profile requires checkpoint and raw observations")
|
| 748 |
+
config.output_dir.mkdir(parents=True, exist_ok=False)
|
| 749 |
+
module = load_official(config)
|
| 750 |
+
paths = sorted(config.observations.glob("*.pt"))
|
| 751 |
+
if not paths:
|
| 752 |
+
raise ValueError("No raw observations for profile")
|
| 753 |
+
raw_inputs = {p.name: p.read_bytes() for p in paths}
|
| 754 |
+
replay = SensorReplay(
|
| 755 |
+
ReplayConfig(
|
| 756 |
+
module=module,
|
| 757 |
+
observations=[
|
| 758 |
+
torch.load(io.BytesIO(raw), map_location="cpu", weights_only=False)
|
| 759 |
+
for raw in raw_inputs.values()
|
| 760 |
+
],
|
| 761 |
+
)
|
| 762 |
+
)
|
| 763 |
+
checkpoint, provenance = load_checkpoint(config.checkpoint)
|
| 764 |
+
check_policy_checkpoint(checkpoint, config)
|
| 765 |
+
agent = build_policy(
|
| 766 |
+
module, replay, module.args, config.policy, checkpoint.get("normalization")
|
| 767 |
+
).cuda()
|
| 768 |
+
agent.load_state_dict(checkpoint["ema_agent"])
|
| 769 |
+
pynvml.nvmlInit()
|
| 770 |
+
model_queries = 0
|
| 771 |
+
|
| 772 |
+
def count_query(module, inputs):
|
| 773 |
+
nonlocal model_queries
|
| 774 |
+
model_queries += 1
|
| 775 |
+
|
| 776 |
+
query_hook = agent.model.register_forward_pre_hook(count_query)
|
| 777 |
+
# Complete full 200-step official evaluator episodes. Measure exactly the
|
| 778 |
+
# declared 500 calls after 30 warmup; trailing padding calls are separate.
|
| 779 |
+
total_episodes = math.ceil((30 + config.iterations) / 200)
|
| 780 |
+
evaluation_agent, evaluation_env = evaluation_transport(
|
| 781 |
+
agent, replay, config.policy
|
| 782 |
+
)
|
| 783 |
+
module.evaluate(
|
| 784 |
+
total_episodes,
|
| 785 |
+
evaluation_agent,
|
| 786 |
+
evaluation_env,
|
| 787 |
+
{
|
| 788 |
+
"stats": checkpoint["norm_stats"],
|
| 789 |
+
"num_queries": config.num_queries,
|
| 790 |
+
"temporal_agg": True,
|
| 791 |
+
"max_timesteps": 200,
|
| 792 |
+
"device": torch.device("cuda"),
|
| 793 |
+
"sim_backend": "physx_cpu",
|
| 794 |
+
},
|
| 795 |
+
)
|
| 796 |
+
query_hook.remove()
|
| 797 |
+
assert model_queries == replay.calls
|
| 798 |
+
measured = replay.rows[30 : 30 + config.iterations]
|
| 799 |
+
assert len(measured) == config.iterations
|
| 800 |
+
timings = [row["total_ms"] for row in measured]
|
| 801 |
+
result = {
|
| 802 |
+
"provenance": provenance
|
| 803 |
+
| source_provenance(config)
|
| 804 |
+
| {
|
| 805 |
+
"raw_observations_sha256": {
|
| 806 |
+
name: hashlib.sha256(raw).hexdigest()
|
| 807 |
+
for name, raw in raw_inputs.items()
|
| 808 |
+
}
|
| 809 |
+
},
|
| 810 |
+
"config": config.model_dump(mode="json"),
|
| 811 |
+
"gpu": torch.cuda.get_device_name(),
|
| 812 |
+
"parameters": sum(p.numel() for p in agent.parameters()),
|
| 813 |
+
"raw_observations": len(paths),
|
| 814 |
+
"warmup_calls": 30,
|
| 815 |
+
"measured_calls": len(measured),
|
| 816 |
+
"total_official_evaluator_calls": replay.calls,
|
| 817 |
+
"actual_model_queries": model_queries,
|
| 818 |
+
"trailing_unmeasured_calls": replay.calls - 30 - len(measured),
|
| 819 |
+
"cold_ms": replay.rows[0]["total_ms"],
|
| 820 |
+
"latency_ms": {
|
| 821 |
+
str(p): float(np.percentile(timings, p)) for p in (50, 95, 99, 100)
|
| 822 |
+
},
|
| 823 |
+
"sampled_peak_process_bytes": max(
|
| 824 |
+
row["sampled_process_bytes"] for row in replay.rows
|
| 825 |
+
),
|
| 826 |
+
"peak_allocated_bytes": torch.cuda.max_memory_allocated(),
|
| 827 |
+
"peak_reserved_bytes": torch.cuda.max_memory_reserved(),
|
| 828 |
+
"scope": PROFILE_SCOPE,
|
| 829 |
+
}
|
| 830 |
+
with (config.output_dir / "iterations.jsonl").open("w") as out:
|
| 831 |
+
for row in replay.rows:
|
| 832 |
+
out.write(
|
| 833 |
+
json.dumps(
|
| 834 |
+
row | {"measured": 30 <= row["index"] < 30 + config.iterations}
|
| 835 |
+
)
|
| 836 |
+
+ "\n"
|
| 837 |
+
)
|
| 838 |
+
(config.output_dir / "result.json").write_text(json.dumps(result, indent=2))
|
| 839 |
+
print("REFERENCE_PROFILE_COMPLETE", json.dumps(result), flush=True)
|
| 840 |
+
|
| 841 |
+
|
| 842 |
+
def run(config: ReferenceConfig):
|
| 843 |
+
torch.set_num_threads(4)
|
| 844 |
+
if config.mode == "witness":
|
| 845 |
+
witness(config)
|
| 846 |
+
elif config.mode == "evaluate":
|
| 847 |
+
if config.checkpoint is None:
|
| 848 |
+
raise ValueError("Evaluation requires a checkpoint")
|
| 849 |
+
evaluate(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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Replay original joint-space demonstrations with explicit episode boundaries.
|
| 2 |
+
|
| 3 |
+
Keep ManiSkill's position conversion, and invert its actual CPU Euler controller
|
| 4 |
+
for pose conversion. Only initial states are restored; all subsequent observations
|
| 5 |
+
are generated by executed actions. Each successful record carries its source ID.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import copy
|
| 9 |
+
import hashlib
|
| 10 |
+
import json
|
| 11 |
+
from collections.abc import Callable
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import Any
|
| 14 |
+
|
| 15 |
+
import gymnasium as gym
|
| 16 |
+
import h5py
|
| 17 |
+
import mani_skill.envs # noqa: F401
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
from mani_skill.trajectory.utils.actions.conversion import from_pd_joint_pos
|
| 21 |
+
from mani_skill.utils import common
|
| 22 |
+
from mani_skill.utils.geometry.rotation_conversions import (
|
| 23 |
+
matrix_to_euler_angles,
|
| 24 |
+
quaternion_to_matrix,
|
| 25 |
+
)
|
| 26 |
+
from mani_skill.utils.structs.pose import Pose
|
| 27 |
+
from mani_skill.utils.wrappers.record import RecordEpisode
|
| 28 |
+
from pydantic import BaseModel, ConfigDict, PositiveInt
|
| 29 |
+
from pydantic_settings import CliApp
|
| 30 |
+
|
| 31 |
+
from lim.reference_act import ACTION_DIMENSIONS, ACTControlMode
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class PoseReplayConfig(BaseModel, frozen=True):
|
| 35 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 36 |
+
source: Path
|
| 37 |
+
"""Original joint-position H5, with matching source metadata JSON."""
|
| 38 |
+
output_dir: Path
|
| 39 |
+
"""New directory; existing data is never overwritten."""
|
| 40 |
+
control_mode: ACTControlMode = "pd_ee_delta_pose"
|
| 41 |
+
"""Target controller, with all camera settings retained from the source."""
|
| 42 |
+
source_ids: tuple[int, ...]
|
| 43 |
+
"""Explicit original episode IDs attempted in this declared order."""
|
| 44 |
+
max_substeps: PositiveInt = 4
|
| 45 |
+
"""Maximum target-control steps per source action, matching official replay."""
|
| 46 |
+
save_video: bool = False
|
| 47 |
+
"""Save observer videos for the pilot; formal data need not record videos."""
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class TargetReplayConfig(BaseModel, frozen=True):
|
| 51 |
+
model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid")
|
| 52 |
+
original: Any
|
| 53 |
+
"""Original joint-control environment."""
|
| 54 |
+
target: Any
|
| 55 |
+
"""Target pose environment, optionally wrapped for recording."""
|
| 56 |
+
actions: Any
|
| 57 |
+
"""Original joint-position demonstration actions."""
|
| 58 |
+
max_substeps: PositiveInt = 4
|
| 59 |
+
"""Bounded target-action retries for clipped commands."""
|
| 60 |
+
on_target_step: Callable[[int], None] | None = None
|
| 61 |
+
"""Optional observer called after each executed target step with its source action index."""
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def pose_target_command(controller, goal_world):
|
| 65 |
+
"""Return a bounded command and whether the requested delta was clipped."""
|
| 66 |
+
if (
|
| 67 |
+
controller.config.frame != "root_translation:root_aligned_body_rotation"
|
| 68 |
+
or not controller.config.use_delta
|
| 69 |
+
or controller.config.use_target
|
| 70 |
+
or not controller.config.normalize_action
|
| 71 |
+
):
|
| 72 |
+
raise ValueError("Expected current-pose-relative normalized root-frame control")
|
| 73 |
+
previous = controller.ee_pose_at_base
|
| 74 |
+
goal = controller.root_link.pose.inv() * goal_world
|
| 75 |
+
low, high = controller.action_space_low[:3], controller.action_space_high[:3]
|
| 76 |
+
pos = 2 * (goal.p - previous.p - low) / (high - low) - 1
|
| 77 |
+
# CPU ManiSkill 3.0.1 applies Euler XYZ *negative* rot_lower, then left-composes.
|
| 78 |
+
delta_rotation = goal.q
|
| 79 |
+
from mani_skill.utils.geometry.rotation_conversions import (
|
| 80 |
+
quaternion_invert,
|
| 81 |
+
quaternion_multiply,
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
delta_rotation = quaternion_multiply(delta_rotation, quaternion_invert(previous.q))
|
| 85 |
+
angles = matrix_to_euler_angles(quaternion_to_matrix(delta_rotation), "XYZ")
|
| 86 |
+
rot = angles / controller.config.rot_lower
|
| 87 |
+
norm = torch.linalg.norm(rot, dim=-1, keepdim=True)
|
| 88 |
+
clipped = bool((pos.abs() > 1).any() or (norm > 1).any())
|
| 89 |
+
return torch.cat([pos.clamp(-1, 1), rot / norm.clamp(min=1)], dim=-1), clipped
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def replay_targets(config: TargetReplayConfig):
|
| 93 |
+
original = config.original.unwrapped.agent.controller
|
| 94 |
+
target = config.target.unwrapped.agent.controller
|
| 95 |
+
ori_arm, arm = original.controllers["arm"], target.controllers["arm"]
|
| 96 |
+
pin = original.articulation.create_pinocchio_model()
|
| 97 |
+
info = {}
|
| 98 |
+
for source_index, action in enumerate(config.actions):
|
| 99 |
+
action = common.to_tensor(action, device=config.original.unwrapped.device)
|
| 100 |
+
parts = original.to_action_dict(action)
|
| 101 |
+
config.original.step(action)
|
| 102 |
+
qpos = original.articulation.get_qpos().clone()
|
| 103 |
+
qpos[:, ori_arm.active_joint_indices] = ori_arm._target_qpos
|
| 104 |
+
pin.compute_forward_kinematics(qpos.cpu().numpy()[0])
|
| 105 |
+
goal = Pose.create(
|
| 106 |
+
original.articulation.pose.sp * pin.get_link_pose(arm.ee_link.index)
|
| 107 |
+
)
|
| 108 |
+
for _ in range(config.max_substeps):
|
| 109 |
+
command, clipped = pose_target_command(arm, goal)
|
| 110 |
+
out = {**parts, "arm": command[0]}
|
| 111 |
+
_, _, _, _, info = config.target.step(target.from_action_dict(out))
|
| 112 |
+
if config.on_target_step is not None:
|
| 113 |
+
config.on_target_step(source_index)
|
| 114 |
+
if not clipped:
|
| 115 |
+
break
|
| 116 |
+
return info
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def tree_first(group):
|
| 120 |
+
return {
|
| 121 |
+
k: tree_first(v) if isinstance(v, h5py.Group) else v[0]
|
| 122 |
+
for k, v in group.items()
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def replace_last(destination, source):
|
| 127 |
+
if isinstance(destination, dict):
|
| 128 |
+
for key in destination:
|
| 129 |
+
replace_last(destination[key], source[key])
|
| 130 |
+
else:
|
| 131 |
+
destination[-1] = source[-1]
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def run(config: PoseReplayConfig):
|
| 135 |
+
torch.set_num_threads(4)
|
| 136 |
+
config.output_dir.mkdir(parents=True, exist_ok=False)
|
| 137 |
+
metadata = json.loads(config.source.with_suffix(".json").read_text())
|
| 138 |
+
episodes = {e["episode_id"]: e for e in metadata["episodes"]}
|
| 139 |
+
if len(set(config.source_ids)) != len(config.source_ids):
|
| 140 |
+
raise ValueError("Duplicate source IDs")
|
| 141 |
+
env_info = metadata["env_info"]
|
| 142 |
+
kwargs = copy.deepcopy(env_info["env_kwargs"])
|
| 143 |
+
kwargs.update(sim_backend="physx_cpu", num_envs=1, max_episode_steps=200)
|
| 144 |
+
original = gym.make(env_info["env_id"], **kwargs)
|
| 145 |
+
kwargs.update(obs_mode="rgb", control_mode=config.control_mode)
|
| 146 |
+
target = RecordEpisode(
|
| 147 |
+
gym.make(env_info["env_id"], **kwargs),
|
| 148 |
+
output_dir=str(config.output_dir),
|
| 149 |
+
trajectory_name="trajectory",
|
| 150 |
+
save_trajectory=True,
|
| 151 |
+
save_video=config.save_video,
|
| 152 |
+
save_on_reset=False,
|
| 153 |
+
info_on_video=True,
|
| 154 |
+
video_fps=20,
|
| 155 |
+
)
|
| 156 |
+
records = []
|
| 157 |
+
try:
|
| 158 |
+
with h5py.File(config.source) as source:
|
| 159 |
+
for source_id in config.source_ids:
|
| 160 |
+
episode = episodes[source_id]
|
| 161 |
+
if episode["control_mode"] != "pd_joint_pos":
|
| 162 |
+
raise ValueError("Source must use joint-position expert actions")
|
| 163 |
+
group = source[f"traj_{source_id}"]
|
| 164 |
+
reset = copy.deepcopy(episode["reset_kwargs"])
|
| 165 |
+
# Explicitly clear even FAILED attempts before another reset.
|
| 166 |
+
if target._trajectory_buffer is not None:
|
| 167 |
+
target.flush_trajectory(save=False)
|
| 168 |
+
if config.save_video:
|
| 169 |
+
target.flush_video(save=False)
|
| 170 |
+
original.reset(**reset)
|
| 171 |
+
target.reset(**reset)
|
| 172 |
+
initial = tree_first(group["env_states"])
|
| 173 |
+
original.unwrapped.set_state_dict(initial)
|
| 174 |
+
target.unwrapped.set_state_dict(initial)
|
| 175 |
+
initial_obs = target.unwrapped.get_obs()
|
| 176 |
+
replace_last(target._trajectory_buffer.state, common.batch(initial))
|
| 177 |
+
replace_last(
|
| 178 |
+
target._trajectory_buffer.observation,
|
| 179 |
+
common.to_numpy(common.batch(initial_obs)),
|
| 180 |
+
)
|
| 181 |
+
if config.save_video:
|
| 182 |
+
target.render_images = []
|
| 183 |
+
if config.control_mode == "pd_ee_delta_pos":
|
| 184 |
+
info = from_pd_joint_pos(
|
| 185 |
+
config.control_mode, group["actions"][:], original, target
|
| 186 |
+
)
|
| 187 |
+
else:
|
| 188 |
+
info = replay_targets(
|
| 189 |
+
TargetReplayConfig(
|
| 190 |
+
original=original,
|
| 191 |
+
target=target,
|
| 192 |
+
actions=group["actions"][:],
|
| 193 |
+
max_substeps=config.max_substeps,
|
| 194 |
+
)
|
| 195 |
+
)
|
| 196 |
+
success = bool(common.to_numpy(info["success"]).item())
|
| 197 |
+
buffer = target._trajectory_buffer
|
| 198 |
+
count = len(buffer.action) - 1
|
| 199 |
+
assert buffer.action.shape[-1] == ACTION_DIMENSIONS[config.control_mode]
|
| 200 |
+
assert len(buffer.observation["extra"]["tcp_pose"]) == count + 1
|
| 201 |
+
record = {
|
| 202 |
+
"source_episode_id": source_id,
|
| 203 |
+
"source_episode_seed": episode["episode_seed"],
|
| 204 |
+
"source_steps": len(group["actions"]),
|
| 205 |
+
"target_steps": count,
|
| 206 |
+
"success": success,
|
| 207 |
+
"output_episode_id": target._episode_id + 1 if success else None,
|
| 208 |
+
"max_abs_rotation_action": float(
|
| 209 |
+
np.abs(buffer.action[1:, :, 3:6]).max()
|
| 210 |
+
)
|
| 211 |
+
if config.control_mode == "pd_ee_delta_pose"
|
| 212 |
+
else None,
|
| 213 |
+
}
|
| 214 |
+
target.flush_trajectory(save=success)
|
| 215 |
+
if success:
|
| 216 |
+
target._json_data["episodes"][-1].update(
|
| 217 |
+
source_episode_id=source_id,
|
| 218 |
+
source_episode_seed=episode["episode_seed"],
|
| 219 |
+
)
|
| 220 |
+
if config.save_video:
|
| 221 |
+
target.flush_video(name=f"source{source_id}", save=success)
|
| 222 |
+
records.append(record)
|
| 223 |
+
with (config.output_dir / "attempts.jsonl").open("a") as f:
|
| 224 |
+
f.write(json.dumps(record) + "\n")
|
| 225 |
+
print("REPLAY_EPISODE", json.dumps(record), flush=True)
|
| 226 |
+
finally:
|
| 227 |
+
# Successful data were flushed deliberately; never save residual failures.
|
| 228 |
+
if target._trajectory_buffer is not None:
|
| 229 |
+
target.flush_trajectory(save=False)
|
| 230 |
+
target.close()
|
| 231 |
+
original.close()
|
| 232 |
+
result = {
|
| 233 |
+
"config": config.model_dump(mode="json"),
|
| 234 |
+
"source_sha256": hashlib.sha256(config.source.read_bytes()).hexdigest(),
|
| 235 |
+
"attempted": len(records),
|
| 236 |
+
"successful": sum(r["success"] for r in records),
|
| 237 |
+
"records": records,
|
| 238 |
+
"rotation_encoding": "CPU Euler XYZ inverse including rot_lower sign; radial clipping",
|
| 239 |
+
"state_restoration": "source state0 only; saved initial state and observation repaired before actions",
|
| 240 |
+
"episode_boundary": "flush failed and successful attempts independently",
|
| 241 |
+
}
|
| 242 |
+
(config.output_dir / "result.json").write_text(json.dumps(result, indent=2) + "\n")
|
| 243 |
+
print("REPLAY_COMPLETE", json.dumps(result), flush=True)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
if __name__ == "__main__":
|
| 247 |
+
run(CliApp.run(PoseReplayConfig))
|
fair-comparison/p3x-liftslow-v1/code/lim/run_sequence.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run a declared finite experiment sequence when its assigned GPU is free."""
|
| 2 |
+
|
| 3 |
+
import fcntl
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import signal
|
| 8 |
+
import subprocess
|
| 9 |
+
import time
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
from pydantic import BaseModel, ConfigDict, NonNegativeInt, PositiveInt
|
| 13 |
+
from pydantic_settings import CliApp
|
| 14 |
+
|
| 15 |
+
from lim.job import JobConfig, run_job
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class SequenceConfig(BaseModel, frozen=True):
|
| 19 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 20 |
+
jobs: tuple[Path, ...]
|
| 21 |
+
"""Ordered immutable JobConfig specifications; any failure stops successors."""
|
| 22 |
+
output_dir: Path
|
| 23 |
+
"""New sequence state directory; never resume an interrupted sequence implicitly."""
|
| 24 |
+
gpu: NonNegativeInt
|
| 25 |
+
"""One preselected physical GPU, matching every job's assignment."""
|
| 26 |
+
max_wait_s: PositiveInt = 172800
|
| 27 |
+
"""Maximum time waiting for shared GPU availability before stopping."""
|
| 28 |
+
poll_s: PositiveInt = 30
|
| 29 |
+
"""Availability interval; no model or renderer is created while waiting."""
|
| 30 |
+
free_memory_mib: PositiveInt = 500
|
| 31 |
+
"""Maximum existing GPU allocation permitted before launching a job."""
|
| 32 |
+
required_files: dict[Path, str] = {}
|
| 33 |
+
"""Exact SHA256 for asynchronously copied inputs; checked before any GPU work."""
|
| 34 |
+
prerequisite_sequence: Path | None = None
|
| 35 |
+
"""Existing sequence state.json that must complete before taking the GPU lock."""
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class SequenceCLIConfig(BaseModel, frozen=True):
|
| 39 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 40 |
+
spec: Path
|
| 41 |
+
"""Complete JSON SequenceConfig, including input dependencies and assigned GPU."""
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def run(config: SequenceConfig):
|
| 45 |
+
jobs = [JobConfig.model_validate_json(p.read_text()) for p in config.jobs]
|
| 46 |
+
if not jobs or any(j.gpu != config.gpu for j in jobs):
|
| 47 |
+
raise ValueError("Sequence must be nonempty and use exactly its assigned GPU")
|
| 48 |
+
config.output_dir.mkdir(parents=True, exist_ok=False)
|
| 49 |
+
record = {
|
| 50 |
+
"status": "waiting",
|
| 51 |
+
"config": config.model_dump(mode="json"),
|
| 52 |
+
"jobs": [j.model_dump(mode="json") for j in jobs],
|
| 53 |
+
"completed_jobs": [],
|
| 54 |
+
"started_epoch": time.time(),
|
| 55 |
+
}
|
| 56 |
+
path = config.output_dir / "state.json"
|
| 57 |
+
|
| 58 |
+
def write():
|
| 59 |
+
tmp = path.with_suffix(".tmp")
|
| 60 |
+
tmp.write_text(json.dumps(record, indent=2) + "\n")
|
| 61 |
+
tmp.replace(path)
|
| 62 |
+
|
| 63 |
+
def interrupted(signum, frame):
|
| 64 |
+
raise KeyboardInterrupt(f"Sequence received signal {signum}")
|
| 65 |
+
|
| 66 |
+
signal.signal(signal.SIGTERM, interrupted)
|
| 67 |
+
write()
|
| 68 |
+
remaining_wait = config.max_wait_s
|
| 69 |
+
try:
|
| 70 |
+
input_wait_started = time.monotonic()
|
| 71 |
+
while missing := [str(p) for p in config.required_files if not p.is_file()]:
|
| 72 |
+
record.update(
|
| 73 |
+
status="waiting_for_inputs",
|
| 74 |
+
missing_files=missing,
|
| 75 |
+
checked_epoch=time.time(),
|
| 76 |
+
)
|
| 77 |
+
write()
|
| 78 |
+
if time.monotonic() - input_wait_started >= remaining_wait:
|
| 79 |
+
raise TimeoutError("Input transfer did not complete")
|
| 80 |
+
time.sleep(config.poll_s)
|
| 81 |
+
for p, expected in config.required_files.items():
|
| 82 |
+
with p.open("rb") as stream:
|
| 83 |
+
actual = hashlib.file_digest(stream, "sha256").hexdigest()
|
| 84 |
+
if actual != expected:
|
| 85 |
+
raise ValueError(f"Input digest mismatch: {p}")
|
| 86 |
+
remaining_wait -= time.monotonic() - input_wait_started
|
| 87 |
+
record.pop("missing_files", None)
|
| 88 |
+
record["inputs_verified"] = True
|
| 89 |
+
write()
|
| 90 |
+
dependency_started = time.monotonic()
|
| 91 |
+
if config.prerequisite_sequence is not None:
|
| 92 |
+
while True:
|
| 93 |
+
dependency = json.loads(config.prerequisite_sequence.read_text())
|
| 94 |
+
status = dependency["status"]
|
| 95 |
+
if status == "complete":
|
| 96 |
+
record["prerequisite_complete"] = str(config.prerequisite_sequence)
|
| 97 |
+
break
|
| 98 |
+
if status in ("failed", "interrupted"):
|
| 99 |
+
raise RuntimeError(
|
| 100 |
+
f"Prerequisite sequence {status}; successors stopped"
|
| 101 |
+
)
|
| 102 |
+
record.update(
|
| 103 |
+
status="waiting_for_prerequisite", checked_epoch=time.time()
|
| 104 |
+
)
|
| 105 |
+
write()
|
| 106 |
+
if time.monotonic() - dependency_started >= remaining_wait:
|
| 107 |
+
raise TimeoutError("Prerequisite sequence did not complete")
|
| 108 |
+
time.sleep(config.poll_s)
|
| 109 |
+
remaining_wait -= time.monotonic() - dependency_started
|
| 110 |
+
# Cooperating project workers cannot race for the same physical device.
|
| 111 |
+
with Path(f"/tmp/lim-gpu-{os.getuid()}-{config.gpu}.lock").open("a") as lock:
|
| 112 |
+
lock_started = time.monotonic()
|
| 113 |
+
while True:
|
| 114 |
+
try:
|
| 115 |
+
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 116 |
+
break
|
| 117 |
+
except BlockingIOError:
|
| 118 |
+
record.update(status="waiting_for_lock", checked_epoch=time.time())
|
| 119 |
+
write()
|
| 120 |
+
if time.monotonic() - lock_started >= remaining_wait:
|
| 121 |
+
raise TimeoutError(
|
| 122 |
+
"Assigned GPU remained reserved by another sequence"
|
| 123 |
+
)
|
| 124 |
+
time.sleep(config.poll_s)
|
| 125 |
+
remaining_wait -= time.monotonic() - lock_started
|
| 126 |
+
for spec, job in zip(config.jobs, jobs, strict=True):
|
| 127 |
+
wait_started = time.monotonic()
|
| 128 |
+
deadline = wait_started + remaining_wait
|
| 129 |
+
record.update(status="waiting", current_job=str(spec))
|
| 130 |
+
while True:
|
| 131 |
+
query = subprocess.run(
|
| 132 |
+
[
|
| 133 |
+
"nvidia-smi",
|
| 134 |
+
f"--id={config.gpu}",
|
| 135 |
+
"--query-gpu=memory.used,utilization.gpu",
|
| 136 |
+
"--format=csv,noheader,nounits",
|
| 137 |
+
],
|
| 138 |
+
capture_output=True,
|
| 139 |
+
text=True,
|
| 140 |
+
check=True,
|
| 141 |
+
timeout=20,
|
| 142 |
+
)
|
| 143 |
+
memory, utilization = [
|
| 144 |
+
int(x.strip()) for x in query.stdout.split(",")
|
| 145 |
+
]
|
| 146 |
+
record.update(
|
| 147 |
+
gpu_memory_mib=memory,
|
| 148 |
+
gpu_utilization_pct=utilization,
|
| 149 |
+
checked_epoch=time.time(),
|
| 150 |
+
)
|
| 151 |
+
write()
|
| 152 |
+
if memory <= config.free_memory_mib and utilization <= 10:
|
| 153 |
+
break
|
| 154 |
+
if time.monotonic() >= deadline:
|
| 155 |
+
raise TimeoutError("Assigned GPU remained occupied")
|
| 156 |
+
time.sleep(config.poll_s)
|
| 157 |
+
if JobConfig.model_validate_json(spec.read_text()) != job:
|
| 158 |
+
raise ValueError("Job specification changed while waiting")
|
| 159 |
+
remaining_wait -= time.monotonic() - wait_started
|
| 160 |
+
record.update(status="running")
|
| 161 |
+
write()
|
| 162 |
+
run_job(job)
|
| 163 |
+
result = json.loads((job.output_dir / "result.json").read_text())
|
| 164 |
+
if result["status"] != "complete" or result["exit_code"] != 0:
|
| 165 |
+
raise RuntimeError("Job did not complete successfully")
|
| 166 |
+
record["completed_jobs"].append(str(spec))
|
| 167 |
+
signal.signal(signal.SIGTERM, interrupted)
|
| 168 |
+
record.update(status="complete", ended_epoch=time.time())
|
| 169 |
+
except BaseException as error:
|
| 170 |
+
current_result = (
|
| 171 |
+
jobs[len(record["completed_jobs"])].output_dir / "result.json"
|
| 172 |
+
if len(record["completed_jobs"]) < len(jobs)
|
| 173 |
+
else None
|
| 174 |
+
)
|
| 175 |
+
child_interrupted = (
|
| 176 |
+
current_result is not None
|
| 177 |
+
and current_result.exists()
|
| 178 |
+
and json.loads(current_result.read_text()).get("status") == "interrupted"
|
| 179 |
+
)
|
| 180 |
+
record.update(
|
| 181 |
+
status="interrupted"
|
| 182 |
+
if isinstance(error, KeyboardInterrupt) or child_interrupted
|
| 183 |
+
else "failed",
|
| 184 |
+
error=f"{type(error).__name__}: {error}",
|
| 185 |
+
ended_epoch=time.time(),
|
| 186 |
+
)
|
| 187 |
+
raise
|
| 188 |
+
finally:
|
| 189 |
+
write()
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
if __name__ == "__main__":
|
| 193 |
+
cli = CliApp.run(SequenceCLIConfig)
|
| 194 |
+
run(SequenceConfig.model_validate_json(cli.spec.read_text()))
|
fair-comparison/p3x-liftslow-v1/code/lim/smoke.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exercise CUDA, physical stepping, and measured camera observations."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import gymnasium as gym
|
| 7 |
+
import imageio.v3 as iio
|
| 8 |
+
import mani_skill.envs # noqa: F401
|
| 9 |
+
import torch
|
| 10 |
+
from pydantic import BaseModel, ConfigDict
|
| 11 |
+
from pydantic_settings import CliApp
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class SmokeConfig(BaseModel, frozen=True):
|
| 15 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 16 |
+
|
| 17 |
+
output_dir: Path = Path("artifacts/smoke")
|
| 18 |
+
"""Directory for a rendered scene and the observed environment witness."""
|
| 19 |
+
|
| 20 |
+
device: str = "cuda:0"
|
| 21 |
+
"""CUDA device used for the seeded kernel witness."""
|
| 22 |
+
|
| 23 |
+
seed: int = 0
|
| 24 |
+
"""Seed for both the kernel and environment reset."""
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def run_smoke(config: SmokeConfig) -> dict:
|
| 28 |
+
torch.manual_seed(config.seed)
|
| 29 |
+
x = torch.randn(32, 32, device=config.device)
|
| 30 |
+
witness = (x @ x.T).diagonal().sum().item()
|
| 31 |
+
assert witness > 0 and torch.isfinite(x).all()
|
| 32 |
+
env = gym.make(
|
| 33 |
+
"StackCube-v1",
|
| 34 |
+
obs_mode="pointcloud",
|
| 35 |
+
control_mode="pd_ee_delta_pose",
|
| 36 |
+
sim_backend="cpu",
|
| 37 |
+
render_mode="rgb_array",
|
| 38 |
+
robot_uids="panda",
|
| 39 |
+
max_episode_steps=200,
|
| 40 |
+
)
|
| 41 |
+
try:
|
| 42 |
+
obs, _ = env.reset(seed=config.seed)
|
| 43 |
+
cloud = obs["pointcloud"]
|
| 44 |
+
valid = cloud["xyzw"][..., 3] > 0
|
| 45 |
+
assert valid.any() and torch.isfinite(cloud["xyzw"]).all()
|
| 46 |
+
action = env.action_space.sample() * 0
|
| 47 |
+
_, _, _, _, info = env.step(action)
|
| 48 |
+
frame = env.render()
|
| 49 |
+
if hasattr(frame, "cpu"):
|
| 50 |
+
frame = frame.cpu().numpy()
|
| 51 |
+
if frame.ndim == 4:
|
| 52 |
+
frame = frame[0]
|
| 53 |
+
assert frame.ndim == 3 and frame.shape[-1] == 3 and frame.max() > 0
|
| 54 |
+
config.output_dir.mkdir(parents=True, exist_ok=True)
|
| 55 |
+
iio.imwrite(config.output_dir / "stackcube.png", frame)
|
| 56 |
+
result = {
|
| 57 |
+
"status": "PASS",
|
| 58 |
+
"scope": "CUDA, physical stepping, and rendering only; no learned policy",
|
| 59 |
+
"gpu": torch.cuda.get_device_name(config.device),
|
| 60 |
+
"torch": torch.__version__,
|
| 61 |
+
"cuda": torch.version.cuda,
|
| 62 |
+
"seed": config.seed,
|
| 63 |
+
"kernel_witness": witness,
|
| 64 |
+
"valid_depth_points": int(valid.sum()),
|
| 65 |
+
"image_shape": list(frame.shape),
|
| 66 |
+
"initial_step_success": info["success"].tolist(),
|
| 67 |
+
"available_extra_keys": sorted(obs["extra"]),
|
| 68 |
+
}
|
| 69 |
+
(config.output_dir / "witness.json").write_text(
|
| 70 |
+
json.dumps(result, indent=2) + "\n"
|
| 71 |
+
)
|
| 72 |
+
print("ENV_WITNESS", json.dumps(result), flush=True)
|
| 73 |
+
return result
|
| 74 |
+
finally:
|
| 75 |
+
env.close()
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
if __name__ == "__main__":
|
| 79 |
+
run_smoke(CliApp.run(SmokeConfig))
|
fair-comparison/p3x-liftslow-v1/code/lim/tasks.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tasks with an annotated native Panda motion-planning expert.
|
| 2 |
+
|
| 3 |
+
Each entry names the ManiSkill expert solution module and the actors whose
|
| 4 |
+
poses are logged during evaluation. All tasks use panda_wristcam with the
|
| 5 |
+
same state25 (qpos9, qvel9, TCP7) and two-camera RGB layout; LiftPegUpright
|
| 6 |
+
defaults to the plain panda, so it runs as the registered wrist-camera variant.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import lim.lift_peg_env # noqa: F401 (registers LiftPegUprightWristcam-v1)
|
| 10 |
+
|
| 11 |
+
TASKS = {
|
| 12 |
+
"StackCube-v1": ("stack_cube", ("cubeA", "cubeB")),
|
| 13 |
+
"StackPyramid-v1": ("stack_pyramid", ("cubeA", "cubeB", "cubeC")),
|
| 14 |
+
"PegInsertionSide-v1": ("peg_insertion_side", ("peg", "box")),
|
| 15 |
+
"LiftPegUprightWristcam-v1": ("lift_peg_upright", ("peg",)),
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def expert_module(env_id, override=None):
|
| 20 |
+
"""The task's native expert solution module, or the module named by `override`."""
|
| 21 |
+
import importlib
|
| 22 |
+
|
| 23 |
+
if env_id not in TASKS:
|
| 24 |
+
raise ValueError(f"No annotated expert for {env_id}")
|
| 25 |
+
return importlib.import_module(
|
| 26 |
+
override or f"mani_skill.examples.motionplanning.panda.solutions.{TASKS[env_id][0]}"
|
| 27 |
+
)
|
fair-comparison/p3x-liftslow-v1/code/lim/train_offline.py
ADDED
|
@@ -0,0 +1,716 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Train pinned ACT on recorded demonstrations; run simulator evaluation separately.
|
| 2 |
+
|
| 3 |
+
The upstream Agent only reads observation/action shapes from its ``env`` argument.
|
| 4 |
+
Here those shapes come from a recorded real environment witness. No environment,
|
| 5 |
+
reset, step, reward, or success result is synthesized by this training entrypoint.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import hashlib
|
| 9 |
+
import importlib.metadata
|
| 10 |
+
import json
|
| 11 |
+
import random
|
| 12 |
+
import signal
|
| 13 |
+
import sys
|
| 14 |
+
import time
|
| 15 |
+
from dataclasses import asdict
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from types import SimpleNamespace
|
| 18 |
+
from typing import Literal
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import torch
|
| 22 |
+
import tyro
|
| 23 |
+
from diffusers.training_utils import EMAModel
|
| 24 |
+
from pydantic import BaseModel, ConfigDict, Field, PositiveInt, model_validator
|
| 25 |
+
from pydantic_settings import CliApp
|
| 26 |
+
from torch.utils.data import BatchSampler, DataLoader, RandomSampler
|
| 27 |
+
|
| 28 |
+
from lim.act_optimization import ACTOptimizationConfig, ACTTrainingObjective
|
| 29 |
+
from lim.act_policy import (
|
| 30 |
+
ACTPolicyConfig,
|
| 31 |
+
ChunkDatasetConfig,
|
| 32 |
+
ChunkRelativeDataset,
|
| 33 |
+
build_policy,
|
| 34 |
+
policy_loss,
|
| 35 |
+
)
|
| 36 |
+
from lim.action_encoding import encode_dataset_actions, encoded_dimension
|
| 37 |
+
from lim.action_objective import validate_binary_gripper
|
| 38 |
+
from lim.keypose_dense import (
|
| 39 |
+
DenseAuxiliaryDataset,
|
| 40 |
+
DenseAuxiliaryDatasetConfig,
|
| 41 |
+
primary_state_sha256,
|
| 42 |
+
)
|
| 43 |
+
from lim.keypose_policy import (
|
| 44 |
+
KeyposeDataset,
|
| 45 |
+
KeyposeDatasetConfig,
|
| 46 |
+
KeyposeSamplingConfig,
|
| 47 |
+
)
|
| 48 |
+
from lim.keypose_sequence import KeyposeSequenceDataset, KeyposeSequenceDatasetConfig
|
| 49 |
+
from lim.keypose_stop import original_state_sha256
|
| 50 |
+
from lim.normalization import (
|
| 51 |
+
FitNormalizationConfig,
|
| 52 |
+
NormalizedDataset,
|
| 53 |
+
NormalizedDatasetConfig,
|
| 54 |
+
checked_statistics,
|
| 55 |
+
fit_normalization,
|
| 56 |
+
)
|
| 57 |
+
from lim.reference_act import (
|
| 58 |
+
ACTION_DIMENSIONS,
|
| 59 |
+
ReferenceConfig,
|
| 60 |
+
load_official,
|
| 61 |
+
source_provenance,
|
| 62 |
+
)
|
| 63 |
+
from lim.tasks import TASKS
|
| 64 |
+
from lim.train_resume import (
|
| 65 |
+
VOLATILE_LEDGER_KEYS,
|
| 66 |
+
StopRequest,
|
| 67 |
+
TrainingParts,
|
| 68 |
+
advance,
|
| 69 |
+
capture,
|
| 70 |
+
check_rebuild,
|
| 71 |
+
check_replay,
|
| 72 |
+
hold_workdir,
|
| 73 |
+
load_snapshot,
|
| 74 |
+
restore,
|
| 75 |
+
resumable_ledger,
|
| 76 |
+
same_metrics,
|
| 77 |
+
save_snapshot,
|
| 78 |
+
split_metrics,
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class FrozenNormalizationConfig(BaseModel, frozen=True):
|
| 83 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 84 |
+
training_ledger: Path
|
| 85 |
+
"""Completed training ledger owning the exact fitted normalization to reuse."""
|
| 86 |
+
sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
|
| 87 |
+
"""Pinned ledger identity; its original population and horizon remain recorded."""
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class OfflineTrainConfig(BaseModel, frozen=True):
|
| 91 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 92 |
+
workdir: Path
|
| 93 |
+
"""New training directory, separate from all prior attempts."""
|
| 94 |
+
official_arguments: list[str]
|
| 95 |
+
"""Native official Args, retained verbatim for recipe comparison."""
|
| 96 |
+
witness: Path
|
| 97 |
+
"""Recorded successful real RGB/environment/ACT witness supplying model shapes."""
|
| 98 |
+
witness_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
|
| 99 |
+
"""Pinned witness identity; shape descriptors are never guessed."""
|
| 100 |
+
optimization: ACTOptimizationConfig = ACTOptimizationConfig()
|
| 101 |
+
"""Training-only single-method intervention; control retains the native objective."""
|
| 102 |
+
policy: ACTPolicyConfig = ACTPolicyConfig()
|
| 103 |
+
"""Policy architecture/input intervention, shared with evaluation and profiling."""
|
| 104 |
+
sampler_seed: int | None = None
|
| 105 |
+
"""Optional private batch order RNG for matched new cohorts; None retains legacy order."""
|
| 106 |
+
keypose_sampling: KeyposeSamplingConfig = KeyposeSamplingConfig()
|
| 107 |
+
"""Training-only sample selection; does not alter the policy or inference ABI."""
|
| 108 |
+
frozen_normalization: FrozenNormalizationConfig | None = None
|
| 109 |
+
"""Reuse completed same-data statistics, e.g. Q30 scales for a Q1 comparison."""
|
| 110 |
+
precision: Literal["fp32", "fp16"] = "fp32"
|
| 111 |
+
"""Training arithmetic. fp16 adds CUDA autocast with dynamic loss scaling;
|
| 112 |
+
parameters, optimizer, EMA, checkpoints and evaluation remain fp32."""
|
| 113 |
+
snapshot_every: PositiveInt | None = None
|
| 114 |
+
"""Updates between full training snapshots for exact resumption; SIGTERM also
|
| 115 |
+
snapshots the current update. None keeps the single-attempt run unchanged."""
|
| 116 |
+
|
| 117 |
+
@model_validator(mode="after")
|
| 118 |
+
def validate_keypose_sampling(self):
|
| 119 |
+
if self.keypose_sampling.active and self.policy.keypose is None:
|
| 120 |
+
raise ValueError("Keypose sample selection requires a keypose policy")
|
| 121 |
+
if self.keypose_sampling.active and self.policy.keypose_context != "none":
|
| 122 |
+
raise ValueError(
|
| 123 |
+
"Completed-goal context screen preserves every original training observation"
|
| 124 |
+
)
|
| 125 |
+
compact = (
|
| 126 |
+
self.policy.chunk_label_offset > 0
|
| 127 |
+
or self.policy.chunk_pose_supervision == "phase_segments"
|
| 128 |
+
or self.policy.chunk_switch_head
|
| 129 |
+
)
|
| 130 |
+
if compact and self.frozen_normalization is None:
|
| 131 |
+
raise ValueError(
|
| 132 |
+
"Compact endpoint outputs reuse completed Q30 statistics; never refit"
|
| 133 |
+
)
|
| 134 |
+
queries = self.official_arguments
|
| 135 |
+
declared = (
|
| 136 |
+
int(queries[queries.index("--num-queries") + 1])
|
| 137 |
+
if "--num-queries" in queries
|
| 138 |
+
else 30
|
| 139 |
+
)
|
| 140 |
+
if (self.policy.chunk_pose_supervision == "phase_segments") != (declared == 2):
|
| 141 |
+
raise ValueError("Phase segments use exactly two queries, and only they do")
|
| 142 |
+
return self
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def load_frozen_normalization(config: OfflineTrainConfig):
|
| 146 |
+
"""Validate reuse without refitting a different horizon's label population."""
|
| 147 |
+
frozen = config.frozen_normalization
|
| 148 |
+
if frozen is None:
|
| 149 |
+
raise ValueError("No frozen normalization source was declared")
|
| 150 |
+
raw = frozen.training_ledger.read_bytes()
|
| 151 |
+
if hashlib.sha256(raw).hexdigest() != frozen.sha256:
|
| 152 |
+
raise ValueError("Frozen normalization training ledger identity mismatch")
|
| 153 |
+
source = json.loads(raw)
|
| 154 |
+
if source["status"] != "complete":
|
| 155 |
+
raise ValueError("Frozen normalization requires completed source training")
|
| 156 |
+
original = ACTPolicyConfig.model_validate(source["config"]["policy"])
|
| 157 |
+
# Pose supervision may intentionally differ, but encoded coordinates may not.
|
| 158 |
+
# Other policy changes do not alter the affine transform's physical meaning.
|
| 159 |
+
for field in (
|
| 160 |
+
"method",
|
| 161 |
+
"action_encoding",
|
| 162 |
+
"chunk_anchor",
|
| 163 |
+
"chunk_normalization_population",
|
| 164 |
+
"keypose",
|
| 165 |
+
):
|
| 166 |
+
if getattr(original, field) != getattr(config.policy, field):
|
| 167 |
+
raise ValueError(f"Frozen normalization representation differs: {field}")
|
| 168 |
+
statistics = checked_statistics(
|
| 169 |
+
source["normalization"],
|
| 170 |
+
config.policy.normalization,
|
| 171 |
+
config.policy.action_encoding,
|
| 172 |
+
)
|
| 173 |
+
if statistics is None:
|
| 174 |
+
raise ValueError("Frozen normalization source has no fitted statistics")
|
| 175 |
+
args = config.official_arguments
|
| 176 |
+
demo = Path(args[args.index("--demo-path") + 1])
|
| 177 |
+
count = int(args[args.index("--num-demos") + 1])
|
| 178 |
+
with demo.open("rb") as stream:
|
| 179 |
+
source_sha = hashlib.file_digest(stream, "sha256").hexdigest()
|
| 180 |
+
if statistics.source_sha256 != source_sha:
|
| 181 |
+
raise ValueError("Frozen normalization demonstration identity mismatch")
|
| 182 |
+
if statistics.trajectories != count or source["source_demonstrations"] != count:
|
| 183 |
+
raise ValueError("Frozen normalization demonstration count differs")
|
| 184 |
+
return statistics, {
|
| 185 |
+
"mode": "frozen_completed_training",
|
| 186 |
+
**frozen.model_dump(mode="json"),
|
| 187 |
+
"source_num_queries": source["official_args"]["num_queries"],
|
| 188 |
+
"source_samples": statistics.samples,
|
| 189 |
+
"source_pose_supervision": original.chunk_pose_supervision,
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def optimizer_step(loss, optimizer, scaler):
|
| 194 |
+
"""One backward and update; False when fp16 loss scaling found inf/NaN gradients
|
| 195 |
+
and skipped the update. A disabled scaler is exactly backward then step."""
|
| 196 |
+
optimizer.zero_grad()
|
| 197 |
+
scaler.scale(loss).backward()
|
| 198 |
+
scale = scaler.get_scale()
|
| 199 |
+
scaler.step(optimizer)
|
| 200 |
+
scaler.update()
|
| 201 |
+
return scaler.get_scale() >= scale
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class OfflineTrainCLI(BaseModel, frozen=True):
|
| 205 |
+
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
|
| 206 |
+
spec: Path
|
| 207 |
+
"""JSON declaring the offline invocation and native recipe."""
|
| 208 |
+
resume: bool = False
|
| 209 |
+
"""Continue the unfinished run in the spec's workdir from its latest snapshot."""
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def policy_spaces(config: OfflineTrainConfig):
|
| 213 |
+
raw = config.witness.read_bytes()
|
| 214 |
+
if hashlib.sha256(raw).hexdigest() != config.witness_sha256:
|
| 215 |
+
raise ValueError("Real environment witness identity mismatch")
|
| 216 |
+
witness = json.loads(raw)
|
| 217 |
+
if witness["status"] != "PASS" or witness["robot"] != "panda_wristcam":
|
| 218 |
+
raise ValueError("Expected a successful real panda_wristcam witness")
|
| 219 |
+
state, rgb, actions = (
|
| 220 |
+
witness["state_shape"],
|
| 221 |
+
witness["rgb_shape"],
|
| 222 |
+
witness["action_shape"],
|
| 223 |
+
)
|
| 224 |
+
control_mode = witness.get("control_mode", "pd_ee_delta_pos")
|
| 225 |
+
encoding = witness.get("action_encoding", "controller")
|
| 226 |
+
if (
|
| 227 |
+
state != [1, 25]
|
| 228 |
+
or rgb != [1, 2, 3, 224, 224]
|
| 229 |
+
or control_mode not in ACTION_DIMENSIONS
|
| 230 |
+
or encoding != config.policy.action_encoding
|
| 231 |
+
# The witness proves sensor and per-action dimensions. Its recorded
|
| 232 |
+
# prediction horizon is not a physical environment dimension and need
|
| 233 |
+
# not equal the new model's query count (e.g. a true single-target head).
|
| 234 |
+
or len(actions) != 3
|
| 235 |
+
or actions[0] != 1
|
| 236 |
+
or not isinstance(actions[1], int)
|
| 237 |
+
or isinstance(actions[1], bool)
|
| 238 |
+
or actions[1] < 1
|
| 239 |
+
or actions[2] != encoded_dimension(ACTION_DIMENSIONS[control_mode], encoding)
|
| 240 |
+
or witness.get("controller_action_shape", [1, ACTION_DIMENSIONS[control_mode]])
|
| 241 |
+
!= [1, ACTION_DIMENSIONS[control_mode]]
|
| 242 |
+
):
|
| 243 |
+
raise ValueError("Witness differs from the audited StackCube RGB contract")
|
| 244 |
+
return SimpleNamespace(
|
| 245 |
+
single_observation_space={
|
| 246 |
+
"state": SimpleNamespace(shape=tuple(state[1:])),
|
| 247 |
+
"rgb": SimpleNamespace(shape=tuple(rgb[1:])),
|
| 248 |
+
},
|
| 249 |
+
single_action_space=SimpleNamespace(shape=(ACTION_DIMENSIONS[control_mode],)),
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def run(config: OfflineTrainConfig, resume: bool = False):
|
| 254 |
+
if resume and config.snapshot_every is None:
|
| 255 |
+
raise ValueError("Only a run declared with snapshots can resume")
|
| 256 |
+
reference = ReferenceConfig()
|
| 257 |
+
provenance = source_provenance(reference)
|
| 258 |
+
native = load_official(reference)
|
| 259 |
+
args = tyro.cli(native.Args, args=config.official_arguments)
|
| 260 |
+
native.args = args
|
| 261 |
+
if (
|
| 262 |
+
args.env_id not in TASKS
|
| 263 |
+
or args.control_mode not in ACTION_DIMENSIONS
|
| 264 |
+
or args.sim_backend != "physx_cpu"
|
| 265 |
+
or args.include_depth
|
| 266 |
+
or args.num_queries not in (1, 2, 10, 20, 30, 50)
|
| 267 |
+
or args.num_dataload_workers != 0
|
| 268 |
+
or args.num_eval_envs != 10
|
| 269 |
+
or not args.cuda
|
| 270 |
+
or args.track
|
| 271 |
+
or not args.exp_name
|
| 272 |
+
or args.total_iters < 2
|
| 273 |
+
or args.num_demos is None
|
| 274 |
+
or args.num_demos < 1
|
| 275 |
+
or args.save_freq != args.total_iters - 1
|
| 276 |
+
):
|
| 277 |
+
raise ValueError("Offline entrypoint supports only the declared RGB ACT recipe")
|
| 278 |
+
if (
|
| 279 |
+
config.policy.method != "cvae"
|
| 280 |
+
or config.policy.normalization.method != "none"
|
| 281 |
+
or config.policy.state_input != "full"
|
| 282 |
+
or config.policy.action_loss.method != "native"
|
| 283 |
+
) and config.optimization.method != "control":
|
| 284 |
+
raise ValueError(
|
| 285 |
+
"Screen policy interventions independently of training-only changes"
|
| 286 |
+
)
|
| 287 |
+
if config.policy.method == "chunk_relative" and args.control_mode != (
|
| 288 |
+
"pd_ee_delta_pose"
|
| 289 |
+
if config.policy.action_encoding == "rotation6d"
|
| 290 |
+
else "pd_ee_delta_pos"
|
| 291 |
+
):
|
| 292 |
+
raise ValueError(
|
| 293 |
+
"Chunk-relative action encoding and physical source controller disagree"
|
| 294 |
+
)
|
| 295 |
+
metadata = json.loads(Path(args.demo_path).with_suffix(".json").read_text())
|
| 296 |
+
demo_control = metadata["env_info"]["env_kwargs"].get(
|
| 297 |
+
"control_mode", metadata["episodes"][0].get("control_mode")
|
| 298 |
+
)
|
| 299 |
+
if demo_control != args.control_mode:
|
| 300 |
+
raise ValueError("Demonstration control mode differs from the training recipe")
|
| 301 |
+
spaces = policy_spaces(config)
|
| 302 |
+
if spaces.single_action_space.shape != (ACTION_DIMENSIONS[args.control_mode],):
|
| 303 |
+
raise ValueError("Witness and training control dimensions differ")
|
| 304 |
+
config.workdir.mkdir(parents=True, exist_ok=True)
|
| 305 |
+
ledger_path = config.workdir / "offline-training.json"
|
| 306 |
+
# Kept open (and locked) until this process exits.
|
| 307 |
+
lock = hold_workdir(config.workdir) if config.snapshot_every else None # noqa: F841
|
| 308 |
+
previous = None
|
| 309 |
+
if resume:
|
| 310 |
+
previous = resumable_ledger(ledger_path, config.model_dump(mode="json"))
|
| 311 |
+
elif ledger_path.exists():
|
| 312 |
+
raise ValueError(
|
| 313 |
+
"Offline training already launched; use a new attempt directory"
|
| 314 |
+
)
|
| 315 |
+
ledger = {
|
| 316 |
+
"status": "running",
|
| 317 |
+
"started_epoch": time.time(),
|
| 318 |
+
"config": config.model_dump(mode="json"),
|
| 319 |
+
"official_args": asdict(args),
|
| 320 |
+
"provenance": provenance,
|
| 321 |
+
"entrypoint_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
|
| 322 |
+
"evaluation": "disabled here; real simulator evaluation is a separate job",
|
| 323 |
+
"success_metrics": None,
|
| 324 |
+
"resume": resume,
|
| 325 |
+
"software_versions": {
|
| 326 |
+
"python": sys.version.split()[0],
|
| 327 |
+
**{
|
| 328 |
+
name: importlib.metadata.version(name)
|
| 329 |
+
for name in (
|
| 330 |
+
"torch",
|
| 331 |
+
"torchvision",
|
| 332 |
+
"numpy",
|
| 333 |
+
"diffusers",
|
| 334 |
+
"gymnasium",
|
| 335 |
+
"mani-skill",
|
| 336 |
+
)
|
| 337 |
+
},
|
| 338 |
+
},
|
| 339 |
+
}
|
| 340 |
+
if previous is None:
|
| 341 |
+
ledger_path.write_text(json.dumps(ledger, indent=2))
|
| 342 |
+
|
| 343 |
+
# Same ordering as the pinned native trainer, including both Agent instances.
|
| 344 |
+
random.seed(args.seed)
|
| 345 |
+
np.random.seed(args.seed)
|
| 346 |
+
torch.manual_seed(args.seed)
|
| 347 |
+
torch.backends.cudnn.deterministic = args.torch_deterministic
|
| 348 |
+
dataset = native.SmallDemoDataset_ACTPolicy(
|
| 349 |
+
args.demo_path,
|
| 350 |
+
args.num_queries,
|
| 351 |
+
num_traj=args.num_demos,
|
| 352 |
+
include_depth=args.include_depth,
|
| 353 |
+
)
|
| 354 |
+
if config.policy.method == "chunk_relative":
|
| 355 |
+
dataset = ChunkRelativeDataset(
|
| 356 |
+
ChunkDatasetConfig(
|
| 357 |
+
dataset=dataset,
|
| 358 |
+
action_encoding=config.policy.action_encoding,
|
| 359 |
+
source=Path(args.demo_path),
|
| 360 |
+
chunk_anchor=config.policy.chunk_anchor,
|
| 361 |
+
phase_supervision=config.policy.has_chunk_phase_head,
|
| 362 |
+
chunk_pose_supervision=config.policy.chunk_pose_supervision,
|
| 363 |
+
chunk_gripper_supervision=config.policy.chunk_gripper_supervision,
|
| 364 |
+
chunk_padding=config.policy.chunk_padding,
|
| 365 |
+
chunk_normalization_population=config.policy.chunk_normalization_population,
|
| 366 |
+
chunk_label_offset=config.policy.chunk_label_offset,
|
| 367 |
+
chunk_waypoint_threshold_m=config.policy.chunk_waypoint_threshold_m,
|
| 368 |
+
switch_supervision=config.policy.chunk_switch_head,
|
| 369 |
+
)
|
| 370 |
+
)
|
| 371 |
+
if config.policy.action_encoding == "rotation6d":
|
| 372 |
+
ledger["action_target_contract"] = dataset.target_contract
|
| 373 |
+
if hasattr(dataset, "supervision_audit"):
|
| 374 |
+
ledger["supervision_audit"] = dataset.supervision_audit
|
| 375 |
+
elif config.policy.keypose is not None:
|
| 376 |
+
dataset = KeyposeDataset(
|
| 377 |
+
KeyposeDatasetConfig(
|
| 378 |
+
dataset=dataset,
|
| 379 |
+
source=Path(args.demo_path),
|
| 380 |
+
sampling=config.keypose_sampling,
|
| 381 |
+
phase_supervision=config.policy.keypose_phase_weight > 0,
|
| 382 |
+
context=config.policy.keypose_context,
|
| 383 |
+
stop_supervision=config.policy.keypose_stop_head,
|
| 384 |
+
)
|
| 385 |
+
)
|
| 386 |
+
(config.workdir / "sample-selection.json").write_text(
|
| 387 |
+
json.dumps(dataset.sample_selection, indent=2) + "\n"
|
| 388 |
+
)
|
| 389 |
+
ledger["sample_selection"] = {
|
| 390 |
+
k: v for k, v in dataset.sample_selection.items() if k != "trajectories"
|
| 391 |
+
}
|
| 392 |
+
if config.policy.keypose_stop_head:
|
| 393 |
+
ledger["stop_supervision"] = dataset.stop_label_summary
|
| 394 |
+
if config.policy.keypose_target_sequence == "future":
|
| 395 |
+
dataset = KeyposeSequenceDataset(
|
| 396 |
+
KeyposeSequenceDatasetConfig(dataset=dataset)
|
| 397 |
+
)
|
| 398 |
+
if config.policy.keypose_dense_head:
|
| 399 |
+
dataset = DenseAuxiliaryDataset(
|
| 400 |
+
DenseAuxiliaryDatasetConfig(
|
| 401 |
+
dataset=dataset,
|
| 402 |
+
source=Path(args.demo_path),
|
| 403 |
+
normalization=config.policy.normalization,
|
| 404 |
+
)
|
| 405 |
+
)
|
| 406 |
+
ledger["dense_aux_normalization"] = dataset.dense_statistics.model_dump(
|
| 407 |
+
mode="json"
|
| 408 |
+
)
|
| 409 |
+
else:
|
| 410 |
+
dataset = encode_dataset_actions(dataset, config.policy.action_encoding)
|
| 411 |
+
if config.policy.action_loss.method == "gripper_bce":
|
| 412 |
+
validate_binary_gripper(dataset)
|
| 413 |
+
if config.frozen_normalization is not None:
|
| 414 |
+
normalization, ledger["normalization_source"] = load_frozen_normalization(
|
| 415 |
+
config
|
| 416 |
+
)
|
| 417 |
+
else:
|
| 418 |
+
normalization = fit_normalization(
|
| 419 |
+
FitNormalizationConfig(
|
| 420 |
+
dataset=dataset,
|
| 421 |
+
normalization=config.policy.normalization,
|
| 422 |
+
action_encoding=config.policy.action_encoding,
|
| 423 |
+
source=Path(args.demo_path),
|
| 424 |
+
action_samples=dataset.normalization_actions
|
| 425 |
+
if config.policy.method == "chunk_relative"
|
| 426 |
+
and config.policy.action_encoding == "rotation6d"
|
| 427 |
+
else None,
|
| 428 |
+
)
|
| 429 |
+
)
|
| 430 |
+
if normalization is not None:
|
| 431 |
+
(config.workdir / "normalization.json").write_text(
|
| 432 |
+
normalization.model_dump_json(indent=2) + "\n"
|
| 433 |
+
)
|
| 434 |
+
dataset = NormalizedDataset(
|
| 435 |
+
NormalizedDatasetConfig(
|
| 436 |
+
dataset=dataset,
|
| 437 |
+
statistics=normalization,
|
| 438 |
+
)
|
| 439 |
+
)
|
| 440 |
+
if dataset.num_traj != args.num_demos or len(dataset) < args.batch_size:
|
| 441 |
+
raise ValueError("Incomplete demonstration count or no complete training batch")
|
| 442 |
+
sample = dataset[0]
|
| 443 |
+
if (
|
| 444 |
+
tuple(sample["observations"]["state"].shape)
|
| 445 |
+
!= spaces.single_observation_space["state"].shape
|
| 446 |
+
or tuple(sample["observations"]["rgb"].shape)
|
| 447 |
+
!= spaces.single_observation_space["rgb"].shape
|
| 448 |
+
or tuple(sample["actions"].shape)
|
| 449 |
+
!= (
|
| 450 |
+
args.num_queries,
|
| 451 |
+
encoded_dimension(
|
| 452 |
+
spaces.single_action_space.shape[-1], config.policy.action_encoding
|
| 453 |
+
),
|
| 454 |
+
)
|
| 455 |
+
):
|
| 456 |
+
raise ValueError(
|
| 457 |
+
"Real demonstration tensors disagree with the witnessed spaces"
|
| 458 |
+
)
|
| 459 |
+
generator = None
|
| 460 |
+
if config.sampler_seed is not None:
|
| 461 |
+
generator = torch.Generator().manual_seed(config.sampler_seed)
|
| 462 |
+
sampler = RandomSampler(dataset, replacement=False, generator=generator)
|
| 463 |
+
batches = BatchSampler(sampler, batch_size=args.batch_size, drop_last=True)
|
| 464 |
+
batches = native.IterationBasedBatchSampler(batches, args.total_iters)
|
| 465 |
+
loader = DataLoader(dataset, batch_sampler=batches, num_workers=0)
|
| 466 |
+
agent = build_policy(native, spaces, args, config.policy, normalization).cuda()
|
| 467 |
+
parameter_groups = [
|
| 468 |
+
{
|
| 469 |
+
"params": [
|
| 470 |
+
p
|
| 471 |
+
for n, p in agent.named_parameters()
|
| 472 |
+
if "backbone" not in n and p.requires_grad
|
| 473 |
+
]
|
| 474 |
+
},
|
| 475 |
+
{
|
| 476 |
+
"params": [
|
| 477 |
+
p
|
| 478 |
+
for n, p in agent.named_parameters()
|
| 479 |
+
if "backbone" in n and p.requires_grad
|
| 480 |
+
],
|
| 481 |
+
"lr": args.lr_backbone,
|
| 482 |
+
},
|
| 483 |
+
]
|
| 484 |
+
optimizer = torch.optim.AdamW(parameter_groups, lr=args.lr, weight_decay=1e-4)
|
| 485 |
+
scheduler = torch.optim.lr_scheduler.StepLR(
|
| 486 |
+
optimizer, int((2 / 3) * args.total_iters)
|
| 487 |
+
)
|
| 488 |
+
ema = EMAModel(parameters=agent.parameters(), power=0.75)
|
| 489 |
+
ema_agent = build_policy(native, spaces, args, config.policy, normalization).cuda()
|
| 490 |
+
agent.train()
|
| 491 |
+
objective = ACTTrainingObjective(config.optimization)
|
| 492 |
+
checkpoint_dir = config.workdir / "runs" / args.exp_name / "checkpoints"
|
| 493 |
+
checkpoint_dir.mkdir(parents=True, exist_ok=resume)
|
| 494 |
+
initial_hash = hashlib.sha256()
|
| 495 |
+
for name, tensor in agent.state_dict().items():
|
| 496 |
+
initial_hash.update(name.encode())
|
| 497 |
+
initial_hash.update(tensor.detach().cpu().contiguous().numpy().tobytes())
|
| 498 |
+
ledger.update(
|
| 499 |
+
initial_state_sha256=initial_hash.hexdigest(),
|
| 500 |
+
parameters=sum(p.numel() for p in agent.parameters()),
|
| 501 |
+
source_demonstrations=dataset.num_traj,
|
| 502 |
+
samples=len(dataset),
|
| 503 |
+
gpu=torch.cuda.get_device_name(),
|
| 504 |
+
normalization=normalization.model_dump(mode="json") if normalization else None,
|
| 505 |
+
)
|
| 506 |
+
if config.policy.keypose_stop_head:
|
| 507 |
+
ledger.update(
|
| 508 |
+
initial_original_state_sha256=original_state_sha256(agent),
|
| 509 |
+
initial_ema_original_state_sha256=original_state_sha256(ema_agent),
|
| 510 |
+
initial_torch_rng_sha256=hashlib.sha256(
|
| 511 |
+
torch.get_rng_state().numpy().tobytes()
|
| 512 |
+
).hexdigest(),
|
| 513 |
+
)
|
| 514 |
+
if config.policy.keypose_dense_head:
|
| 515 |
+
ledger["initial_primary_state_sha256"] = primary_state_sha256(agent)
|
| 516 |
+
ledger["initial_ema_primary_state_sha256"] = primary_state_sha256(ema_agent)
|
| 517 |
+
if previous is None:
|
| 518 |
+
ledger_path.write_text(json.dumps(ledger, indent=2))
|
| 519 |
+
print("OFFLINE_TRAIN_START", json.dumps(ledger), flush=True)
|
| 520 |
+
else:
|
| 521 |
+
check_rebuild(previous, ledger)
|
| 522 |
+
half = config.precision == "fp16"
|
| 523 |
+
scaler = torch.amp.GradScaler("cuda", enabled=half)
|
| 524 |
+
skipped = 0
|
| 525 |
+
parts = TrainingParts(
|
| 526 |
+
agent=agent,
|
| 527 |
+
optimizer=optimizer,
|
| 528 |
+
scheduler=scheduler,
|
| 529 |
+
ema=ema,
|
| 530 |
+
scaler=scaler,
|
| 531 |
+
sampler=generator,
|
| 532 |
+
objective=objective,
|
| 533 |
+
cuda=True,
|
| 534 |
+
)
|
| 535 |
+
metrics_path = config.workdir / "metrics.jsonl"
|
| 536 |
+
snapshot_dir = config.workdir / "resume"
|
| 537 |
+
iterator = iter(loader)
|
| 538 |
+
start, elapsed, replayed = 0, 0.0, {}
|
| 539 |
+
if previous is not None:
|
| 540 |
+
snapshot = load_snapshot(previous["resume_snapshot"])
|
| 541 |
+
start = snapshot["iteration"] + 1
|
| 542 |
+
advance(iterator, start)
|
| 543 |
+
check_replay(parts, snapshot)
|
| 544 |
+
restore(parts, snapshot)
|
| 545 |
+
skipped, elapsed = snapshot["skipped"], snapshot["elapsed_s"]
|
| 546 |
+
del snapshot
|
| 547 |
+
resumes = previous.get("resumes", [])
|
| 548 |
+
replayed = split_metrics(metrics_path, start)
|
| 549 |
+
# Rebuilt values equal the stored ones but keep their Python types, so
|
| 550 |
+
# records embedded in checkpoints pickle exactly as in the original run.
|
| 551 |
+
rebuilt = {k: v for k, v in ledger.items() if k not in VOLATILE_LEDGER_KEYS}
|
| 552 |
+
ledger = previous | rebuilt | {
|
| 553 |
+
"status": "running",
|
| 554 |
+
"resume": True,
|
| 555 |
+
"resumes": resumes
|
| 556 |
+
+ [
|
| 557 |
+
{
|
| 558 |
+
"from_updates": start,
|
| 559 |
+
"snapshot_sha256": previous["resume_snapshot"]["sha256"],
|
| 560 |
+
"started_epoch": time.time(),
|
| 561 |
+
"replayed_metric_rows": len(replayed),
|
| 562 |
+
"identical_metric_rows": 0,
|
| 563 |
+
}
|
| 564 |
+
],
|
| 565 |
+
}
|
| 566 |
+
ledger_path.write_text(json.dumps(ledger, indent=2))
|
| 567 |
+
print("OFFLINE_TRAIN_RESUME", json.dumps(ledger["resumes"][-1]), flush=True)
|
| 568 |
+
stop = StopRequest() if config.snapshot_every else None
|
| 569 |
+
started = time.monotonic() - elapsed
|
| 570 |
+
with metrics_path.open("a" if resume else "x") as metrics:
|
| 571 |
+
for iteration, data in enumerate(iterator, start=start):
|
| 572 |
+
obs = {
|
| 573 |
+
k: v.cuda(non_blocking=True) for k, v in data["observations"].items()
|
| 574 |
+
}
|
| 575 |
+
actions = data["actions"].cuda(non_blocking=True)
|
| 576 |
+
phase_labels = (
|
| 577 |
+
data["phase"].cuda(non_blocking=True) if "phase" in data else None
|
| 578 |
+
)
|
| 579 |
+
stop_labels = (
|
| 580 |
+
data["stop_after_target"].cuda(non_blocking=True)
|
| 581 |
+
if "stop_after_target" in data
|
| 582 |
+
else None
|
| 583 |
+
)
|
| 584 |
+
dense_labels = (
|
| 585 |
+
data["dense_actions"].cuda(non_blocking=True)
|
| 586 |
+
if "dense_actions" in data
|
| 587 |
+
else None
|
| 588 |
+
)
|
| 589 |
+
switch_labels = (
|
| 590 |
+
data["switch"].cuda(non_blocking=True) if "switch" in data else None
|
| 591 |
+
)
|
| 592 |
+
with torch.autocast("cuda", dtype=torch.float16, enabled=half):
|
| 593 |
+
losses = policy_loss(
|
| 594 |
+
agent,
|
| 595 |
+
native,
|
| 596 |
+
obs,
|
| 597 |
+
actions,
|
| 598 |
+
config.policy,
|
| 599 |
+
objective,
|
| 600 |
+
phase_labels,
|
| 601 |
+
stop_labels,
|
| 602 |
+
dense_labels,
|
| 603 |
+
switch_labels,
|
| 604 |
+
)
|
| 605 |
+
loss = losses["loss"]
|
| 606 |
+
if not torch.isfinite(loss):
|
| 607 |
+
raise FloatingPointError(f"Nonfinite training loss at {iteration}")
|
| 608 |
+
skipped += not optimizer_step(loss, optimizer, scaler)
|
| 609 |
+
if iteration == 0:
|
| 610 |
+
# Gradients survive the step; the next zero_grad releases them.
|
| 611 |
+
ledger["parameters_with_gradient"] = sum(
|
| 612 |
+
p.numel() for p in agent.parameters() if p.grad is not None
|
| 613 |
+
)
|
| 614 |
+
scheduler.step()
|
| 615 |
+
ema.step(agent.parameters())
|
| 616 |
+
if iteration % args.log_freq == 0 or iteration == args.total_iters - 1:
|
| 617 |
+
record = {
|
| 618 |
+
"iteration": iteration,
|
| 619 |
+
"updates": iteration + 1,
|
| 620 |
+
"loss": loss.item(),
|
| 621 |
+
**{
|
| 622 |
+
key: value.item()
|
| 623 |
+
for key, value in losses.items()
|
| 624 |
+
if key != "loss"
|
| 625 |
+
},
|
| 626 |
+
"elapsed_s": time.monotonic() - started,
|
| 627 |
+
"epoch": time.time(),
|
| 628 |
+
"lr": optimizer.param_groups[0]["lr"],
|
| 629 |
+
**(
|
| 630 |
+
{"loss_scale": scaler.get_scale(), "skipped_updates": skipped}
|
| 631 |
+
if half
|
| 632 |
+
else {}
|
| 633 |
+
),
|
| 634 |
+
}
|
| 635 |
+
if iteration in replayed:
|
| 636 |
+
ledger["resumes"][-1]["identical_metric_rows"] += same_metrics(
|
| 637 |
+
record, replayed[iteration]
|
| 638 |
+
)
|
| 639 |
+
metrics.write(json.dumps(record) + "\n")
|
| 640 |
+
metrics.flush()
|
| 641 |
+
print("OFFLINE_UPDATE", json.dumps(record), flush=True)
|
| 642 |
+
if iteration % args.save_freq == 0:
|
| 643 |
+
ema.copy_to(ema_agent.parameters())
|
| 644 |
+
torch.save(
|
| 645 |
+
{
|
| 646 |
+
"norm_stats": dataset.norm_stats,
|
| 647 |
+
"agent": agent.state_dict(),
|
| 648 |
+
"ema_agent": ema_agent.state_dict(),
|
| 649 |
+
"policy": config.policy.model_dump(mode="json"),
|
| 650 |
+
"num_queries": args.num_queries,
|
| 651 |
+
"control_mode": args.control_mode,
|
| 652 |
+
"normalization": normalization.model_dump(mode="json")
|
| 653 |
+
if normalization
|
| 654 |
+
else None,
|
| 655 |
+
"normalization_source": ledger.get("normalization_source"),
|
| 656 |
+
"training_sample_selection": ledger.get("sample_selection"),
|
| 657 |
+
"action_target_contract": ledger.get("action_target_contract"),
|
| 658 |
+
"supervision_audit": ledger.get("supervision_audit"),
|
| 659 |
+
**(
|
| 660 |
+
{"stop_supervision": ledger["stop_supervision"]}
|
| 661 |
+
if config.policy.keypose_stop_head
|
| 662 |
+
else {}
|
| 663 |
+
),
|
| 664 |
+
**({"training_precision": "fp16"} if half else {}),
|
| 665 |
+
**(
|
| 666 |
+
{
|
| 667 |
+
"dense_aux_normalization": ledger[
|
| 668 |
+
"dense_aux_normalization"
|
| 669 |
+
]
|
| 670 |
+
}
|
| 671 |
+
if config.policy.keypose_dense_head
|
| 672 |
+
else {}
|
| 673 |
+
),
|
| 674 |
+
},
|
| 675 |
+
checkpoint_dir / f"{iteration}.pt",
|
| 676 |
+
)
|
| 677 |
+
if stop is None or iteration == args.total_iters - 1:
|
| 678 |
+
continue
|
| 679 |
+
stopping = stop.requested # Read once: a later signal waits one update.
|
| 680 |
+
if stopping or (iteration + 1) % config.snapshot_every == 0:
|
| 681 |
+
old = ledger.get("resume_snapshot")
|
| 682 |
+
ledger["resume_snapshot"] = save_snapshot(
|
| 683 |
+
snapshot_dir,
|
| 684 |
+
capture(parts, iteration, skipped, time.monotonic() - started),
|
| 685 |
+
)
|
| 686 |
+
ledger_path.write_text(json.dumps(ledger, indent=2))
|
| 687 |
+
if old is not None and old["path"] != ledger["resume_snapshot"]["path"]:
|
| 688 |
+
Path(old["path"]).unlink()
|
| 689 |
+
if stopping:
|
| 690 |
+
ledger.update(status="interrupted", interrupted_epoch=time.time())
|
| 691 |
+
ledger_path.write_text(json.dumps(ledger, indent=2))
|
| 692 |
+
print("OFFLINE_TRAIN_INTERRUPTED", json.dumps(ledger["resume_snapshot"]), flush=True)
|
| 693 |
+
raise SystemExit(128 + signal.SIGTERM)
|
| 694 |
+
if iteration != args.total_iters - 1:
|
| 695 |
+
raise RuntimeError("Native sampler did not complete the declared update budget")
|
| 696 |
+
final = checkpoint_dir / f"{iteration}.pt"
|
| 697 |
+
ledger.update(
|
| 698 |
+
status="complete",
|
| 699 |
+
ended_epoch=time.time(),
|
| 700 |
+
updates=iteration + 1,
|
| 701 |
+
final_checkpoint=str(final),
|
| 702 |
+
final_checkpoint_sha256=hashlib.sha256(final.read_bytes()).hexdigest(),
|
| 703 |
+
**({"skipped_updates": skipped} if half else {}),
|
| 704 |
+
)
|
| 705 |
+
if "resume_snapshot" in ledger:
|
| 706 |
+
# Only an unfinished run can use it; the record stays in the ledger.
|
| 707 |
+
ledger["resume_snapshot"]["removed_at_completion"] = True
|
| 708 |
+
ledger_path.write_text(json.dumps(ledger, indent=2))
|
| 709 |
+
if "resume_snapshot" in ledger:
|
| 710 |
+
Path(ledger["resume_snapshot"]["path"]).unlink()
|
| 711 |
+
print("OFFLINE_TRAIN_COMPLETE", json.dumps(ledger), flush=True)
|
| 712 |
+
|
| 713 |
+
|
| 714 |
+
if __name__ == "__main__":
|
| 715 |
+
cli = CliApp.run(OfflineTrainCLI)
|
| 716 |
+
run(OfflineTrainConfig.model_validate_json(cli.spec.read_text()), cli.resume)
|
fair-comparison/p3x-liftslow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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exact resumption of offline ACT training from a full training snapshot.
|
| 2 |
+
|
| 3 |
+
A snapshot holds every state the update loop mutates: model, optimizer,
|
| 4 |
+
scheduler, EMA, fp16 loss scaler, the skipped-update count and all RNG streams.
|
| 5 |
+
The batch sampler's position lives in generator frames that cannot be saved, so
|
| 6 |
+
a resume rebuilds the loader exactly as the original run did, replays only the
|
| 7 |
+
batch indices of the completed updates, checks that the replay landed where the
|
| 8 |
+
original stopped, and then restores the saved state. Capturing a snapshot reads
|
| 9 |
+
but never draws from any RNG, so continuous training is unchanged.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import fcntl
|
| 13 |
+
import hashlib
|
| 14 |
+
import json
|
| 15 |
+
import random
|
| 16 |
+
import signal
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from typing import Any
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import torch
|
| 22 |
+
from pydantic import BaseModel, ConfigDict
|
| 23 |
+
from torch.utils.data.dataloader import _SingleProcessDataLoaderIter
|
| 24 |
+
|
| 25 |
+
SNAPSHOT_VERSION = 1
|
| 26 |
+
VOLATILE_LEDGER_KEYS = ("status", "started_epoch", "resume")
|
| 27 |
+
"""Ledger fields that legitimately differ between the original and resumed setup."""
|
| 28 |
+
WALL_CLOCK_METRICS = ("elapsed_s", "epoch")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class TrainingParts(BaseModel, frozen=True):
|
| 32 |
+
model_config = ConfigDict(
|
| 33 |
+
arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
|
| 34 |
+
)
|
| 35 |
+
agent: torch.nn.Module
|
| 36 |
+
optimizer: torch.optim.Optimizer
|
| 37 |
+
scheduler: Any
|
| 38 |
+
"""Learning-rate scheduler with state_dict/load_state_dict."""
|
| 39 |
+
ema: Any
|
| 40 |
+
"""diffusers EMAModel tracking the agent parameters."""
|
| 41 |
+
scaler: torch.amp.GradScaler
|
| 42 |
+
sampler: torch.Generator | None
|
| 43 |
+
"""Private batch-order generator; None for the legacy global-RNG order."""
|
| 44 |
+
objective: Any
|
| 45 |
+
"""Training objective; its lazily created private generator is saved too."""
|
| 46 |
+
cuda: bool
|
| 47 |
+
"""Save the CUDA RNG of the current device (dropout and CVAE noise)."""
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def file_sha256(path):
|
| 51 |
+
with Path(path).open("rb") as stream:
|
| 52 |
+
return hashlib.file_digest(stream, "sha256").hexdigest()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def rng_state(parts: TrainingParts):
|
| 56 |
+
generator = parts.objective.generator
|
| 57 |
+
return {
|
| 58 |
+
"python": random.getstate(),
|
| 59 |
+
"numpy": np.random.get_state(),
|
| 60 |
+
"torch": torch.get_rng_state(),
|
| 61 |
+
"cuda": torch.cuda.get_rng_state() if parts.cuda else None,
|
| 62 |
+
"sampler": None if parts.sampler is None else parts.sampler.get_state(),
|
| 63 |
+
"objective": None
|
| 64 |
+
if generator is None
|
| 65 |
+
else {"device": str(generator.device), "state": generator.get_state()},
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def set_rng_state(parts: TrainingParts, state):
|
| 70 |
+
random.setstate(state["python"])
|
| 71 |
+
np.random.set_state(state["numpy"])
|
| 72 |
+
torch.set_rng_state(state["torch"])
|
| 73 |
+
if parts.cuda:
|
| 74 |
+
torch.cuda.set_rng_state(state["cuda"])
|
| 75 |
+
if parts.sampler is not None:
|
| 76 |
+
parts.sampler.set_state(state["sampler"])
|
| 77 |
+
if state["objective"] is not None:
|
| 78 |
+
generator = torch.Generator(device=state["objective"]["device"])
|
| 79 |
+
generator.set_state(state["objective"]["state"])
|
| 80 |
+
parts.objective.generator = generator
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def capture(parts: TrainingParts, iteration, skipped, elapsed_s):
|
| 84 |
+
"""State after update ``iteration``, before the loader fetches the next batch."""
|
| 85 |
+
return {
|
| 86 |
+
"version": SNAPSHOT_VERSION,
|
| 87 |
+
"iteration": iteration,
|
| 88 |
+
"skipped": skipped,
|
| 89 |
+
"elapsed_s": elapsed_s,
|
| 90 |
+
"agent": parts.agent.state_dict(),
|
| 91 |
+
"optimizer": parts.optimizer.state_dict(),
|
| 92 |
+
"scheduler": parts.scheduler.state_dict(),
|
| 93 |
+
"ema": parts.ema.state_dict(),
|
| 94 |
+
"scaler": parts.scaler.state_dict(),
|
| 95 |
+
"rng": rng_state(parts),
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def save_snapshot(directory: Path, state):
|
| 100 |
+
"""Atomic write; the returned record is what the ledger pins."""
|
| 101 |
+
directory.mkdir(exist_ok=True)
|
| 102 |
+
updates = state["iteration"] + 1
|
| 103 |
+
path = directory / f"{updates}.pt"
|
| 104 |
+
partial = path.with_suffix(".partial")
|
| 105 |
+
torch.save(state, partial)
|
| 106 |
+
partial.replace(path)
|
| 107 |
+
return {"updates": updates, "path": str(path), "sha256": file_sha256(path)}
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def load_snapshot(record):
|
| 111 |
+
if file_sha256(record["path"]) != record["sha256"]:
|
| 112 |
+
raise ValueError("Training snapshot identity differs from the ledger record")
|
| 113 |
+
state = torch.load(record["path"], map_location="cpu", weights_only=False)
|
| 114 |
+
if state["version"] != SNAPSHOT_VERSION or state["iteration"] + 1 != record["updates"]:
|
| 115 |
+
raise ValueError("Training snapshot does not match its ledger record")
|
| 116 |
+
return state
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def advance(iterator, batches):
|
| 120 |
+
"""Consume the batch indices of completed updates without loading samples."""
|
| 121 |
+
if type(iterator) is not _SingleProcessDataLoaderIter:
|
| 122 |
+
raise ValueError("Replay supports the single-process loader only")
|
| 123 |
+
for _ in range(batches):
|
| 124 |
+
iterator._next_index()
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def check_replay(parts: TrainingParts, state):
|
| 128 |
+
"""The replayed batch order must stand exactly where the original run stopped."""
|
| 129 |
+
rng = state["rng"]
|
| 130 |
+
if parts.sampler is not None:
|
| 131 |
+
if not torch.equal(parts.sampler.get_state(), rng["sampler"]):
|
| 132 |
+
raise ValueError("Replayed batch sampler differs from the snapshot")
|
| 133 |
+
elif not torch.equal(torch.get_rng_state(), rng["torch"]):
|
| 134 |
+
# Legacy order draws each epoch's seed from the global RNG; equal state
|
| 135 |
+
# proves the loop drew from it nothing but those seeds.
|
| 136 |
+
raise ValueError(
|
| 137 |
+
"Legacy batch order shares the global RNG with the update loop; "
|
| 138 |
+
"this run cannot be resumed exactly"
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def restore(parts: TrainingParts, state):
|
| 143 |
+
parts.agent.load_state_dict(state["agent"])
|
| 144 |
+
parts.optimizer.load_state_dict(state["optimizer"])
|
| 145 |
+
parts.scheduler.load_state_dict(state["scheduler"])
|
| 146 |
+
parts.ema.load_state_dict(state["ema"])
|
| 147 |
+
parts.ema.to(device=next(parts.agent.parameters()).device)
|
| 148 |
+
parts.scaler.load_state_dict(state["scaler"])
|
| 149 |
+
set_rng_state(parts, state["rng"])
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class StopRequest:
|
| 153 |
+
"""SIGTERM asks the loop to snapshot the current update and exit."""
|
| 154 |
+
|
| 155 |
+
def __init__(self):
|
| 156 |
+
self.requested = False
|
| 157 |
+
signal.signal(signal.SIGTERM, self.request)
|
| 158 |
+
|
| 159 |
+
def request(self, signum, frame):
|
| 160 |
+
self.requested = True
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def hold_workdir(workdir: Path):
|
| 164 |
+
"""Exclusive for the process lifetime, so a resume cannot race a live attempt."""
|
| 165 |
+
lock = (workdir / "training.lock").open("a")
|
| 166 |
+
try:
|
| 167 |
+
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 168 |
+
except BlockingIOError:
|
| 169 |
+
lock.close()
|
| 170 |
+
raise ValueError("Another process is training in this directory") from None
|
| 171 |
+
return lock
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def resumable_ledger(path: Path, config):
|
| 175 |
+
"""The unfinished original ledger, if it may continue under ``config``."""
|
| 176 |
+
ledger = json.loads(path.read_text())
|
| 177 |
+
if ledger["status"] not in ("running", "interrupted"):
|
| 178 |
+
raise ValueError("Only an unfinished training can resume")
|
| 179 |
+
if ledger["config"] != config:
|
| 180 |
+
raise ValueError("Resume requires the identical training specification")
|
| 181 |
+
if "resume_snapshot" not in ledger:
|
| 182 |
+
raise ValueError("No completed snapshot; launch a new attempt directory")
|
| 183 |
+
return ledger
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def check_rebuild(previous, fresh):
|
| 187 |
+
"""Every deterministic setup record must reproduce before state is restored."""
|
| 188 |
+
for key, value in fresh.items():
|
| 189 |
+
if key not in VOLATILE_LEDGER_KEYS and json.loads(json.dumps(value)) != previous.get(key):
|
| 190 |
+
raise ValueError(f"Resumed setup differs from the original run: {key}")
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def split_metrics(path: Path, updates):
|
| 194 |
+
"""Keep rows of completed updates; set aside rows the resume recomputes.
|
| 195 |
+
|
| 196 |
+
Every attempt's original file is preserved under the next free number. A final
|
| 197 |
+
line cut off by a hard kill is dropped.
|
| 198 |
+
"""
|
| 199 |
+
lines = path.read_text().splitlines()
|
| 200 |
+
rows = []
|
| 201 |
+
for number, line in enumerate(lines):
|
| 202 |
+
try:
|
| 203 |
+
rows.append((line, json.loads(line)))
|
| 204 |
+
except json.JSONDecodeError:
|
| 205 |
+
if number != len(lines) - 1:
|
| 206 |
+
raise
|
| 207 |
+
attempt = len(list(path.parent.glob("metrics-before-resume*.jsonl")))
|
| 208 |
+
path.rename(path.with_name(f"metrics-before-resume{attempt}.jsonl"))
|
| 209 |
+
path.write_text("".join(line + "\n" for line, row in rows if row["iteration"] < updates))
|
| 210 |
+
return {row["iteration"]: row for _, row in rows if row["iteration"] >= updates}
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def same_metrics(record, old):
|
| 214 |
+
"""Recomputed values equal the interrupted attempt's, wall clock aside."""
|
| 215 |
+
|
| 216 |
+
def strip(row):
|
| 217 |
+
return {k: v for k, v in row.items() if k not in WALL_CLOCK_METRICS}
|
| 218 |
+
|
| 219 |
+
return strip(record) == strip(old)
|
fair-comparison/p3x-liftslow-v1/code/lim/waypoints.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""AWE-style waypoint selection on dense controller targets.
|
| 2 |
+
|
| 3 |
+
Shi et al. (CoRL 2023) choose the fewest waypoints such that linear
|
| 4 |
+
interpolation between consecutive waypoints stays within a distance threshold
|
| 5 |
+
of every intermediate state, by dynamic programming. Here the states are the
|
| 6 |
+
dense controller target positions of one demonstration; gripper command
|
| 7 |
+
changes are forced waypoints so no interpolated segment spans a gripper event.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from itertools import pairwise
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def segment_error(points: np.ndarray, start: int, end: int) -> float:
|
| 16 |
+
"""Largest distance from points[start+1:end] to the segment start->end."""
|
| 17 |
+
if end - start < 2:
|
| 18 |
+
return 0.0
|
| 19 |
+
a, b = points[start], points[end]
|
| 20 |
+
inner = points[start + 1 : end]
|
| 21 |
+
direction = b - a
|
| 22 |
+
length = float(direction @ direction)
|
| 23 |
+
if length == 0.0:
|
| 24 |
+
return float(np.linalg.norm(inner - a, axis=1).max())
|
| 25 |
+
t = np.clip((inner - a) @ direction / length, 0.0, 1.0)
|
| 26 |
+
return float(np.linalg.norm(inner - (a + t[:, None] * direction), axis=1).max())
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _piece(points, start, end, threshold):
|
| 30 |
+
"""Fewest waypoints in (start, end] covering points[start..end]."""
|
| 31 |
+
cost = {start: 0}
|
| 32 |
+
previous = {}
|
| 33 |
+
for i in range(start + 1, end + 1):
|
| 34 |
+
best = None
|
| 35 |
+
for j in range(i - 1, start - 1, -1):
|
| 36 |
+
if j not in cost or segment_error(points, j, i) > threshold:
|
| 37 |
+
continue
|
| 38 |
+
if best is None or cost[j] + 1 < best[0]:
|
| 39 |
+
best = (cost[j] + 1, j)
|
| 40 |
+
# Adjacent points are always a valid segment, so best exists.
|
| 41 |
+
cost[i], previous[i] = best
|
| 42 |
+
chosen, i = [], end
|
| 43 |
+
while i != start:
|
| 44 |
+
chosen.append(i)
|
| 45 |
+
i = previous[i]
|
| 46 |
+
return sorted(chosen)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def select_waypoints(positions, threshold: float, gripper=None) -> np.ndarray:
|
| 50 |
+
"""Waypoint indices into positions (n x d), always including n-1.
|
| 51 |
+
|
| 52 |
+
Index 0 is the start anchor, not a waypoint. Where the gripper command
|
| 53 |
+
changes between i-1 and i, both i-1 and i are forced waypoints.
|
| 54 |
+
"""
|
| 55 |
+
points = np.asarray(positions, dtype=np.float64)
|
| 56 |
+
if points.ndim != 2 or len(points) < 1 or not np.isfinite(points).all():
|
| 57 |
+
raise ValueError("Expected a finite n x d position array")
|
| 58 |
+
if threshold <= 0:
|
| 59 |
+
raise ValueError("Waypoint threshold must be positive")
|
| 60 |
+
n = len(points)
|
| 61 |
+
anchors = {0, n - 1}
|
| 62 |
+
if gripper is not None:
|
| 63 |
+
command = np.asarray(gripper)
|
| 64 |
+
if command.shape != (n,):
|
| 65 |
+
raise ValueError("Gripper commands must align with positions")
|
| 66 |
+
for i in np.flatnonzero(command[1:] != command[:-1]) + 1:
|
| 67 |
+
anchors.update((int(i) - 1, int(i)))
|
| 68 |
+
anchors = sorted(anchors)
|
| 69 |
+
if n == 1:
|
| 70 |
+
return np.array([0], dtype=np.int64)
|
| 71 |
+
chosen = set(anchors[1:])
|
| 72 |
+
for start, end in pairwise(anchors):
|
| 73 |
+
chosen.update(_piece(points, start, end, threshold))
|
| 74 |
+
return np.array(sorted(chosen), dtype=np.int64)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def next_waypoint(length: int, waypoints) -> np.ndarray:
|
| 78 |
+
"""For each action time t, the first waypoint strictly after t (last maps to itself)."""
|
| 79 |
+
points = np.asarray(waypoints, dtype=np.int64)
|
| 80 |
+
if len(points) == 0 or points[-1] != length - 1 or np.any(np.diff(points) <= 0):
|
| 81 |
+
raise ValueError("Waypoints must be increasing and end at the last action")
|
| 82 |
+
index = np.searchsorted(points, np.arange(length), side="right")
|
| 83 |
+
return points[np.minimum(index, len(points) - 1)]
|
fair-comparison/p3x-liftslow-v1/runs/dense-q50-u90k-n100_liftslow-s100/reference.json
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"mode": "evaluate",
|
| 3 |
+
"source": "third_party/ManiSkill/examples/baselines/act/train_rgbd.py",
|
| 4 |
+
"checkpoint": "/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/runs/dense-q50-u90k-n100_liftslow-s100/train/runs/fair-dense-q50-u90k-n100_liftslow-s100/checkpoints/89999.pt",
|
| 5 |
+
"output_dir": "/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/runs/dense-q50-u90k-n100_liftslow-s100/unused",
|
| 6 |
+
"episodes": 60,
|
| 7 |
+
"num_envs": 10,
|
| 8 |
+
"seed_start": 54000,
|
| 9 |
+
"observations": null,
|
| 10 |
+
"iterations": 500,
|
| 11 |
+
"demonstration_metadata": "/home/ghz/Work/Research/lim/artifacts/keypose-data/LiftPegUprightWristcam-slow/pose/trajectory.json",
|
| 12 |
+
"architecture": {
|
| 13 |
+
"hidden_dim": 256,
|
| 14 |
+
"dim_feedforward": 512,
|
| 15 |
+
"enc_layers": 2,
|
| 16 |
+
"dec_layers": 4
|
| 17 |
+
},
|
| 18 |
+
"policy": {
|
| 19 |
+
"method": "chunk_relative",
|
| 20 |
+
"action_encoding": "rotation6d",
|
| 21 |
+
"chunk_anchor": "chunk_start_tcp",
|
| 22 |
+
"chunk_pose_supervision": "dense",
|
| 23 |
+
"chunk_gripper_supervision": "future",
|
| 24 |
+
"chunk_padding": "terminal",
|
| 25 |
+
"chunk_normalization_population": "dense",
|
| 26 |
+
"chunk_label_offset": 0,
|
| 27 |
+
"chunk_waypoint_threshold_m": null,
|
| 28 |
+
"chunk_switch_head": false,
|
| 29 |
+
"chunk_switch_weight": 1.0,
|
| 30 |
+
"flow_steps": 8,
|
| 31 |
+
"inference_seed": 20260916,
|
| 32 |
+
"normalization": {
|
| 33 |
+
"method": "action_zscore",
|
| 34 |
+
"state_floor": [
|
| 35 |
+
0.01,
|
| 36 |
+
0.01,
|
| 37 |
+
0.01,
|
| 38 |
+
0.01,
|
| 39 |
+
0.01,
|
| 40 |
+
0.01,
|
| 41 |
+
0.01,
|
| 42 |
+
0.001,
|
| 43 |
+
0.001,
|
| 44 |
+
0.01,
|
| 45 |
+
0.01,
|
| 46 |
+
0.01,
|
| 47 |
+
0.01,
|
| 48 |
+
0.01,
|
| 49 |
+
0.01,
|
| 50 |
+
0.01,
|
| 51 |
+
0.001,
|
| 52 |
+
0.001,
|
| 53 |
+
0.001,
|
| 54 |
+
0.001,
|
| 55 |
+
0.001,
|
| 56 |
+
0.01,
|
| 57 |
+
0.01,
|
| 58 |
+
0.01,
|
| 59 |
+
0.01
|
| 60 |
+
],
|
| 61 |
+
"action_floor": 0.01
|
| 62 |
+
},
|
| 63 |
+
"state_input": "full",
|
| 64 |
+
"action_loss": {
|
| 65 |
+
"method": "group_balanced",
|
| 66 |
+
"position_axis_weights": [
|
| 67 |
+
1.0,
|
| 68 |
+
1.0,
|
| 69 |
+
1.0
|
| 70 |
+
]
|
| 71 |
+
},
|
| 72 |
+
"keypose": null,
|
| 73 |
+
"keypose_phase_weight": 0.0,
|
| 74 |
+
"keypose_target_sequence": "current",
|
| 75 |
+
"keypose_context": "none",
|
| 76 |
+
"keypose_stop_head": false,
|
| 77 |
+
"keypose_stop_weight": 0.1,
|
| 78 |
+
"keypose_dense_head": false,
|
| 79 |
+
"keypose_dense_weight": 1.0,
|
| 80 |
+
"chunk_phase_head": false,
|
| 81 |
+
"chunk_phase_weight": 0.0
|
| 82 |
+
},
|
| 83 |
+
"num_queries": 50,
|
| 84 |
+
"video_seeds": [],
|
| 85 |
+
"keypose_trace": false,
|
| 86 |
+
"control_mode": "pd_ee_delta_pose",
|
| 87 |
+
"gripper_execution": {
|
| 88 |
+
"aggregation": "native",
|
| 89 |
+
"binary": false,
|
| 90 |
+
"trace": false
|
| 91 |
+
}
|
| 92 |
+
}
|
fair-comparison/p3x-liftslow-v1/runs/dense-q50-u90k-n100_liftslow-s100/train-spec.json
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"workdir": "/home/ghz/Work/Research/lim/artifacts/fair-comparison/p3x-liftslow-v1/runs/dense-q50-u90k-n100_liftslow-s100/train",
|
| 3 |
+
"official_arguments": [
|
| 4 |
+
"--env-id",
|
| 5 |
+
"LiftPegUprightWristcam-v1",
|
| 6 |
+
"--no-include-depth",
|
| 7 |
+
"--demo-path",
|
| 8 |
+
"/home/ghz/Work/Research/lim/artifacts/keypose-data/LiftPegUprightWristcam-slow/pose/trajectory.h5",
|
| 9 |
+
"--control-mode",
|
| 10 |
+
"pd_ee_delta_pose",
|
| 11 |
+
"--sim-backend",
|
| 12 |
+
"physx_cpu",
|
| 13 |
+
"--num-demos",
|
| 14 |
+
"100",
|
| 15 |
+
"--max-episode-steps",
|
| 16 |
+
"200",
|
| 17 |
+
"--total-iters",
|
| 18 |
+
"90000",
|
| 19 |
+
"--batch-size",
|
| 20 |
+
"256",
|
| 21 |
+
"--log-freq",
|
| 22 |
+
"100",
|
| 23 |
+
"--eval-freq",
|
| 24 |
+
"90000",
|
| 25 |
+
"--save-freq",
|
| 26 |
+
"89999",
|
| 27 |
+
"--num-eval-envs",
|
| 28 |
+
"10",
|
| 29 |
+
"--num-eval-episodes",
|
| 30 |
+
"10",
|
| 31 |
+
"--no-capture-video",
|
| 32 |
+
"--exp-name",
|
| 33 |
+
"fair-dense-q50-u90k-n100_liftslow-s100",
|
| 34 |
+
"--seed",
|
| 35 |
+
"100",
|
| 36 |
+
"--num-queries",
|
| 37 |
+
"50"
|
| 38 |
+
],
|
| 39 |
+
"witness": "/home/ghz/Work/Research/lim/artifacts/fair-comparison/witness/LiftPegUprightWristcam-v1/result.json",
|
| 40 |
+
"witness_sha256": "37b2bc44653bcabd4d7c13e1ea695b0ba76618472411f87ed1840d6ac3684c22",
|
| 41 |
+
"optimization": {
|
| 42 |
+
"method": "control",
|
| 43 |
+
"shift_pixels": 4,
|
| 44 |
+
"horizon_decay": 10.0,
|
| 45 |
+
"augmentation_seed": 20260915
|
| 46 |
+
},
|
| 47 |
+
"policy": {
|
| 48 |
+
"method": "chunk_relative",
|
| 49 |
+
"action_encoding": "rotation6d",
|
| 50 |
+
"chunk_anchor": "chunk_start_tcp",
|
| 51 |
+
"chunk_pose_supervision": "dense",
|
| 52 |
+
"chunk_gripper_supervision": "future",
|
| 53 |
+
"chunk_padding": "terminal",
|
| 54 |
+
"chunk_normalization_population": "dense",
|
| 55 |
+
"chunk_label_offset": 0,
|
| 56 |
+
"chunk_waypoint_threshold_m": null,
|
| 57 |
+
"chunk_switch_head": false,
|
| 58 |
+
"chunk_switch_weight": 1.0,
|
| 59 |
+
"flow_steps": 8,
|
| 60 |
+
"inference_seed": 20260916,
|
| 61 |
+
"normalization": {
|
| 62 |
+
"method": "action_zscore",
|
| 63 |
+
"state_floor": [
|
| 64 |
+
0.01,
|
| 65 |
+
0.01,
|
| 66 |
+
0.01,
|
| 67 |
+
0.01,
|
| 68 |
+
0.01,
|
| 69 |
+
0.01,
|
| 70 |
+
0.01,
|
| 71 |
+
0.001,
|
| 72 |
+
0.001,
|
| 73 |
+
0.01,
|
| 74 |
+
0.01,
|
| 75 |
+
0.01,
|
| 76 |
+
0.01,
|
| 77 |
+
0.01,
|
| 78 |
+
0.01,
|
| 79 |
+
0.01,
|
| 80 |
+
0.001,
|
| 81 |
+
0.001,
|
| 82 |
+
0.001,
|
| 83 |
+
0.001,
|
| 84 |
+
0.001,
|
| 85 |
+
0.01,
|
| 86 |
+
0.01,
|
| 87 |
+
0.01,
|
| 88 |
+
0.01
|
| 89 |
+
],
|
| 90 |
+
"action_floor": 0.01
|
| 91 |
+
},
|
| 92 |
+
"state_input": "full",
|
| 93 |
+
"action_loss": {
|
| 94 |
+
"method": "group_balanced",
|
| 95 |
+
"position_axis_weights": [
|
| 96 |
+
1.0,
|
| 97 |
+
1.0,
|
| 98 |
+
1.0
|
| 99 |
+
]
|
| 100 |
+
},
|
| 101 |
+
"keypose": null,
|
| 102 |
+
"keypose_phase_weight": 0.0,
|
| 103 |
+
"keypose_target_sequence": "current",
|
| 104 |
+
"keypose_context": "none",
|
| 105 |
+
"keypose_stop_head": false,
|
| 106 |
+
"keypose_stop_weight": 0.1,
|
| 107 |
+
"keypose_dense_head": false,
|
| 108 |
+
"keypose_dense_weight": 1.0,
|
| 109 |
+
"chunk_phase_head": false,
|
| 110 |
+
"chunk_phase_weight": 0.0
|
| 111 |
+
},
|
| 112 |
+
"sampler_seed": 100,
|
| 113 |
+
"keypose_sampling": {
|
| 114 |
+
"gripper_initial_only": false,
|
| 115 |
+
"motion_endpoint_radius_m": 0.0
|
| 116 |
+
},
|
| 117 |
+
"frozen_normalization": null,
|
| 118 |
+
"precision": "fp32",
|
| 119 |
+
"snapshot_every": null
|
| 120 |
+
}
|
fair-comparison/p3x-liftslow-v1/runs/dense-q50-u90k-n100_liftslow-s100/train/metrics.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
fair-comparison/p3x-liftslow-v1/runs/dense-q50-u90k-n100_liftslow-s100/train/normalization.json
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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0.001,
|
| 25 |
+
0.001,
|
| 26 |
+
0.01,
|
| 27 |
+
0.01,
|
| 28 |
+
0.01,
|
| 29 |
+
0.01
|
| 30 |
+
],
|
| 31 |
+
"action_floor": 0.01
|
| 32 |
+
},
|
| 33 |
+
"action_encoding": "rotation6d",
|
| 34 |
+
"source_sha256": "dfb7b1a424a12a219648e9f24cde45c3dcc099897ecad5171948317907f7c0d3",
|
| 35 |
+
"trajectories": 100,
|
| 36 |
+
"samples": 932150,
|
| 37 |
+
"state": {
|
| 38 |
+
"center": [
|
| 39 |
+
0.0,
|
| 40 |
+
0.0,
|
| 41 |
+
0.0,
|
| 42 |
+
0.0,
|
| 43 |
+
0.0,
|
| 44 |
+
0.0,
|
| 45 |
+
0.0,
|
| 46 |
+
0.0,
|
| 47 |
+
0.0,
|
| 48 |
+
0.0,
|
| 49 |
+
0.0,
|
| 50 |
+
0.0,
|
| 51 |
+
0.0,
|
| 52 |
+
0.0,
|
| 53 |
+
0.0,
|
| 54 |
+
0.0,
|
| 55 |
+
0.0,
|
| 56 |
+
0.0,
|
| 57 |
+
0.0,
|
| 58 |
+
0.0,
|
| 59 |
+
0.0,
|
| 60 |
+
0.0,
|
| 61 |
+
0.0,
|
| 62 |
+
0.0,
|
| 63 |
+
0.0
|
| 64 |
+
],
|
| 65 |
+
"scale": [
|
| 66 |
+
1.0,
|
| 67 |
+
1.0,
|
| 68 |
+
1.0,
|
| 69 |
+
1.0,
|
| 70 |
+
1.0,
|
| 71 |
+
1.0,
|
| 72 |
+
1.0,
|
| 73 |
+
1.0,
|
| 74 |
+
1.0,
|
| 75 |
+
1.0,
|
| 76 |
+
1.0,
|
| 77 |
+
1.0,
|
| 78 |
+
1.0,
|
| 79 |
+
1.0,
|
| 80 |
+
1.0,
|
| 81 |
+
1.0,
|
| 82 |
+
1.0,
|
| 83 |
+
1.0,
|
| 84 |
+
1.0,
|
| 85 |
+
1.0,
|
| 86 |
+
1.0,
|
| 87 |
+
1.0,
|
| 88 |
+
1.0,
|
| 89 |
+
1.0,
|
| 90 |
+
1.0
|
| 91 |
+
]
|
| 92 |
+
},
|
| 93 |
+
"action": {
|
| 94 |
+
"center": [
|
| 95 |
+
-0.00409134039811845,
|
| 96 |
+
-0.00034821918549549823,
|
| 97 |
+
0.25334054597908673,
|
| 98 |
+
-0.6482621860176762,
|
| 99 |
+
-0.1722537664890157,
|
| 100 |
+
0.17213817401650097,
|
| 101 |
+
-0.48305492944998246,
|
| 102 |
+
-0.036949049196568114,
|
| 103 |
+
0.0017706053732961,
|
| 104 |
+
0.0
|
| 105 |
+
],
|
| 106 |
+
"scale": [
|
| 107 |
+
0.22049181915876406,
|
| 108 |
+
0.12061939626625781,
|
| 109 |
+
0.7762177964377905,
|
| 110 |
+
0.9363876267106759,
|
| 111 |
+
2.920650091196781,
|
| 112 |
+
2.920074752883881,
|
| 113 |
+
0.9303273710763246,
|
| 114 |
+
1.7636183383343345,
|
| 115 |
+
0.04878805310889702,
|
| 116 |
+
1.0
|
| 117 |
+
]
|
| 118 |
+
}
|
| 119 |
+
}
|