OpenGHz commited on
Commit
d26db08
·
verified ·
1 Parent(s): 6d6a569

Add fair-comparison/extract-train-v1

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. fair-comparison/extract-train-v1/CODE_SNAPSHOT.json +338 -0
  2. fair-comparison/extract-train-v1/code/lim/__init__.py +1 -0
  3. fair-comparison/extract-train-v1/code/lim/act_optimization.py +81 -0
  4. fair-comparison/extract-train-v1/code/lim/act_policy.py +1366 -0
  5. fair-comparison/extract-train-v1/code/lim/action.py +77 -0
  6. fair-comparison/extract-train-v1/code/lim/action_encoding.py +120 -0
  7. fair-comparison/extract-train-v1/code/lim/action_objective.py +229 -0
  8. fair-comparison/extract-train-v1/code/lim/bspline_chunk.py +191 -0
  9. fair-comparison/extract-train-v1/code/lim/chunk_coordinates.py +262 -0
  10. fair-comparison/extract-train-v1/code/lim/chunk_done.py +114 -0
  11. fair-comparison/extract-train-v1/code/lim/chunk_endpoint.py +69 -0
  12. fair-comparison/extract-train-v1/code/lim/chunk_ensemble.py +174 -0
  13. fair-comparison/extract-train-v1/code/lim/chunk_flow.py +230 -0
  14. fair-comparison/extract-train-v1/code/lim/chunk_phase.py +32 -0
  15. fair-comparison/extract-train-v1/code/lim/chunk_samples.py +103 -0
  16. fair-comparison/extract-train-v1/code/lim/chunk_switch.py +60 -0
  17. fair-comparison/extract-train-v1/code/lim/collect_keyposes.py +592 -0
  18. fair-comparison/extract-train-v1/code/lim/evaluate_phase_chunk.py +327 -0
  19. fair-comparison/extract-train-v1/code/lim/evaluate_planned_keypose.py +1210 -0
  20. fair-comparison/extract-train-v1/code/lim/expert_stack_pyramid.py +129 -0
  21. fair-comparison/extract-train-v1/code/lim/expert_stack_pyramid_pick.py +133 -0
  22. fair-comparison/extract-train-v1/code/lim/gripper_execution.py +228 -0
  23. fair-comparison/extract-train-v1/code/lim/gripper_feedback.py +213 -0
  24. fair-comparison/extract-train-v1/code/lim/job.py +107 -0
  25. fair-comparison/extract-train-v1/code/lim/keypose_context.py +156 -0
  26. fair-comparison/extract-train-v1/code/lim/keypose_control.py +139 -0
  27. fair-comparison/extract-train-v1/code/lim/keypose_data.py +333 -0
  28. fair-comparison/extract-train-v1/code/lim/keypose_dense.py +135 -0
  29. fair-comparison/extract-train-v1/code/lim/keypose_diagnostics.py +205 -0
  30. fair-comparison/extract-train-v1/code/lim/keypose_extract.py +580 -0
  31. fair-comparison/extract-train-v1/code/lim/keypose_oracle.py +191 -0
  32. fair-comparison/extract-train-v1/code/lim/keypose_phase.py +121 -0
  33. fair-comparison/extract-train-v1/code/lim/keypose_policy.py +260 -0
  34. fair-comparison/extract-train-v1/code/lim/keypose_sequence.py +46 -0
  35. fair-comparison/extract-train-v1/code/lim/keypose_stop.py +77 -0
  36. fair-comparison/extract-train-v1/code/lim/keypose_trace.py +71 -0
  37. fair-comparison/extract-train-v1/code/lim/lift_peg_env.py +19 -0
  38. fair-comparison/extract-train-v1/code/lim/normalization.py +264 -0
  39. fair-comparison/extract-train-v1/code/lim/observations.py +89 -0
  40. fair-comparison/extract-train-v1/code/lim/ood_env.py +94 -0
  41. fair-comparison/extract-train-v1/code/lim/pi05_policy.py +322 -0
  42. fair-comparison/extract-train-v1/code/lim/planned_keypose.py +370 -0
  43. fair-comparison/extract-train-v1/code/lim/policy.py +52 -0
  44. fair-comparison/extract-train-v1/code/lim/policy_video.py +189 -0
  45. fair-comparison/extract-train-v1/code/lim/profile.py +122 -0
  46. fair-comparison/extract-train-v1/code/lim/real_chunks.py +223 -0
  47. fair-comparison/extract-train-v1/code/lim/reference_act.py +856 -0
  48. fair-comparison/extract-train-v1/code/lim/replay_pose.py +247 -0
  49. fair-comparison/extract-train-v1/code/lim/rlinf_openpi.py +61 -0
  50. fair-comparison/extract-train-v1/code/lim/run_sequence.py +194 -0
fair-comparison/extract-train-v1/CODE_SNAPSHOT.json ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "artifact": "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1",
3
+ "files": {
4
+ "/home/zhixi/Work/Research/lim/pixi.toml": "c4646961cd9519cb1ec640821b29b2a12a230a807db21b6e7914b5f59c7cb6e9",
5
+ "/home/zhixi/Work/Research/lim/pixi.lock": "d99598c608997b2284003d1bfb3ac4dc25cd3c5436765b4728ee8e36500d19d8",
6
+ "/home/zhixi/Work/Research/lim/round2/reference-source.json": "a73f863463cce7b3672dc8e8a1f012042579349cf1296af55b02520a5f34fbdc",
7
+ "/home/zhixi/Work/Research/lim/experiments/keypose-mechanism/essence-h800/specs/fendpoint_fg-main-train.json": "5bc2a32c0592bd041c04da4557fcd84d980776e6ce43316e30f55a69215405eb",
8
+ "/home/zhixi/Work/Research/lim/experiments/keypose-mechanism/essence-h800/specs/fendpoint_fg-main-eval.json": "1404828d20e9f10e26c9f7f32e2894428a3d282a159d46067459af194534cbcf",
9
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-data-v1/data/mainx/pose/derive.json": "c62f9e1b2bda978e826c61cdb1e6a3424a803a06a1d2b92ddc49975d08139eab",
10
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-data-v1/data/mainx/cap95.json": "03328bae6bd3587e58dc7d4471b6ccd5a3f47e5d046099c134184703557455ef",
11
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-data-v1/data/mainx/pose/trajectory.h5": "5995b99ed36d4cfefc990c2375eabbcb2d0eba79f11d3f475c4972b98c31ee94",
12
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-data-v1/data/l3x/pose/derive.json": "838c0c988ab9c71af2f7edf08b70d0d6d852310b0b13b1fb413fca81bef933ac",
13
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-data-v1/data/l3x/cap95.json": "8f96802d3685ed3420eecc8af58edf955b42b5cf5ed74df06908e4e97c15395d",
14
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-data-v1/data/l3x/pose/trajectory.h5": "6e50000172f6460af05db2464d7fd73dd07179c4fbce8578167b945f725b5d7b",
15
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/__init__.py": "0cc163c61e6ea84e2d0707efb92d5a97f63007460dc3fab12583ee531a1fbf1d",
16
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/act_optimization.py": "45122bf568e42e20fcff5b39ed68c8e238a11dde07c413ae87078b7d6c554af8",
17
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/act_policy.py": "3f6af11f8b58ba9caa3722260ef9c376f3ef27d52aa334554639e1c295e95e5c",
18
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/action.py": "d787ae6e63b633b38db7d83182c607ce65d4720e0f4f2005a0ff3798ff476bf0",
19
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/action_encoding.py": "178cab172b0afc168bf015599775278240f2126d243c25e9be4a5a7650966a13",
20
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/action_objective.py": "45816f03724659055ecb088430309f0388cf2b35289da61072cdb6cc3294cdf9",
21
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/bspline_chunk.py": "ccefefaf88718ea33f596e92b474dc732a5482e059fdef98c354be010348a1a1",
22
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/chunk_coordinates.py": "f10e878909395753f971957434d8df4bbaa70e298cc7c2421625f7dcca1603b5",
23
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/chunk_done.py": "adf3dfc52ff436cb10183e92654b16f11bfd8d23263d3ef0ca89066f59f1f6fc",
24
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/chunk_endpoint.py": "64a86d99276874fdc3be5d63e8abd4b5cf34308f9c77cc0ce859eb76ca802ba8",
25
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/chunk_ensemble.py": "ee1fc57c17e7e9b149a4f671c5c02e95f45fc3f0ff3548e0b6a2ab7c73489590",
26
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/chunk_flow.py": "9f164652433d9381405c71a25f6b264c7714a6a4aa681b7e916622668159aa47",
27
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/chunk_phase.py": "7cdb66ed1fc09458f8c19119f20f4ce33287d88b9a7bd2d1a610938116494572",
28
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/chunk_samples.py": "8c5240174b0871695c328c77fa268cf61a3c3221004cb7d9f861c12c722be8e3",
29
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/chunk_switch.py": "72cd6201e69cbb21b065be5a58da8f7ffeccd1b671aa42c1944adba40513d5b9",
30
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/collect_keyposes.py": "82f8019a691cee5a402122b87762fd2a62af5358b060708d7f899da045e51686",
31
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/evaluate_phase_chunk.py": "f8d62d1f62a49415ab774210df2da7888952d9007d5d7a166e1bf227e94ba997",
32
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/evaluate_planned_keypose.py": "a38bc26b814adeb2d5e9108c83dfcdb999a45877018254c61abe68c8ad1da45e",
33
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/expert_stack_pyramid.py": "178a4fb07b2e9063215087c6a6cfc2056acf5bc18485253266b1cc9aa346f3ca",
34
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/expert_stack_pyramid_pick.py": "fe3b0679d448c3e8efaa7b161f10ea2ae7e9133b3bee5f10eded964ac9992a6c",
35
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/gripper_execution.py": "ea0f64a596c6695c8863d12a55a835d11bebd7080f0055a64919b54b4bc944c8",
36
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/gripper_feedback.py": "d61c8edca56f663bbc9a28c381b663efa800661afae26a14a0f127102ff077ac",
37
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/job.py": "308f1d833c5f6c85eb763f61d9960ed3ca866f50648a9c84a5a57420aad385c0",
38
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/keypose_context.py": "c1d3e9e410b8743ac05791eb82d24e3557fd4de6c020c7614ef5ab28454a1a07",
39
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/keypose_control.py": "c976047a23a831a44e2b6056c3337483c892facc27976b70fcaebea5cb3d8730",
40
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/keypose_data.py": "5791fff2c56009b0a26a4269b24fa0879c4c1b34d69c0f399f17b0e32da80c5b",
41
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/keypose_dense.py": "2eaf0cfb30735491613a9431d58e75832196b9578dff611b9e8d74374a77f9cd",
42
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/keypose_diagnostics.py": "5e6fc13c3192970547c858cff8dc230b1573c8e06f2385cb537f2a850b4c2b23",
43
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/keypose_extract.py": "605ee94b38de6d1d6f9d74450b294a88e27aa1f2faec7472d2fd67fce2f46da2",
44
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/keypose_oracle.py": "4a0c5beded686c42289f9dac8b42633033f5d4028c77be659a6c615e6521963f",
45
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/keypose_phase.py": "bf889849599c0ad30e9d3d6a573eed8c30f93bee5e50476b729646881d9993ea",
46
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/keypose_policy.py": "f0dc4b64217f3014fc91416c2a4e3adebe37a4f598457488511cb630ff7fdbe8",
47
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/keypose_sequence.py": "7f3c8abb456c317bcf30ecd380bf4f2de18adbc90847a7ffc25398a48fd285bd",
48
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/keypose_stop.py": "9e2192abf01d0033250d1235a3fbaf90bd690375687bb18257e30d00631d575e",
49
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/keypose_trace.py": "fce7d06ace6db293a973c6c13529a7e0655996df814f0a4a6cc2dfb860dcd1a3",
50
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/lift_peg_env.py": "94a5c36cf95d4e45fcefad1ec7ce385fc28fe51c8984fa437aa933b794991edb",
51
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/normalization.py": "866fcfc00741c6fe01a82a9399263b325896c697812d7b7923f77e178dca7a24",
52
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/observations.py": "b83243c45bff96db3d653164fbe5c49801b07e6ba7ed6d394f6e18a1fd7dde1d",
53
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/ood_env.py": "5a2131cea9ca1da648919b3790fd214cca245be6016195561115d0597321513b",
54
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/pi05_policy.py": "ea9ff23cb7ab0dc8186777505e94f12245d8b02bf66852137393b597698a40d1",
55
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/planned_keypose.py": "bf5e177084c008619845c21d6a90a1ad3c1d6242ea89dea2134fa5ae2c924cec",
56
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/policy.py": "f440e9fc39bfe81d57b334e1f807a3c219253bc185fb141ef932de715d999b24",
57
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/policy_video.py": "88ab77abcc7d5c6b67bf110ab25f36aff88af6ea43e3bfc4284e980df109735d",
58
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/profile.py": "f51d6c88cad12794445d5342972fe76e7378300c77be9252c59a67444ae89e2d",
59
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/real_chunks.py": "4ca2d3bc7a7da74039197a7fb011eee0fcddc9f8b4a68fa89c85ba246388ffc3",
60
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/reference_act.py": "596a3fa158949e9ae536bb24c64119e8ab07bd6e006316d4598754c84718467f",
61
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/replay_pose.py": "e81ee3cfad6cc21286e2ff4505faae031040d68562e69ab784df611f93e24b9f",
62
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/rlinf_openpi.py": "17052985ae204e6c1e9e7d553a313dc4ebfc9b07dd511c5c06ab9e25ef56ff14",
63
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/run_sequence.py": "44a4b3c21590bf82e4dfd319f872b77a43a084e07dbf43a9e102163c6ade60ad",
64
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/smoke.py": "c41e00fa8a8290ab80a11996d3ceb6eb0e54c3e36172e59f90ae8f294c5315a1",
65
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/tasks.py": "40a5d3790131e8c2abe999b8cf144fe129800192c551f08d0945dd447e8f07f8",
66
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/train_offline.py": "019c383e84372a94381eb8a075509e576e3a1437d1bd2a7605e915573794b37d",
67
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/train_pi05.py": "753c348d9206a89c2590b5f3e2ecd7889339a43acd16341a36b8ad22b94a4adb",
68
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/train_pi05_real.py": "2670532654c8eccd3fdd8882c3ae57d50ba6cc06930d083aad2c342ce92e13e5",
69
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/train_real.py": "9263c3877a38f486a12825d74d9f71d608bc16b68fba2873ba6466974f6b3fc7",
70
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/train_resume.py": "3fc973bce5c64415f326afdcd208a5731570c03f6fee326fa250ec36b0803ac2",
71
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/umi_data.py": "0521bbb7f2d5ca62a20013f4da468544b7e87114009ceed63862ce192851243b",
72
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/code/lim/waypoints.py": "c7a72725174850b2bcc631cc86740306adbfbdfae6bdec0e61b4f8d6b78aca99",
73
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/tools/analyze_phase.py": "671669c217b7bc2310ef15b57d8f15ead8d008c1bea3cfc520d842a4e3b02ba3",
74
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/tools/bspline_offline.py": "ace73b452a655a519d6d437a9622ac82e8bc3089ba9d7c3265b3113b11ffa3da",
75
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/tools/check_executor_data.py": "60a61cacef810b79bb928e029a9f33842c7ef0e97d2417f63f7603e3ba2eab3f",
76
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/tools/check_factor.py": "404b75e0f749fc0380b72abba2eee0be36e0bb44581dd78a310d08019d4f0e4e",
77
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/tools/check_pi05_training.py": "e55d5dd20c4f3f822aa51bff880dcc1411bc63d75e6d1235db1c1bdb0cae4b90",
78
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/tools/check_training.py": "4276b4b957285711b0060c48b9b0fc22d2be2d9e90a4bdb39ac72de8bbe8baf8",
79
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/tools/collect_executor.py": "aa50531d75a85672a6491a368f4977e7abd9e0a8c364f0fb8a7c301e02178b1b",
80
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/tools/collect_online.py": "ca5c35260c1e266d97930e51c093059db4ce755c39416cc63fe7c43d7b3b94c7",
81
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/tools/compare_stages.py": "17d02cb715180d3a8c82b617a0cb508f4c43d2bfd3933effa909bbcb7d0bf9e7",
82
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/tools/derive_extracted.py": "28e79fd4cddf711c7b1e4445c7dfcdc2cdc1c9796e356e7d4ffdbb50bffb0ceb",
83
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/tools/dump_arrays.py": "964c03b81bcea9d92357be6b30260478655287aeb9107af11a4d6d5376d8c2fc",
84
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/tools/expert_ceiling.py": "1b7a40ba482b471dec4e9513b50bb0046a3606a4758271fb072db9150be316f6",
85
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/tools/factor_evaluate.py": "d9d34db694554bc674c3c8d70325b605d7784b4bbad5a355f3cbbead96fc3efc",
86
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/tools/fit_phase_probe.py": "1d41aaa07bd1ad3937632668f56c184e7d8a8d50e9730fa1e996b72ea28e7d65",
87
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/tools/flow_probe.py": "0e95f4229f0054c06e4a84f37ff57009c4c3583db51f5826c7e10f033171c518",
88
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/tools/job_queue.py": "d2beb756fd7110714235f8beb9f55cd1ccd4c306b09b095b155edc3983f20c4e",
89
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/tools/loss_probe.py": "07aca2522d2c0a37c5eec8b6ff3054819a39f27b64c072abdce4bbb8e89f3791",
90
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/tools/merge_datasets.py": "2894c877be16f90b3d100216722d9d365ee986e365428d0185c0c4147edc6045",
91
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/tools/phase_stats.py": "95361cb0e0366024e9dc7ff5745548074251409d3e59640fab80173524e22a55",
92
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/tools/probe_done.py": "a6c9d1cf89758cd3ee7d51827323658a221407450184f0710bab5fc7b8a6803e",
93
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/tools/probe_phase.py": "24d83bc099ebdfcb3972c9cf5cdf26da74e54b97a191edc8548e04f49e836b33",
94
+ "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-train-v1/tools/speed_cap.py": "62983f3f05db3736caad416ae70320cf2dbefa75c00ea2b3642a2c27f2dc6f30"
95
+ },
96
+ "jobs": 32,
97
+ "restart": "forbidden; failures keep their terminal ledger",
98
+ "stage": "extract-train",
99
+ "selection": {
100
+ "rule": "PLAN.md \u00a71",
101
+ "base": {
102
+ "dense": {
103
+ "30000": {
104
+ "queries": 50,
105
+ "execution": "seq_n8_cap95",
106
+ "mean": 47.5
107
+ },
108
+ "90000": {
109
+ "queries": 50,
110
+ "execution": "seq_n8",
111
+ "mean": 49.5
112
+ }
113
+ },
114
+ "keypose": {
115
+ "30000": {
116
+ "queries": 50,
117
+ "execution": "seq_n8_cap95",
118
+ "mean": 47.0
119
+ },
120
+ "90000": {
121
+ "queries": 50,
122
+ "execution": "seq_n8_cap95",
123
+ "mean": 52.0
124
+ }
125
+ }
126
+ },
127
+ "best_updates": {
128
+ "dense": 90000,
129
+ "keypose": 90000
130
+ },
131
+ "shared_before_extension": 90000,
132
+ "extension_needed": true,
133
+ "extended": {
134
+ "dense": {
135
+ "queries": 50,
136
+ "execution": "seq_n8",
137
+ "mean": 49.5
138
+ },
139
+ "keypose": {
140
+ "queries": 50,
141
+ "execution": "seq_n8_cap95",
142
+ "mean": 50.0
143
+ }
144
+ },
145
+ "extension_gained": false,
146
+ "updates": 90000,
147
+ "dense": {
148
+ "queries": 50,
149
+ "execution": "seq_n8",
150
+ "mean": 49.5
151
+ },
152
+ "keypose": {
153
+ "queries": 50,
154
+ "execution": "seq_n8_cap95",
155
+ "mean": 52.0
156
+ }
157
+ },
158
+ "source_version": "extract-data-v1",
159
+ "horizon": 400,
160
+ "runs": [
161
+ {
162
+ "mode": "keypose",
163
+ "queries": 50,
164
+ "updates": 90000,
165
+ "seed": 100,
166
+ "dataset": "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-data-v1/data/mainx/pose/trajectory.h5",
167
+ "demos": 100,
168
+ "samples": 10461,
169
+ "data": "mainx",
170
+ "env_id": "StackCube-v1",
171
+ "state_input": "full",
172
+ "witness": null,
173
+ "phase_head": true,
174
+ "done_weight": 0.0,
175
+ "phase_done": false,
176
+ "bspline_knots": null,
177
+ "flow": false,
178
+ "flow_decoder": "native",
179
+ "loss": "balanced",
180
+ "backbone": "act",
181
+ "pi05_state": true
182
+ },
183
+ {
184
+ "mode": "keypose",
185
+ "queries": 50,
186
+ "updates": 90000,
187
+ "seed": 101,
188
+ "dataset": "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-data-v1/data/mainx/pose/trajectory.h5",
189
+ "demos": 100,
190
+ "samples": 10461,
191
+ "data": "mainx",
192
+ "env_id": "StackCube-v1",
193
+ "state_input": "full",
194
+ "witness": null,
195
+ "phase_head": true,
196
+ "done_weight": 0.0,
197
+ "phase_done": false,
198
+ "bspline_knots": null,
199
+ "flow": false,
200
+ "flow_decoder": "native",
201
+ "loss": "balanced",
202
+ "backbone": "act",
203
+ "pi05_state": true
204
+ },
205
+ {
206
+ "mode": "keypose",
207
+ "queries": 50,
208
+ "updates": 90000,
209
+ "seed": 102,
210
+ "dataset": "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-data-v1/data/mainx/pose/trajectory.h5",
211
+ "demos": 100,
212
+ "samples": 10461,
213
+ "data": "mainx",
214
+ "env_id": "StackCube-v1",
215
+ "state_input": "full",
216
+ "witness": null,
217
+ "phase_head": true,
218
+ "done_weight": 0.0,
219
+ "phase_done": false,
220
+ "bspline_knots": null,
221
+ "flow": false,
222
+ "flow_decoder": "native",
223
+ "loss": "balanced",
224
+ "backbone": "act",
225
+ "pi05_state": true
226
+ },
227
+ {
228
+ "mode": "keypose",
229
+ "queries": 50,
230
+ "updates": 90000,
231
+ "seed": 103,
232
+ "dataset": "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-data-v1/data/mainx/pose/trajectory.h5",
233
+ "demos": 100,
234
+ "samples": 10461,
235
+ "data": "mainx",
236
+ "env_id": "StackCube-v1",
237
+ "state_input": "full",
238
+ "witness": null,
239
+ "phase_head": true,
240
+ "done_weight": 0.0,
241
+ "phase_done": false,
242
+ "bspline_knots": null,
243
+ "flow": false,
244
+ "flow_decoder": "native",
245
+ "loss": "balanced",
246
+ "backbone": "act",
247
+ "pi05_state": true
248
+ },
249
+ {
250
+ "mode": "keypose",
251
+ "queries": 50,
252
+ "updates": 90000,
253
+ "seed": 100,
254
+ "dataset": "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-data-v1/data/l3x/pose/trajectory.h5",
255
+ "demos": 100,
256
+ "samples": null,
257
+ "data": "l3x",
258
+ "env_id": "StackCube-v1",
259
+ "state_input": "full",
260
+ "witness": null,
261
+ "phase_head": true,
262
+ "done_weight": 0.0,
263
+ "phase_done": false,
264
+ "bspline_knots": null,
265
+ "flow": false,
266
+ "flow_decoder": "native",
267
+ "loss": "balanced",
268
+ "backbone": "act",
269
+ "pi05_state": true
270
+ },
271
+ {
272
+ "mode": "keypose",
273
+ "queries": 50,
274
+ "updates": 90000,
275
+ "seed": 101,
276
+ "dataset": "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-data-v1/data/l3x/pose/trajectory.h5",
277
+ "demos": 100,
278
+ "samples": null,
279
+ "data": "l3x",
280
+ "env_id": "StackCube-v1",
281
+ "state_input": "full",
282
+ "witness": null,
283
+ "phase_head": true,
284
+ "done_weight": 0.0,
285
+ "phase_done": false,
286
+ "bspline_knots": null,
287
+ "flow": false,
288
+ "flow_decoder": "native",
289
+ "loss": "balanced",
290
+ "backbone": "act",
291
+ "pi05_state": true
292
+ },
293
+ {
294
+ "mode": "keypose",
295
+ "queries": 50,
296
+ "updates": 90000,
297
+ "seed": 102,
298
+ "dataset": "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-data-v1/data/l3x/pose/trajectory.h5",
299
+ "demos": 100,
300
+ "samples": null,
301
+ "data": "l3x",
302
+ "env_id": "StackCube-v1",
303
+ "state_input": "full",
304
+ "witness": null,
305
+ "phase_head": true,
306
+ "done_weight": 0.0,
307
+ "phase_done": false,
308
+ "bspline_knots": null,
309
+ "flow": false,
310
+ "flow_decoder": "native",
311
+ "loss": "balanced",
312
+ "backbone": "act",
313
+ "pi05_state": true
314
+ },
315
+ {
316
+ "mode": "keypose",
317
+ "queries": 50,
318
+ "updates": 90000,
319
+ "seed": 103,
320
+ "dataset": "/home/zhixi/Work/Research/lim/artifacts/fair-comparison/extract-data-v1/data/l3x/pose/trajectory.h5",
321
+ "demos": 100,
322
+ "samples": null,
323
+ "data": "l3x",
324
+ "env_id": "StackCube-v1",
325
+ "state_input": "full",
326
+ "witness": null,
327
+ "phase_head": true,
328
+ "done_weight": 0.0,
329
+ "phase_done": false,
330
+ "bspline_knots": null,
331
+ "flow": false,
332
+ "flow_decoder": "native",
333
+ "loss": "balanced",
334
+ "backbone": "act",
335
+ "pi05_state": true
336
+ }
337
+ ]
338
+ }
fair-comparison/extract-train-v1/code/lim/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Compact manipulation policy experiments."""
fair-comparison/extract-train-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/extract-train-v1/code/lim/act_policy.py ADDED
@@ -0,0 +1,1366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.bspline_chunk import demonstration_segments, segment_reconstruction
41
+ from lim.chunk_flow import ChunkFlowConfig, ChunkFlowModel, flow_reconstruction
42
+ from lim.chunk_coordinates import (
43
+ ChunkAnchor,
44
+ ChunkGripperSupervision,
45
+ ChunkPadding,
46
+ ChunkPoseSupervision,
47
+ chunk_relative_to_world,
48
+ controller_pose_targets,
49
+ pose_target_contract,
50
+ resolve_anchor,
51
+ world_to_chunk_relative,
52
+ )
53
+ from lim.keypose_context import (
54
+ KeyposeContextMode,
55
+ KeyposeContextModel,
56
+ KeyposeContextModelConfig,
57
+ )
58
+ from lim.keypose_control import (
59
+ KeyposeControlConfig,
60
+ KeyposeEnv,
61
+ KeyposeEnvConfig,
62
+ encode_keypose,
63
+ )
64
+ from lim.keypose_dense import (
65
+ DenseAuxiliaryHead,
66
+ DenseAuxiliaryHeadConfig,
67
+ read_dense_actions,
68
+ )
69
+ from lim.keypose_phase import (
70
+ DONE_PHASE,
71
+ KeyposePhaseHead,
72
+ KeyposePhaseHeadConfig,
73
+ read_phase_logits,
74
+ )
75
+ from lim.keypose_policy import FirstKeyposeAgent, FirstKeyposeAgentConfig
76
+ from lim.keypose_stop import KeyposeStopHead, KeyposeStopHeadConfig, read_stop_logits
77
+ from lim.chunk_done import (
78
+ ChunkDoneHead,
79
+ ChunkDoneHeadConfig,
80
+ labels_from_valid,
81
+ batch_done_items,
82
+ read_done_logits,
83
+ )
84
+ from lim.chunk_switch import (
85
+ SWITCH_HORIZON,
86
+ ChunkSwitchHead,
87
+ ChunkSwitchHeadConfig,
88
+ read_switch_fraction,
89
+ )
90
+ from lim.normalization import (
91
+ NormalizationConfig,
92
+ NormalizedModel,
93
+ NormalizedModelConfig,
94
+ checked_statistics,
95
+ )
96
+
97
+
98
+ class ACTPolicyConfig(BaseModel, frozen=True):
99
+ model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
100
+ method: Literal["cvae", "state_free", "flow", "chunk_relative"] = "cvae"
101
+ """One independent policy intervention; cvae preserves the native agent."""
102
+ action_encoding: ActionEncoding = "controller"
103
+ """Rotation6D learns ten-dimensional labels and decodes only after ensembling."""
104
+ chunk_anchor: ChunkAnchor = "chunk_start_tcp"
105
+ """Chunk label frame. Identity isolates the anchor: targets become absolute
106
+ world poses while the controller boundary still converts against real TCP."""
107
+ chunk_pose_supervision: ChunkPoseSupervision = "dense"
108
+ """Replace only valid-slot pose labels; padding and dense normalization stay
109
+ shared. Endpoint inference needs no prefix."""
110
+ chunk_gripper_supervision: ChunkGripperSupervision = "future"
111
+ """Future commands, or current command repeated in valid slots; independent of
112
+ pose and phase labels, with terminal padding and fitted scales preserved."""
113
+ chunk_padding: ChunkPadding = "terminal"
114
+ """Out-of-range slots keep measured terminal targets, or repeat the current
115
+ complete endpoint target. Valid labels and normalization are unchanged."""
116
+ chunk_normalization_population: Literal["dense", "supervised"] = "dense"
117
+ """Action statistics use dense valid pairs, or one complete current target per
118
+ observation for the repeated current-target recipe."""
119
+ chunk_label_offset: NonNegativeInt = 0
120
+ """Slot i supervises time t+offset+i; zero preserves every existing recipe."""
121
+ chunk_waypoint_threshold_m: PositiveFloat | None = None
122
+ """AWE distance threshold (metres) for future_waypoint labels; None otherwise."""
123
+ chunk_bspline_knots: PositiveInt | None = None
124
+ """Unique knots per B-spline segment for bspline labels (lim.bspline_chunk;
125
+ num_queries = knots + 6 rows); None otherwise."""
126
+ chunk_switch_head: bool = False
127
+ """Regress the current phase's remaining steps from decoder query zero."""
128
+ chunk_switch_weight: NonNegativeFloat = Field(default=1.0, allow_inf_nan=False)
129
+ """L1 weight on the remaining-steps fraction when the switch head exists."""
130
+ chunk_phase_done: bool = False
131
+ """Label padded items with a seventh "done" phase instead of ignoring them;
132
+ requires a trained per-item phase head (chunk_phase_weight > 0)."""
133
+ chunk_done_weight: NonNegativeFloat = Field(default=0.0, allow_inf_nan=False)
134
+ """BCE weight of the per-item end-of-demonstration logits (lim.chunk_done);
135
+ positive values add the head. Action labels, padding and statistics are unchanged."""
136
+ flow_steps: PositiveInt = 8
137
+ """Euler evaluations per fresh observation for the conditional flow head
138
+ (method flow) or the flow-matching head (chunk_flow)."""
139
+ inference_seed: NonNegativeInt = 20260916
140
+ """Private flow inference noise stream, independent of the training RNG;
141
+ chunk_flow evaluations seed each episode with inference_seed + scene seed."""
142
+ chunk_flow: bool = False
143
+ """Replace the CVAE decoder pass by a flow-matching head on the same
144
+ observation encoder (lim.chunk_flow); False keeps the CVAE."""
145
+ flow_decoder: Literal["native", "modulated"] = "native"
146
+ """chunk_flow only: native reads decoder layer 1 with time in the input (pi0);
147
+ modulated reads the last layer with time modulating every layer (pi0.5-style)."""
148
+ normalization: NormalizationConfig = NormalizationConfig()
149
+ """Independent training-fitted scaling; none preserves existing policies."""
150
+ state_input: Literal["full", "no_velocity", "tcp_only", "no_state"] = "full"
151
+ """State25 information subset, masked in both CVAE branches with capacity fixed;
152
+ no_state masks all 25 values, leaving the images as the only observation."""
153
+ action_loss: ActionLossConfig = ActionLossConfig()
154
+ """Action objective and linked inference semantics, persisted with the policy."""
155
+ keypose: KeyposeControlConfig | None = None
156
+ """When set, learn next world keypose on all queries; execute the first at 20Hz."""
157
+ keypose_phase_weight: NonNegativeFloat = Field(default=0.0, allow_inf_nan=False)
158
+ """Weight on six-class primitive CE from query-zero features; zero preserves
159
+ the native action-only model. Labels are supervision only, never inputs."""
160
+ keypose_target_sequence: Literal["current", "future"] = "current"
161
+ """Repeat the current primitive goal, or supervise each future time's goal;
162
+ both variants still execute query zero with the same keypose controller."""
163
+ keypose_context: KeyposeContextMode = "none"
164
+ """Optional completed-target11 input shared by prior and posterior state
165
+ projections; zero and previous_target have identical trainable structure."""
166
+ keypose_stop_head: bool = False
167
+ """Add independent terminal-intent logits from decoder query zero."""
168
+ keypose_stop_weight: NonNegativeFloat = Field(default=0.1, allow_inf_nan=False)
169
+ """BCE weight when the stop head exists; zero retains the same head for controls."""
170
+ keypose_dense_head: bool = False
171
+ """Add a dense30 auxiliary decoder projection; never executed at inference."""
172
+ keypose_dense_weight: NonNegativeFloat = Field(default=1.0, allow_inf_nan=False)
173
+ """Dense group-balanced reconstruction weight; zero is the matched head control."""
174
+ chunk_phase_head: bool = False
175
+ """Retain the per-query phase head even when its auxiliary loss is zero."""
176
+ chunk_phase_weight: NonNegativeFloat = Field(default=0.0, allow_inf_nan=False)
177
+ """Per-query phase CE weight. Positive values also enable the head, preserving
178
+ the architecture of existing checkpoints with no explicit head field."""
179
+
180
+ @property
181
+ def has_chunk_phase_head(self):
182
+ """Whether model construction and diagnostic labels include a phase head."""
183
+ return self.chunk_phase_head or self.chunk_phase_weight > 0
184
+
185
+ @property
186
+ def has_chunk_done_head(self):
187
+ """Whether model construction and training labels include the done head."""
188
+ return self.chunk_done_weight > 0
189
+
190
+ def action_dimension(self, controller_dimension):
191
+ """Per-item model output width: the encoded target, plus the knot column
192
+ of B-spline segments."""
193
+ width = encoded_dimension(controller_dimension, self.action_encoding)
194
+ return width + (self.chunk_pose_supervision == "bspline")
195
+
196
+ @model_validator(mode="after")
197
+ def check_bspline(self):
198
+ if (self.chunk_pose_supervision == "bspline") != (self.chunk_bspline_knots is not None):
199
+ raise ValueError("Exactly the B-spline supervision carries a knot count")
200
+ if self.chunk_pose_supervision == "bspline" and (
201
+ self.method != "chunk_relative"
202
+ or self.action_encoding != "rotation6d"
203
+ or self.chunk_anchor != "chunk_start_tcp"
204
+ or self.chunk_gripper_supervision != "future"
205
+ or self.chunk_padding != "terminal"
206
+ or self.chunk_normalization_population != "dense"
207
+ or self.chunk_label_offset
208
+ or self.has_chunk_phase_head
209
+ or self.chunk_switch_head
210
+ or self.has_chunk_done_head
211
+ or not self.action_loss.plain_groups
212
+ ):
213
+ raise ValueError(
214
+ "B-spline segments use TCP-anchored pose6D, default label fields,"
215
+ " no per-item heads and the group-balanced objective"
216
+ )
217
+ return self
218
+
219
+ @model_validator(mode="after")
220
+ def check_flow(self):
221
+ if self.flow_decoder != "native" and not self.chunk_flow:
222
+ raise ValueError("The modulated decoder belongs to the flow head")
223
+ if self.chunk_flow and (
224
+ self.method != "chunk_relative"
225
+ or self.action_encoding != "rotation6d"
226
+ or self.chunk_pose_supervision not in ("dense", "future_endpoint")
227
+ or self.has_chunk_phase_head
228
+ or self.chunk_switch_head
229
+ or self.has_chunk_done_head
230
+ or self.state_input != "full"
231
+ or not self.action_loss.plain_groups
232
+ ):
233
+ raise ValueError(
234
+ "The flow head replaces the CVAE of full-state TCP-anchored dense or"
235
+ " endpoint pose6D chunks, without per-item heads"
236
+ )
237
+ return self
238
+
239
+ @model_validator(mode="after")
240
+ def check_phase_done(self):
241
+ if self.chunk_phase_done and (
242
+ self.chunk_phase_weight <= 0
243
+ or self.chunk_done_weight > 0
244
+ or self.chunk_padding != "terminal"
245
+ or self.chunk_label_offset
246
+ or self.chunk_pose_supervision == "phase_segments"
247
+ or self.chunk_switch_head
248
+ ):
249
+ raise ValueError(
250
+ "The done phase labels terminal padding of a trained per-item phase head, without the done head"
251
+ )
252
+ return self
253
+
254
+ @model_validator(mode="after")
255
+ def check_done(self):
256
+ # Labels are the dataset's in-range mask; offsets and two-segment
257
+ # outputs index items by something other than consecutive steps.
258
+ if self.has_chunk_done_head and (
259
+ self.method != "chunk_relative"
260
+ or self.action_encoding != "rotation6d"
261
+ or self.chunk_padding != "terminal"
262
+ or self.chunk_label_offset
263
+ or self.chunk_pose_supervision == "phase_segments"
264
+ or self.chunk_switch_head
265
+ ):
266
+ raise ValueError(
267
+ "The done head labels consecutive pose6D chunk items with terminal padding"
268
+ )
269
+ return self
270
+
271
+ @model_validator(mode="after")
272
+ def check_normalization(self):
273
+ compact = (
274
+ self.chunk_label_offset > 0
275
+ or self.chunk_pose_supervision == "phase_segments"
276
+ or self.chunk_switch_head
277
+ )
278
+ # A Q30 future-endpoint switch arm keeps its template's zero-weight phase
279
+ # head, so it differs from that template only by the switch head.
280
+ phase_head_allowed = (
281
+ self.chunk_pose_supervision == "future_endpoint"
282
+ and not self.chunk_label_offset
283
+ and self.chunk_phase_weight == 0
284
+ )
285
+ if compact and (
286
+ self.method != "chunk_relative"
287
+ or self.action_encoding != "rotation6d"
288
+ or self.chunk_anchor != "chunk_start_tcp"
289
+ or self.chunk_gripper_supervision != "future"
290
+ or self.chunk_padding != "terminal"
291
+ or self.chunk_normalization_population != "dense"
292
+ or (self.has_chunk_phase_head and not phase_head_allowed)
293
+ ):
294
+ raise ValueError(
295
+ "Compact endpoint outputs use TCP-anchored pose6D, own gripper labels, no phase head"
296
+ )
297
+ if self.chunk_label_offset > 0 and self.chunk_pose_supervision != "future_endpoint":
298
+ raise ValueError("Lookahead labels shift future-time endpoint supervision only")
299
+ if (self.chunk_pose_supervision == "future_waypoint") != (
300
+ self.chunk_waypoint_threshold_m is not None
301
+ ):
302
+ raise ValueError("Exactly the waypoint supervision carries a waypoint threshold")
303
+ if self.chunk_pose_supervision == "phase_segments" and not self.chunk_switch_head:
304
+ raise ValueError("Phase segments always carry the switch head (weight may be zero)")
305
+ if self.chunk_switch_head and (
306
+ self.chunk_pose_supervision not in ("phase_segments", "future_endpoint")
307
+ or self.chunk_label_offset
308
+ ):
309
+ raise ValueError("The switch head supervises unshifted endpoint recipes only")
310
+ if self.chunk_pose_supervision == "phase_segments" and self.chunk_label_offset:
311
+ raise ValueError("Phase segments are indexed by phase, not by time offset")
312
+ if self.chunk_padding == "current_target" and (
313
+ self.chunk_pose_supervision != "current_endpoint"
314
+ or self.chunk_gripper_supervision != "current"
315
+ ):
316
+ raise ValueError(
317
+ "Current-target padding requires current endpoint and gripper"
318
+ )
319
+ if self.chunk_gripper_supervision != "future" and (
320
+ self.method != "chunk_relative" or self.action_encoding != "rotation6d"
321
+ ):
322
+ raise ValueError("Chunk gripper supervision requires chunk-relative pose6D")
323
+ if self.chunk_pose_supervision != "dense" and (
324
+ self.method != "chunk_relative"
325
+ or self.action_encoding != "rotation6d"
326
+ ):
327
+ raise ValueError(
328
+ "Matched endpoint supervision requires pose6D chunk-relative targets"
329
+ )
330
+ if self.has_chunk_phase_head and (
331
+ self.method != "chunk_relative"
332
+ or self.action_encoding != "rotation6d"
333
+ ):
334
+ raise ValueError(
335
+ "Chunk phase supervision requires fixed-anchor pose6D targets"
336
+ )
337
+ if self.chunk_normalization_population == "supervised" and (
338
+ self.chunk_pose_supervision != "current_endpoint"
339
+ or self.chunk_gripper_supervision != "current"
340
+ or self.chunk_padding != "current_target"
341
+ ):
342
+ raise ValueError(
343
+ "Supervised normalization requires repeated complete current-target endpoint labels"
344
+ )
345
+ if self.keypose_dense_head and not self.keypose_stop_head:
346
+ raise ValueError(
347
+ "Dense auxiliary screen requires the existing stop/context policy"
348
+ )
349
+ if self.keypose_stop_head and (
350
+ self.keypose is None
351
+ or self.method != "cvae"
352
+ or self.state_input != "full"
353
+ or self.keypose_target_sequence != "current"
354
+ or self.keypose_context != "previous_target"
355
+ or self.keypose_phase_weight != 0
356
+ ):
357
+ raise ValueError(
358
+ "Stop supervision requires current previous-target full-state CVAE keypose without phase"
359
+ )
360
+ if self.keypose_context != "none" and (
361
+ self.keypose is None
362
+ or self.method != "cvae"
363
+ or self.state_input != "full"
364
+ or self.keypose_target_sequence != "current"
365
+ or self.keypose_phase_weight != 0
366
+ ):
367
+ raise ValueError(
368
+ "Completed-goal context requires current full-state CVAE keypose without a phase head"
369
+ )
370
+ if self.keypose_target_sequence == "future" and self.keypose is None:
371
+ raise ValueError("Future keypose supervision requires a keypose policy")
372
+ if self.keypose_phase_weight > 0 and self.keypose is None:
373
+ raise ValueError("Phase classification requires a keypose policy")
374
+ if self.chunk_anchor != "chunk_start_tcp" and (
375
+ self.method != "chunk_relative" or self.action_encoding != "rotation6d"
376
+ ):
377
+ raise ValueError(
378
+ "Absolute chunk anchors are only defined for pose6D chunk_relative"
379
+ )
380
+ if (
381
+ self.method == "chunk_relative"
382
+ and self.action_encoding == "controller"
383
+ and self.normalization.method != "none"
384
+ ):
385
+ raise ValueError(
386
+ "Position-only chunk-relative checkpoints retain their original unnormalized contract"
387
+ )
388
+ if self.keypose is not None and (
389
+ self.method != "cvae"
390
+ or self.action_encoding != "rotation6d"
391
+ or self.state_input != "full"
392
+ or self.action_loss.method != "group_balanced"
393
+ or self.normalization.method != "action_zscore"
394
+ ):
395
+ raise ValueError(
396
+ "Keypose screen requires full-state CVAE, rotation6d, group-balanced action-zscore"
397
+ )
398
+ if self.normalization.method != "none" and self.method not in (
399
+ "cvae",
400
+ "chunk_relative",
401
+ ):
402
+ raise ValueError(
403
+ "Screen normalization on the native state-conditioned CVAE"
404
+ )
405
+ if self.state_input != "full" and self.method not in ("cvae", "chunk_relative"):
406
+ raise ValueError("State subsets are screened on the CVAE policies")
407
+ if self.action_loss.method != "native" and (
408
+ self.method not in ("cvae", "chunk_relative")
409
+ or self.action_encoding != "rotation6d"
410
+ or (self.state_input != "full" and self.method != "chunk_relative")
411
+ ):
412
+ raise ValueError("Screen pose action losses on full-state Rotation6D CVAE")
413
+ if (
414
+ self.method == "chunk_relative"
415
+ and self.action_encoding == "rotation6d"
416
+ and (
417
+ self.keypose is not None
418
+ or self.normalization.method != "action_zscore"
419
+ or self.action_loss.method != "group_balanced"
420
+ )
421
+ ):
422
+ raise ValueError(
423
+ "Pose chunk-relative screen requires full-state/group-balanced/action-zscore"
424
+ )
425
+ return self
426
+
427
+
428
+ class ModelBuildConfig(BaseModel, frozen=True):
429
+ model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid")
430
+ native_model: Any
431
+ """Newly initialized pinned DETRVAE; selected modules are reused unchanged."""
432
+ policy: ACTPolicyConfig
433
+ """Validated policy variant and sampler configuration."""
434
+
435
+
436
+ class StateFreeModel(nn.Module):
437
+ """Constant state tokens preserve capacity but carry no proprioceptive signal."""
438
+
439
+ def __init__(self, config: ModelBuildConfig):
440
+ super().__init__()
441
+ self.base = config.native_model
442
+ self.state_dim = self.base.input_proj_robot_state.in_features
443
+
444
+ def forward(self, obs, actions=None):
445
+ # Both the posterior and action decoder see constants, including training.
446
+ # The original state values are never read; images determine batch/device.
447
+ state = torch.zeros(
448
+ obs["rgb"].shape[0],
449
+ self.state_dim,
450
+ device=obs["rgb"].device,
451
+ dtype=obs["rgb"].dtype,
452
+ )
453
+ return self.base({"rgb": obs["rgb"], "state": state}, actions)
454
+
455
+
456
+ class StateSubsetModel(nn.Module):
457
+ """Remove selected state information without changing initialization or width."""
458
+
459
+ def __init__(self, config: ModelBuildConfig):
460
+ super().__init__()
461
+ self.config = config
462
+ self.base = config.native_model
463
+ if self.base.input_proj_robot_state.in_features != 25:
464
+ raise ValueError(
465
+ "State subsets require qpos9, qvel9, TCP position3/quaternion4"
466
+ )
467
+ keep = torch.zeros(25, dtype=torch.bool)
468
+ if config.policy.state_input == "no_velocity":
469
+ keep[:9] = True
470
+ keep[18:] = True
471
+ elif config.policy.state_input == "tcp_only":
472
+ keep[18:] = True
473
+ elif config.policy.state_input != "no_state":
474
+ raise ValueError("Full-state control must use the unwrapped native model")
475
+ self.register_buffer("keep_state", keep, persistent=False)
476
+
477
+ def forward(self, obs, actions=None):
478
+ # Applied after optional per-axis normalization, before posterior/decoder.
479
+ # masked_fill also prevents discarded NaNs from reaching either branch.
480
+ state = obs["state"].masked_fill(~self.keep_state, 0)
481
+ return self.base({**obs, "state": state}, actions)
482
+
483
+
484
+ class FlowACT(nn.Module):
485
+ """Conditional linear-path flow: Gaussian noise -> normalized action chunks.
486
+
487
+ Observation memory is encoded once per fresh observation. Only the action
488
+ decoder is iterated, with noisy actions and continuous time as inputs.
489
+ """
490
+
491
+ def __init__(self, config: ModelBuildConfig):
492
+ super().__init__()
493
+ native = config.native_model
494
+ self.config = config.policy
495
+ self.backbones = native.backbones
496
+ self.input_proj = native.input_proj
497
+ self.input_proj_robot_state = native.input_proj_robot_state
498
+ self.transformer = native.transformer
499
+ self.query_embed = native.query_embed
500
+ self.action_head = native.action_head
501
+ self.additional_pos_embed = native.additional_pos_embed
502
+ self.num_queries = native.num_queries
503
+ width = self.transformer.d_model
504
+ self.action_input = nn.Linear(self.action_head.out_features, width)
505
+ self.time_mlp = nn.Sequential(
506
+ nn.Linear(width, width), nn.SiLU(), nn.Linear(width, width)
507
+ )
508
+ self.register_buffer(
509
+ "time_frequencies",
510
+ torch.exp(
511
+ -math.log(10000) * torch.arange(width // 2) / max(1, width // 2 - 1)
512
+ ),
513
+ )
514
+ self.generator = None
515
+
516
+ def encode_observation(self, obs):
517
+ features, positions = [], []
518
+ for camera in range(obs["rgb"].shape[1]):
519
+ feature, position = self.backbones[0](obs["rgb"][:, camera])
520
+ features.append(self.input_proj(feature[0]))
521
+ positions.append(position[0])
522
+ batch = obs["rgb"].shape[0]
523
+ src = torch.cat(features, dim=3).flatten(2).permute(2, 0, 1)
524
+ pos = (
525
+ torch.cat(positions, dim=3).flatten(2).permute(2, 0, 1).repeat(1, batch, 1)
526
+ )
527
+ proprio = self.input_proj_robot_state(obs["state"]).unsqueeze(0)
528
+ # Keep the native proprioceptive position; there is no CVAE latent token.
529
+ pos = torch.cat(
530
+ [self.additional_pos_embed.weight[1:2, None].expand(-1, batch, -1), pos]
531
+ )
532
+ src = torch.cat([proprio, src])
533
+ memory = self.transformer.encoder(src, pos=pos)
534
+ return memory, pos
535
+
536
+ def velocity(self, noisy, time, memory, pos):
537
+ angles = time[:, None] * self.time_frequencies[None] * 1000
538
+ time_embedding = self.time_mlp(torch.cat([angles.sin(), angles.cos()], dim=-1))
539
+ target = (self.action_input(noisy) + time_embedding[:, None]).transpose(0, 1)
540
+ queries = self.query_embed.weight[:, None].expand(-1, noisy.shape[0], -1)
541
+ hidden = self.transformer.decoder(target, memory, pos=pos, query_pos=queries)[
542
+ -1
543
+ ]
544
+ return self.action_head(hidden.transpose(0, 1))
545
+
546
+ def training_loss(self, obs, actions):
547
+ memory, pos = self.encode_observation(obs)
548
+ noise = torch.randn_like(actions)
549
+ time = torch.rand(actions.shape[0], device=actions.device)
550
+ noisy = (1 - time[:, None, None]) * noise + time[:, None, None] * actions
551
+ target = actions - noise
552
+ return F.mse_loss(self.velocity(noisy, time, memory, pos), target)
553
+
554
+ def forward(self, obs):
555
+ memory, pos = self.encode_observation(obs)
556
+ if self.generator is None or self.generator.device != obs["rgb"].device:
557
+ self.generator = torch.Generator(device=obs["rgb"].device)
558
+ self.generator.manual_seed(self.config.inference_seed)
559
+ batch = obs["rgb"].shape[0]
560
+ action = torch.randn(
561
+ batch,
562
+ self.num_queries,
563
+ self.action_head.out_features,
564
+ device=obs["rgb"].device,
565
+ generator=self.generator,
566
+ )
567
+ step = 1 / self.config.flow_steps
568
+ for index in range(self.config.flow_steps):
569
+ time = action.new_full((batch,), index * step)
570
+ action = action + step * self.velocity(action, time, memory, pos)
571
+ # Match native ACT: the controller clips after temporal aggregation.
572
+ return action, (None, None)
573
+
574
+
575
+ def build_policy(native, spaces, args, policy, normalization=None):
576
+ fitted = checked_statistics(
577
+ normalization, policy.normalization, policy.action_encoding
578
+ )
579
+ if policy.action_encoding != "controller":
580
+ spaces = SimpleNamespace(
581
+ single_observation_space=spaces.single_observation_space,
582
+ single_action_space=SimpleNamespace(
583
+ shape=(policy.action_dimension(spaces.single_action_space.shape[-1]),)
584
+ ),
585
+ )
586
+ agent = native.Agent(spaces, args)
587
+ if policy.keypose_stop_head:
588
+ # Attach to the actual native decoder before context/normalization wrappers.
589
+ agent.model.action_head = KeyposeStopHead(
590
+ KeyposeStopHeadConfig(action_head=agent.model.action_head)
591
+ )
592
+ if policy.keypose_dense_head:
593
+ agent.model.action_head = DenseAuxiliaryHead(
594
+ DenseAuxiliaryHeadConfig(
595
+ primary=agent.model.action_head,
596
+ hidden_size=agent.model.action_head.action.in_features,
597
+ )
598
+ )
599
+ if policy.keypose_context != "none":
600
+ if fitted is None:
601
+ raise ValueError(
602
+ "Completed-goal context requires checkpoint-owned action statistics"
603
+ )
604
+ agent.model = KeyposeContextModel(
605
+ KeyposeContextModelConfig(
606
+ model=agent.model, mode=policy.keypose_context, statistics=fitted
607
+ )
608
+ )
609
+ if policy.keypose_phase_weight > 0 or policy.has_chunk_phase_head:
610
+ agent.model.action_head = KeyposePhaseHead(
611
+ KeyposePhaseHeadConfig(
612
+ action_head=agent.model.action_head,
613
+ all_queries=policy.has_chunk_phase_head,
614
+ done_class=policy.chunk_phase_done,
615
+ )
616
+ )
617
+ if policy.chunk_switch_head:
618
+ # Outermost: it may wrap the phase head; both read the same features.
619
+ agent.model.action_head = ChunkSwitchHead(
620
+ ChunkSwitchHeadConfig(action_head=agent.model.action_head)
621
+ )
622
+ if policy.has_chunk_done_head:
623
+ agent.model.action_head = ChunkDoneHead(
624
+ ChunkDoneHeadConfig(action_head=agent.model.action_head)
625
+ )
626
+ if policy.chunk_flow:
627
+ agent.model = ChunkFlowModel(
628
+ ChunkFlowConfig(
629
+ native_model=agent.model, steps=policy.flow_steps, decoder=policy.flow_decoder
630
+ )
631
+ )
632
+ if policy.method == "state_free":
633
+ agent.model = StateFreeModel(
634
+ ModelBuildConfig(native_model=agent.model, policy=policy)
635
+ )
636
+ elif policy.method == "flow":
637
+ agent.model = FlowACT(ModelBuildConfig(native_model=agent.model, policy=policy))
638
+ if policy.state_input != "full":
639
+ agent.model = StateSubsetModel(
640
+ ModelBuildConfig(native_model=agent.model, policy=policy)
641
+ )
642
+ if policy.action_loss.binary_gripper:
643
+ agent.model = BinaryGripperModel(BinaryGripperModelConfig(model=agent.model))
644
+ if fitted is not None:
645
+ if spaces.single_action_space.shape != (
646
+ len(fitted.action.center),
647
+ ) or spaces.single_observation_space["state"].shape != (
648
+ len(fitted.state.center),
649
+ ):
650
+ raise ValueError("Fitted normalization shapes differ from the policy")
651
+ agent.model = NormalizedModel(
652
+ NormalizedModelConfig(model=agent.model, statistics=fitted)
653
+ )
654
+ return agent
655
+
656
+
657
+ def policy_loss(
658
+ agent,
659
+ native,
660
+ obs,
661
+ actions,
662
+ policy,
663
+ objective,
664
+ phase_labels=None,
665
+ stop_labels=None,
666
+ dense_labels=None,
667
+ switch_labels=None,
668
+ done_labels=None,
669
+ ):
670
+ if policy.action_loss.method != "native":
671
+ if objective.config.method != "control":
672
+ raise ValueError(
673
+ "Action loss candidates require the control training recipe"
674
+ )
675
+ obs = {**obs, "rgb": agent.normalize(obs["rgb"].float() / 255)}
676
+ if policy.chunk_flow:
677
+ # No latent and no per-item heads (check_flow): only the velocity loss.
678
+ velocity, target = agent.model(obs, actions)
679
+ losses = flow_reconstruction(velocity, target)
680
+ return {"loss": losses["reconstruction"], **losses}
681
+ prediction, (mu, logvar) = agent.model(obs, actions)
682
+ reconstruction = (
683
+ segment_reconstruction
684
+ if policy.chunk_pose_supervision == "bspline"
685
+ else pose_reconstruction
686
+ )
687
+ losses = reconstruction(prediction, actions, policy.action_loss)
688
+ kl = native.kl_divergence(mu, logvar)[0][0]
689
+ result = {
690
+ "loss": losses["reconstruction"] + agent.kl_weight * kl,
691
+ "kl": kl,
692
+ **losses,
693
+ }
694
+ if policy.keypose_phase_weight > 0:
695
+ logits = read_phase_logits(agent)
696
+ if (
697
+ phase_labels is None
698
+ or phase_labels.dtype != torch.long
699
+ or phase_labels.shape != logits.shape[:1]
700
+ or not ((phase_labels >= 0) & (phase_labels < 6)).all()
701
+ ):
702
+ raise ValueError(
703
+ "Expected one integer primitive label in [0, 5] per observation"
704
+ )
705
+ phase_ce = F.cross_entropy(logits, phase_labels)
706
+ result.update(
707
+ loss=result["loss"] + policy.keypose_phase_weight * phase_ce,
708
+ phase_ce=phase_ce,
709
+ phase_accuracy=(logits.argmax(-1) == phase_labels).float().mean(),
710
+ )
711
+ if policy.has_chunk_phase_head:
712
+ logits = read_phase_logits(agent)
713
+ classes = DONE_PHASE + int(policy.chunk_phase_done)
714
+ if (
715
+ phase_labels is None
716
+ or phase_labels.dtype != torch.long
717
+ or phase_labels.shape != prediction.shape[:2]
718
+ or logits.shape != (*prediction.shape[:2], classes)
719
+ or not (
720
+ (phase_labels == -100) | ((phase_labels >= 0) & (phase_labels < classes))
721
+ ).all()
722
+ or (policy.chunk_phase_done and (phase_labels == -100).any())
723
+ or not ((phase_labels[:, 0] >= 0) & (phase_labels[:, 0] < DONE_PHASE)).all()
724
+ ):
725
+ raise ValueError(
726
+ "Expected valid future phase labels and -100 only for padding"
727
+ )
728
+ phase_ce = F.cross_entropy(
729
+ logits.flatten(0, 1), phase_labels.flatten(), ignore_index=-100
730
+ )
731
+ valid = phase_labels != -100
732
+ # Keep CE as a diagnostic at weight zero, but remove its graph from
733
+ # the objective entirely: unused head parameters must get no gradient.
734
+ if policy.chunk_phase_weight > 0:
735
+ result["loss"] = result["loss"] + policy.chunk_phase_weight * phase_ce
736
+ result.update(
737
+ phase_ce=phase_ce,
738
+ phase_accuracy=(logits.argmax(-1)[valid] == phase_labels[valid])
739
+ .float()
740
+ .mean(),
741
+ phase_query0_accuracy=(logits[:, 0].argmax(-1) == phase_labels[:, 0])
742
+ .float()
743
+ .mean(),
744
+ )
745
+ if policy.keypose_stop_head:
746
+ logits = read_stop_logits(agent)
747
+ if (
748
+ stop_labels is None
749
+ or not stop_labels.is_floating_point()
750
+ or stop_labels.shape != logits.shape
751
+ or logits.ndim != 1
752
+ or not ((stop_labels == 0) | (stop_labels == 1)).all()
753
+ ):
754
+ raise ValueError("Expected one float binary stop label per observation")
755
+ stop_bce = F.binary_cross_entropy_with_logits(logits, stop_labels)
756
+ result.update(
757
+ loss=result["loss"] + policy.keypose_stop_weight * stop_bce,
758
+ stop_bce=stop_bce,
759
+ stop_accuracy=((logits >= 0) == stop_labels.bool()).float().mean(),
760
+ stop_predicted_positive=(logits >= 0).float().mean(),
761
+ )
762
+ if policy.chunk_switch_head:
763
+ fraction = read_switch_fraction(agent)
764
+ if (
765
+ switch_labels is None
766
+ or not switch_labels.is_floating_point()
767
+ or switch_labels.shape != fraction.shape
768
+ or not ((switch_labels > 0) & (switch_labels <= 1)).all()
769
+ ):
770
+ raise ValueError("Expected one remaining-steps fraction in (0, 1] per observation")
771
+ switch_l1 = (fraction - switch_labels).abs().mean()
772
+ # At weight zero the head stays a diagnostic: no graph, no gradient.
773
+ if policy.chunk_switch_weight > 0:
774
+ result["loss"] = result["loss"] + policy.chunk_switch_weight * switch_l1
775
+ result["switch_l1"] = switch_l1.detach()
776
+ if policy.has_chunk_done_head:
777
+ logits = read_done_logits(agent)
778
+ if (
779
+ done_labels is None
780
+ or not done_labels.is_floating_point()
781
+ or done_labels.shape != prediction.shape[:2]
782
+ or logits.shape != done_labels.shape
783
+ or not ((done_labels == 0) | (done_labels == 1)).all()
784
+ or (done_labels[:, 0] != 0).any()
785
+ ):
786
+ raise ValueError("Expected one binary end label per item, item 0 never done")
787
+ done_bce = F.binary_cross_entropy_with_logits(logits, done_labels)
788
+ with torch.no_grad():
789
+ # Training forwards carry the posterior latent: diagnostics only.
790
+ items = batch_done_items(logits)
791
+ truth = (1 - done_labels).sum(-1)
792
+ result.update(
793
+ loss=result["loss"] + policy.chunk_done_weight * done_bce,
794
+ done_bce=done_bce,
795
+ done_accuracy=((logits >= 0) == done_labels.bool()).float().mean(),
796
+ done_items_exact=(items == truth).float().mean(),
797
+ )
798
+ if policy.keypose_dense_head:
799
+ dense_prediction = read_dense_actions(agent)
800
+ if (
801
+ dense_labels is None
802
+ or dense_labels.shape != prediction.shape
803
+ or dense_prediction.shape != prediction.shape
804
+ or not torch.isfinite(dense_labels).all()
805
+ ):
806
+ raise ValueError(
807
+ "Expected finite normalized dense labels matching the original Q30 horizon"
808
+ )
809
+ dense_loss = pose_reconstruction(
810
+ dense_prediction,
811
+ dense_labels,
812
+ ActionLossConfig(method="group_balanced"),
813
+ )
814
+ result.update(
815
+ loss=result["loss"]
816
+ + policy.keypose_dense_weight * dense_loss["reconstruction"],
817
+ **{f"dense_{key}": value for key, value in dense_loss.items()},
818
+ )
819
+ return result
820
+ if policy.method != "flow":
821
+ return objective.compute_loss(agent, native, obs, actions)
822
+ obs = {**obs, "rgb": agent.normalize(obs["rgb"].float() / 255)}
823
+ loss = agent.model.training_loss(obs, actions)
824
+ return {"loss": loss, "flow_mse": loss}
825
+
826
+
827
+ class ChunkDatasetConfig(BaseModel, frozen=True):
828
+ model_config = ConfigDict(
829
+ arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
830
+ )
831
+ dataset: Any
832
+ """Pinned native preprocessed StackCube dataset with state25 and delta actions."""
833
+ action_encoding: ActionEncoding = "controller"
834
+ """Existing position-only controller labels, or dense fixed-reference pose6D."""
835
+ source: Path | None = None
836
+ """Pose6D H5 used to verify robot-root axes in every saved state."""
837
+ chunk_anchor: ChunkAnchor = "chunk_start_tcp"
838
+ """Label origin; identity makes every target an absolute world pose."""
839
+ phase_supervision: bool = False
840
+ """Return each valid future action's primitive label; ignore padded labels."""
841
+ phase_done: bool = False
842
+ """Label padded items DONE_PHASE instead of ignoring them."""
843
+ chunk_pose_supervision: ChunkPoseSupervision = "dense"
844
+ """Only valid-slot pose labels change; phase and fitted scales do not."""
845
+ chunk_gripper_supervision: ChunkGripperSupervision = "future"
846
+ """Future commands or current command repeated in valid slots only."""
847
+ chunk_padding: ChunkPadding = "terminal"
848
+ """Measured terminal pose/last gripper, or repeat the current complete target."""
849
+ chunk_normalization_population: Literal["dense", "supervised"] = "dense"
850
+ """Action statistics use dense valid pairs, or one complete current target per
851
+ observation for the repeated current-target recipe."""
852
+ chunk_label_offset: NonNegativeInt = 0
853
+ """Slot i supervises time t+offset+i; zero preserves every existing recipe."""
854
+ chunk_waypoint_threshold_m: PositiveFloat | None = None
855
+ """AWE distance threshold for future_waypoint labels."""
856
+ chunk_bspline_knots: PositiveInt | None = None
857
+ """Unique knots per segment for bspline labels (lim.bspline_chunk)."""
858
+ switch_supervision: bool = False
859
+ """Also return the current primitive's remaining-steps fraction."""
860
+ done_supervision: bool = False
861
+ """Also return each item's end-of-demonstration label (lim.chunk_done)."""
862
+
863
+ @model_validator(mode="after")
864
+ def check_supervision(self):
865
+ if (self.chunk_pose_supervision == "bspline") != (self.chunk_bspline_knots is not None):
866
+ raise ValueError("Exactly the B-spline supervision carries a knot count")
867
+ if self.chunk_pose_supervision == "bspline" and (
868
+ self.action_encoding != "rotation6d"
869
+ or self.phase_supervision
870
+ or self.switch_supervision
871
+ or self.done_supervision
872
+ ):
873
+ raise ValueError("B-spline segments carry pose6D rows and no per-item labels")
874
+ if self.done_supervision and (
875
+ self.action_encoding != "rotation6d"
876
+ or self.chunk_padding != "terminal"
877
+ or self.chunk_label_offset
878
+ or self.chunk_pose_supervision == "phase_segments"
879
+ ):
880
+ raise ValueError("End labels mark consecutive pose6D items with terminal padding")
881
+ if self.chunk_padding == "current_target" and (
882
+ self.chunk_pose_supervision != "current_endpoint"
883
+ or self.chunk_gripper_supervision != "current"
884
+ ):
885
+ raise ValueError(
886
+ "Current-target padding requires current endpoint and gripper"
887
+ )
888
+ if (
889
+ self.chunk_gripper_supervision != "future"
890
+ and self.action_encoding != "rotation6d"
891
+ ):
892
+ raise ValueError("Chunk gripper supervision requires pose6D data")
893
+ if (
894
+ self.chunk_pose_supervision != "dense"
895
+ and self.action_encoding != "rotation6d"
896
+ ):
897
+ raise ValueError(
898
+ "Endpoint labels require pose6D chunk-relative data"
899
+ )
900
+ if self.chunk_normalization_population == "supervised" and (
901
+ self.chunk_pose_supervision != "current_endpoint"
902
+ or self.chunk_gripper_supervision != "current"
903
+ or self.chunk_padding != "current_target"
904
+ ):
905
+ raise ValueError(
906
+ "Supervised normalization requires repeated complete current-target endpoint labels"
907
+ )
908
+ return self
909
+
910
+
911
+ def remaining_fraction(ends, labels):
912
+ """Steps left in each observation's primitive, min(steps, horizon)/horizon."""
913
+ remaining = torch.from_numpy(ends).long()[labels] - torch.arange(len(labels))
914
+ if not (remaining >= 1).all():
915
+ raise ValueError("Every observation must have at least one remaining step")
916
+ return remaining.clamp(max=SWITCH_HORIZON).float() / SWITCH_HORIZON
917
+
918
+
919
+ class ChunkRelativeDataset(Dataset):
920
+ """Encode actual controller goals relative to each query's current TCP.
921
+
922
+ StackCube panda_wristcam state = qpos9, qvel9, world TCP pose7.
923
+ The root orientation is identity and pd_ee_delta_pos uses scale 0.1 m.
924
+ Positions at future steps are supervised data only, never policy inputs.
925
+ """
926
+
927
+ def __init__(self, config: ChunkDatasetConfig):
928
+ self.config = config
929
+ self.dataset = config.dataset
930
+ self.phase_chunks = []
931
+ self.waypoint_counts = []
932
+ if config.phase_supervision and config.action_encoding != "rotation6d":
933
+ raise ValueError("Chunk phase labels require pose6D data")
934
+ if config.phase_done and not config.phase_supervision:
935
+ raise ValueError("The done phase extends per-item phase labels")
936
+ for trajectory in self.dataset.trajectories["observations"]:
937
+ if trajectory["state"].shape[-1] != 25:
938
+ raise ValueError("Chunk labels require the audited state25 layout")
939
+ if config.action_encoding == "rotation6d":
940
+ import h5py
941
+
942
+ if config.source is None:
943
+ raise ValueError(
944
+ "Pose chunk-relative labels require source H5 root-frame verification"
945
+ )
946
+ self.chunks = []
947
+ self.world_targets = []
948
+ self.segment_fits = []
949
+ self.switch_labels = []
950
+ self.done_chunks = []
951
+ populations = []
952
+ with h5py.File(config.source) as data:
953
+ names = sorted(data, key=lambda n: int(n.split("_")[-1]))[
954
+ : self.dataset.num_traj
955
+ ]
956
+ if len(names) != self.dataset.num_traj:
957
+ raise ValueError(
958
+ "Source trajectory count differs from the native dataset"
959
+ )
960
+ for name, actions, obs in zip(
961
+ names,
962
+ self.trajectories["actions"],
963
+ self.trajectories["observations"],
964
+ strict=True,
965
+ ):
966
+ tcp = obs["state"][:, 18:25]
967
+ if actions.shape[-1] != 7 or len(tcp) != len(actions) + 1:
968
+ raise ValueError(
969
+ "Expected unencoded pose actions and a terminal TCP"
970
+ )
971
+ stored_tcp = torch.from_numpy(data[name]["obs/extra/tcp_pose"][:])
972
+ torch.testing.assert_close(tcp, stored_tcp, atol=0, rtol=0)
973
+ roots = data[name]["env_states/articulations/panda_wristcam"][
974
+ :, 3:7
975
+ ]
976
+ np.testing.assert_allclose(
977
+ roots, np.tile([1, 0, 0, 0], (len(roots), 1)), atol=1e-5
978
+ )
979
+ goals = controller_pose_targets(actions, tcp[:-1])
980
+ terminal = encode_keypose(tcp[-1], actions[-1, -1])[None]
981
+ goals = torch.cat([goals, terminal])
982
+ if config.chunk_pose_supervision == "bspline":
983
+ labels, fit = demonstration_segments(
984
+ goals, tcp, config.chunk_bspline_knots
985
+ )
986
+ if labels.shape[1] != self.num_queries:
987
+ raise ValueError("Segment rows differ from the query count")
988
+ self.segment_fits.append(fit)
989
+ populations.append(labels.flatten(0, 1))
990
+ self.chunks.append(labels)
991
+ self.world_targets.append(goals)
992
+ continue
993
+ times = (
994
+ torch.arange(len(actions))[:, None]
995
+ + config.chunk_label_offset
996
+ + torch.arange(self.num_queries)[None]
997
+ )
998
+ valid = times < len(actions)
999
+ if config.done_supervision:
1000
+ self.done_chunks.append(labels_from_valid(valid))
1001
+ if config.chunk_pose_supervision == "future_waypoint":
1002
+ from lim.waypoints import next_waypoint, select_waypoints
1003
+
1004
+ waypoints = select_waypoints(
1005
+ goals[: len(actions), :3].numpy(),
1006
+ config.chunk_waypoint_threshold_m,
1007
+ actions[:, -1].numpy(),
1008
+ )
1009
+ self.waypoint_counts.append((len(waypoints), len(actions)))
1010
+ following = torch.from_numpy(
1011
+ next_waypoint(len(actions), waypoints)
1012
+ )
1013
+ if (
1014
+ config.phase_supervision
1015
+ or config.chunk_pose_supervision not in ("dense", "future_waypoint")
1016
+ ):
1017
+ from lim.keypose_phase import KEYPOSE_PHASE_NAMES
1018
+
1019
+ key = data[name]["keyframes"]
1020
+ labels = torch.from_numpy(
1021
+ key["action_keyframe_index"][:]
1022
+ ).long()
1023
+ starts, ends = key["start_action"][:], key["end_action"][:]
1024
+ # Six-class phase labels exist only for the canonical
1025
+ # StackCube primitives; other tasks' experts record
1026
+ # their own primitive list, used for endpoints alone.
1027
+ segments = len(starts)
1028
+ if (
1029
+ (
1030
+ config.phase_supervision
1031
+ and tuple(key["name"].asstr()[:]) != KEYPOSE_PHASE_NAMES
1032
+ )
1033
+ or segments < 1
1034
+ or starts.shape != (segments,)
1035
+ or ends.shape != (segments,)
1036
+ or starts[0] != 0
1037
+ or ends[-1] != len(actions)
1038
+ or np.any(ends <= starts)
1039
+ or not np.array_equal(starts[1:], ends[:-1])
1040
+ or not np.array_equal(
1041
+ labels.numpy(), np.repeat(np.arange(segments), ends - starts)
1042
+ )
1043
+ ):
1044
+ raise ValueError(
1045
+ "Expected aligned canonical primitive indices"
1046
+ )
1047
+ phase = labels[times.clamp(max=len(actions) - 1)].clone()
1048
+ phase[~valid] = DONE_PHASE if config.phase_done else -100
1049
+ self.phase_chunks.append(phase)
1050
+ relative = world_to_chunk_relative(
1051
+ goals[times.clamp(max=len(actions))],
1052
+ resolve_anchor(tcp[:-1, None], config.chunk_anchor),
1053
+ )
1054
+ # The default population preserves the original dense labels
1055
+ # and physical loss weights across supervision variants.
1056
+ if config.chunk_normalization_population == "dense":
1057
+ populations.append(relative[valid])
1058
+ if config.chunk_pose_supervision == "future_waypoint":
1059
+ replacement = world_to_chunk_relative(
1060
+ goals[following[times.clamp(max=len(actions) - 1)]],
1061
+ resolve_anchor(tcp[:-1, None], config.chunk_anchor),
1062
+ )
1063
+ relative[valid] = torch.cat(
1064
+ [replacement[valid][:, :9], relative[valid][:, -1:]], -1
1065
+ )
1066
+ elif config.chunk_pose_supervision != "dense":
1067
+ poses = torch.from_numpy(key["target_pose_world"][:])
1068
+ grippers = torch.from_numpy(key["gripper_command"][:])
1069
+ if (
1070
+ poses.shape != (segments, 7)
1071
+ or grippers.shape != (segments,)
1072
+ or not torch.isfinite(poses).all()
1073
+ or not torch.isfinite(grippers).all()
1074
+ or not torch.equal(grippers[labels], actions[:, -1])
1075
+ ):
1076
+ raise ValueError(
1077
+ "Endpoint and dense primitive labels disagree"
1078
+ )
1079
+ endpoints = encode_keypose(poses, grippers)
1080
+ if config.chunk_pose_supervision == "phase_segments":
1081
+ if self.num_queries != 2:
1082
+ raise ValueError("Phase segments require exactly two queries")
1083
+ segments = torch.stack(
1084
+ [labels, (labels + 1).clamp(max=5)], -1
1085
+ )
1086
+ # Both slots carry their own primitive gripper command.
1087
+ relative = world_to_chunk_relative(
1088
+ endpoints[segments],
1089
+ resolve_anchor(tcp[:-1, None], config.chunk_anchor),
1090
+ )
1091
+ self.switch_labels.append(remaining_fraction(ends, labels))
1092
+ self.chunks.append(relative)
1093
+ self.world_targets.append(goals)
1094
+ continue
1095
+ if config.switch_supervision:
1096
+ self.switch_labels.append(remaining_fraction(ends, labels))
1097
+ endpoint_indices = (
1098
+ labels[times.clamp(max=len(actions) - 1)]
1099
+ if config.chunk_pose_supervision == "future_endpoint"
1100
+ else labels[:, None].expand_as(times)
1101
+ )
1102
+ replacement = world_to_chunk_relative(
1103
+ endpoints[endpoint_indices],
1104
+ resolve_anchor(tcp[:-1, None], config.chunk_anchor),
1105
+ )
1106
+ # Preserve original dense terminal padding and every
1107
+ # future gripper command, including in current_endpoint.
1108
+ relative[valid] = torch.cat(
1109
+ [replacement[valid][:, :9], relative[valid][:, -1:]], -1
1110
+ )
1111
+ if config.chunk_gripper_supervision == "current":
1112
+ # Change the supervised gripper timing only. The current
1113
+ # command is not the phase-end command and never replaces
1114
+ # the terminal padding or dense normalization population.
1115
+ repeated = actions[:, -1, None].expand_as(times)
1116
+ relative[..., -1][valid] = repeated[valid]
1117
+ if config.chunk_padding == "current_target":
1118
+ # Query zero always exists and already has the complete
1119
+ # current endpoint. Only replace out-of-range slots.
1120
+ repeated = relative[:, :1].expand_as(relative)
1121
+ relative[~valid] = repeated[~valid]
1122
+ if config.chunk_normalization_population == "supervised":
1123
+ # One target per original observation, independent of Q
1124
+ # and padding, matching the old KeyposeDataset weighting.
1125
+ populations.append(relative[:, 0])
1126
+ self.chunks.append(relative)
1127
+ self.world_targets.append(goals)
1128
+ self.normalization_actions = torch.cat(populations)
1129
+ self.target_contract = pose_target_contract(
1130
+ config.chunk_anchor,
1131
+ config.chunk_pose_supervision,
1132
+ config.chunk_gripper_supervision,
1133
+ config.chunk_padding,
1134
+ config.chunk_normalization_population,
1135
+ config.chunk_label_offset,
1136
+ config.chunk_waypoint_threshold_m,
1137
+ config.chunk_bspline_knots,
1138
+ )
1139
+ all_chunks = torch.cat(self.chunks)
1140
+ tensors = {
1141
+ "sample_indices": torch.tensor(self.dataset.slices),
1142
+ **(
1143
+ {"segment_labels": all_chunks}
1144
+ if self.segment_fits
1145
+ else {
1146
+ "pose_labels": all_chunks[..., :9],
1147
+ "gripper_labels": all_chunks[..., -1],
1148
+ }
1149
+ ),
1150
+ "normalization_population": self.normalization_actions,
1151
+ }
1152
+ if self.phase_chunks:
1153
+ tensors["phase_labels"] = torch.cat(self.phase_chunks)
1154
+ if self.switch_labels:
1155
+ tensors["switch_labels"] = torch.cat(self.switch_labels)
1156
+ if self.done_chunks:
1157
+ tensors["done_labels"] = torch.cat(self.done_chunks)
1158
+ self.supervision_audit = {
1159
+ "pose_supervision": config.chunk_pose_supervision,
1160
+ "gripper_supervision": config.chunk_gripper_supervision,
1161
+ "samples": len(self.dataset.slices),
1162
+ "normalization_samples": len(self.normalization_actions),
1163
+ **{
1164
+ f"{name}_sha256": hashlib.sha256(
1165
+ tensor.contiguous().numpy().tobytes()
1166
+ ).hexdigest()
1167
+ for name, tensor in tensors.items()
1168
+ },
1169
+ **(
1170
+ {
1171
+ "waypoints": sum(w for w, _ in self.waypoint_counts),
1172
+ "actions": sum(n for _, n in self.waypoint_counts),
1173
+ "waypoint_threshold_m": config.chunk_waypoint_threshold_m,
1174
+ }
1175
+ if self.waypoint_counts
1176
+ else {}
1177
+ ),
1178
+ **(
1179
+ {
1180
+ "segment_knots": config.chunk_bspline_knots,
1181
+ "fitted_unique_knots": sum(f["knots"] for f in self.segment_fits),
1182
+ "fitted_control_points": sum(
1183
+ f["control_points"] for f in self.segment_fits
1184
+ ),
1185
+ "max_fit_error": max(f["max_error"] for f in self.segment_fits),
1186
+ }
1187
+ if self.segment_fits
1188
+ else {}
1189
+ ),
1190
+ **(
1191
+ {
1192
+ # Over the sampled observations, i.e. what training sees.
1193
+ "done_items": len(self.dataset.slices) * self.num_queries,
1194
+ "done_positives": int(
1195
+ sum(self.done_chunks[j][t].sum() for j, t in self.dataset.slices)
1196
+ ),
1197
+ }
1198
+ if self.done_chunks
1199
+ else {}
1200
+ ),
1201
+ **(
1202
+ {
1203
+ "phase_done_items": int(
1204
+ sum(
1205
+ (self.phase_chunks[j][t] == DONE_PHASE).sum()
1206
+ for j, t in self.dataset.slices
1207
+ )
1208
+ )
1209
+ }
1210
+ if config.phase_done
1211
+ else {}
1212
+ ),
1213
+ }
1214
+
1215
+ def __getattr__(self, name):
1216
+ return getattr(self.dataset, name)
1217
+
1218
+ def __len__(self):
1219
+ return len(self.dataset)
1220
+
1221
+ def __getitem__(self, index):
1222
+ trajectory, start = self.dataset.slices[index]
1223
+ if self.config.action_encoding == "rotation6d":
1224
+ return {
1225
+ "observations": {
1226
+ k: v[start]
1227
+ for k, v in self.trajectories["observations"][trajectory].items()
1228
+ },
1229
+ "actions": self.chunks[trajectory][start],
1230
+ **(
1231
+ {"phase": self.phase_chunks[trajectory][start]}
1232
+ if self.config.phase_supervision
1233
+ else {}
1234
+ ),
1235
+ **(
1236
+ {"switch": self.switch_labels[trajectory][start]}
1237
+ if self.switch_labels
1238
+ else {}
1239
+ ),
1240
+ **(
1241
+ {"done": self.done_chunks[trajectory][start]}
1242
+ if self.done_chunks
1243
+ else {}
1244
+ ),
1245
+ }
1246
+ sample = self.dataset[index]
1247
+ positions = self.dataset.trajectories["observations"][trajectory]["state"][
1248
+ :, 18:21
1249
+ ]
1250
+ length = len(self.dataset.trajectories["actions"][trajectory])
1251
+ if len(positions) != length + 1:
1252
+ raise ValueError("Expected terminal TCP observation for stationary padding")
1253
+ times = torch.arange(start, start + self.dataset.num_queries).clamp(max=length)
1254
+ actions = sample["actions"].clone()
1255
+ # Native labels contain already bounded normalized delta commands. Do not
1256
+ # clip the resulting chunk targets: legitimate offsets can exceed +/-1.
1257
+ actions[:, :3] += (positions[times] - positions[start]) / 0.1
1258
+ return {"observations": sample["observations"], "actions": actions}
1259
+
1260
+
1261
+ class TargetTransportConfig(BaseModel, frozen=True):
1262
+ model_config = ConfigDict(
1263
+ arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
1264
+ )
1265
+ wrapped: Any
1266
+ """Agent or environment at the existing native evaluator boundary."""
1267
+ action_encoding: ActionEncoding = "controller"
1268
+ """Position-only scaled world goals, or world xyz plus 6D rotation goals."""
1269
+ chunk_anchor: ChunkAnchor = "chunk_start_tcp"
1270
+ """Frame the model's output is expressed in; must match its training labels."""
1271
+
1272
+
1273
+ class TargetFrameAgent:
1274
+ """Express all predicted TCP goals in one frame before native ensembling."""
1275
+
1276
+ def __init__(self, config: TargetTransportConfig):
1277
+ self.config = config
1278
+ self.wrapped = config.wrapped
1279
+
1280
+ def __getattr__(self, name):
1281
+ return getattr(self.wrapped, name)
1282
+
1283
+ def get_action(self, obs):
1284
+ target = self.wrapped.get_action(obs).clone()
1285
+ if self.config.action_encoding == "rotation6d":
1286
+ # Restore with the SAME frame the labels were written in.
1287
+ return chunk_relative_to_world(
1288
+ target,
1289
+ resolve_anchor(obs["state"][:, None, 18:25], self.config.chunk_anchor),
1290
+ )
1291
+ if self.config.chunk_anchor != "chunk_start_tcp":
1292
+ raise ValueError("Absolute anchors require the pose6D encoding")
1293
+ target[:, :, :3] += obs["state"][:, None, 18:21] / 0.1
1294
+ return target
1295
+
1296
+
1297
+ class TargetFrameEnv:
1298
+ """Convert the ensembled goal to the current controller delta exactly once."""
1299
+
1300
+ def __init__(self, config: TargetTransportConfig):
1301
+ self.config = config
1302
+ self.wrapped = config.wrapped
1303
+ self.current_tcp = None
1304
+ if config.action_encoding == "rotation6d":
1305
+ import gymnasium as gym
1306
+
1307
+ self.action_space = gym.spaces.Box(
1308
+ -np.inf, np.inf, (self.wrapped.num_envs, 10), dtype=np.float32
1309
+ )
1310
+ self.single_action_space = gym.spaces.Box(
1311
+ -np.inf, np.inf, (10,), dtype=np.float32
1312
+ )
1313
+
1314
+ def __getattr__(self, name):
1315
+ return getattr(self.wrapped, name)
1316
+
1317
+ def remember(self, observation):
1318
+ self.current_tcp = np.array(observation["state"][:, 18:25], copy=True)
1319
+
1320
+ def reset(self):
1321
+ observation, info = self.wrapped.reset()
1322
+ self.remember(observation)
1323
+ return observation, info
1324
+
1325
+ def step(self, target):
1326
+ if self.config.action_encoding == "rotation6d":
1327
+ delta = world_to_chunk_relative(
1328
+ torch.as_tensor(target), torch.as_tensor(self.current_tcp)
1329
+ )
1330
+ action = sixd_to_controller(delta).numpy()
1331
+ else:
1332
+ action = np.array(target, copy=True)
1333
+ action[:, :3] -= self.current_tcp[:, :3] / 0.1
1334
+ result = self.wrapped.step(action)
1335
+ self.remember(result[0])
1336
+ return result
1337
+
1338
+
1339
+ def evaluation_transport(agent, env, policy):
1340
+ if policy.keypose is not None:
1341
+ return (
1342
+ FirstKeyposeAgent(FirstKeyposeAgentConfig(agent=agent)),
1343
+ KeyposeEnv(KeyposeEnvConfig(env=env, control=policy.keypose)),
1344
+ )
1345
+ if policy.method == "chunk_relative":
1346
+ return (
1347
+ TargetFrameAgent(
1348
+ TargetTransportConfig(
1349
+ wrapped=agent,
1350
+ action_encoding=policy.action_encoding,
1351
+ chunk_anchor=policy.chunk_anchor,
1352
+ )
1353
+ ),
1354
+ # The environment converts world goals against the real measured TCP
1355
+ # under every anchor mode; that boundary is physical, not a label frame.
1356
+ TargetFrameEnv(
1357
+ TargetTransportConfig(
1358
+ wrapped=env, action_encoding=policy.action_encoding
1359
+ )
1360
+ ),
1361
+ )
1362
+ if policy.action_loss.binary_gripper:
1363
+ env = BinaryGripperEnv(BinaryGripperEnvConfig(env=env))
1364
+ if policy.action_encoding == "rotation6d":
1365
+ return agent, Rotation6DEnv(EncodedEnvConfig(env=env))
1366
+ return agent, env
fair-comparison/extract-train-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/extract-train-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/extract-train-v1/code/lim/action_objective.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pose ACT loss groups and binary-gripper inference semantics."""
2
+
3
+ import hashlib
4
+ from typing import Any, Literal
5
+
6
+ import numpy as np
7
+ import torch
8
+ import torch.nn.functional as F
9
+ from pydantic import (
10
+ BaseModel,
11
+ ConfigDict,
12
+ NonNegativeFloat,
13
+ PositiveFloat,
14
+ model_validator,
15
+ )
16
+ from torch import nn
17
+
18
+
19
+ class ActionLossConfig(BaseModel, frozen=True):
20
+ model_config = ConfigDict(
21
+ extra="forbid", use_attribute_docstrings=True, allow_inf_nan=False
22
+ )
23
+ method: Literal["native", "gripper_bce", "group_balanced"] = "native"
24
+ """Native 3:6:1 L1; 3:6:1 with gripper BCE; or equal means of the three L1 groups."""
25
+ position_axis_weights: tuple[PositiveFloat, PositiveFloat, PositiveFloat] = (
26
+ 1.0,
27
+ 1.0,
28
+ 1.0,
29
+ )
30
+ """XYZ absolute-error weights before averaging in group_balanced only.
31
+
32
+ Errors are in the coordinates supplied to the loss, including any fitted
33
+ normalization; this changes no labels, normalization or inference decoding.
34
+ """
35
+ group_weights: tuple[NonNegativeFloat, NonNegativeFloat, NonNegativeFloat] = (
36
+ 1.0,
37
+ 1.0,
38
+ 1.0,
39
+ )
40
+ """Position, rotation and gripper multipliers inside the group_balanced mean.
41
+
42
+ The reconstruction is (w_p L_p + w_R L_R + w_g L_g) / 3: (0.9, 1.8, 0.3)
43
+ is the per-coordinate 3:6:1 mean, (1, 1, 0) drops the gripper term with
44
+ the pose terms unchanged.
45
+ """
46
+ gripper_objective: Literal["l1", "bce"] = "l1"
47
+ """group_balanced only: the gripper group as L1 on +-1, or BCE on its logit
48
+ (then decoded as 2 p(open) - 1, as gripper_bce)."""
49
+
50
+ @model_validator(mode="after")
51
+ def check_position_weights(self):
52
+ if self.method != "group_balanced" and (
53
+ self.position_axis_weights != (1.0, 1.0, 1.0)
54
+ or self.group_weights != (1.0, 1.0, 1.0)
55
+ or self.gripper_objective != "l1"
56
+ ):
57
+ raise ValueError(
58
+ "Non-default position or group weights and the gripper objective"
59
+ " require group_balanced"
60
+ )
61
+ if not any(self.group_weights[:2]):
62
+ raise ValueError("At least one pose group must keep a positive weight")
63
+ return self
64
+
65
+ @property
66
+ def binary_gripper(self):
67
+ """Whether the last output is a gripper logit with binary execution."""
68
+ return self.method == "gripper_bce" or self.gripper_objective == "bce"
69
+
70
+ @property
71
+ def plain_groups(self):
72
+ """group_balanced with its historical equal groups and L1 gripper."""
73
+ return (
74
+ self.method == "group_balanced"
75
+ and self.group_weights == (1.0, 1.0, 1.0)
76
+ and self.gripper_objective == "l1"
77
+ )
78
+
79
+
80
+ def pose_reconstruction(prediction, actions, config: ActionLossConfig):
81
+ if prediction.shape != actions.shape or actions.shape[-1] != 10:
82
+ raise ValueError(
83
+ "Pose objectives require matching ten-dimensional action chunks"
84
+ )
85
+ position = F.l1_loss(prediction[..., :3], actions[..., :3])
86
+ rotation = F.l1_loss(prediction[..., 3:9], actions[..., 3:9])
87
+ groups = {"position_l1": position, "rotation_l1": rotation}
88
+ if config.method == "gripper_bce":
89
+ labels = (actions[..., -1] + 1) / 2
90
+ gripper = F.binary_cross_entropy_with_logits(prediction[..., -1], labels)
91
+ reconstruction = 0.3 * position + 0.6 * rotation + 0.1 * gripper
92
+ groups["gripper_bce"] = gripper
93
+ else:
94
+ if config.gripper_objective == "bce":
95
+ labels = (actions[..., -1] + 1) / 2
96
+ gripper = F.binary_cross_entropy_with_logits(prediction[..., -1], labels)
97
+ groups["gripper_bce"] = gripper
98
+ else:
99
+ gripper = F.l1_loss(prediction[..., -1], actions[..., -1])
100
+ groups["gripper_l1"] = gripper
101
+ if config.method == "group_balanced":
102
+ # Reuse the original tensor/graph at the default, preserving the
103
+ # exact historical loss and gradients rather than multiplying by 1.
104
+ weighted_position = position
105
+ if config.position_axis_weights != (1.0, 1.0, 1.0):
106
+ weighted_position = (
107
+ (prediction[..., :3] - actions[..., :3]).abs()
108
+ * prediction.new_tensor(config.position_axis_weights)
109
+ ).mean()
110
+ groups["weighted_position_l1"] = weighted_position
111
+ if config.group_weights == (1.0, 1.0, 1.0):
112
+ reconstruction = (weighted_position + rotation + gripper) / 3
113
+ else:
114
+ w_p, w_r, w_g = config.group_weights
115
+ reconstruction = (
116
+ w_p * weighted_position + w_r * rotation + w_g * gripper
117
+ ) / 3
118
+ else:
119
+ reconstruction = F.l1_loss(prediction, actions)
120
+ return {"reconstruction": reconstruction, **groups}
121
+
122
+
123
+ def validate_binary_gripper(dataset):
124
+ """Validate every unpadded training label once; padding holds its final label."""
125
+ for actions in dataset.trajectories["actions"]:
126
+ gripper = actions[..., -1]
127
+ if not torch.all((gripper == -1) | (gripper == 1)):
128
+ raise ValueError("Binary gripper supervision requires exactly -1/+1 labels")
129
+
130
+
131
+ class BinaryGripperModelConfig(BaseModel, frozen=True):
132
+ model_config = ConfigDict(
133
+ arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
134
+ )
135
+ model: Any
136
+ """Native CVAE; the last output coordinate is a logit during training."""
137
+
138
+
139
+ class BinaryGripperModel(nn.Module):
140
+ def __init__(self, config: BinaryGripperModelConfig):
141
+ super().__init__()
142
+ self.config = config
143
+ self.base = config.model
144
+
145
+ def forward(self, obs, actions=None):
146
+ prediction, latent = self.base(obs, actions)
147
+ if actions is None:
148
+ # Native temporal aggregation averages 2*p(open)-1, equivalent to
149
+ # averaging probabilities. Do not threshold each chunk in isolation.
150
+ prediction = torch.cat(
151
+ [prediction[..., :-1], 2 * prediction[..., -1:].sigmoid() - 1], dim=-1
152
+ )
153
+ return prediction, latent
154
+
155
+
156
+ def unwrapped_state_sha256(model):
157
+ """Hash parameters/buffers as named without the BinaryGripperModel wrapper.
158
+
159
+ The wrapper draws no RNG and adds no parameters, so with the same seed this
160
+ equals the full initial-state hash of the same recipe with an L1 gripper.
161
+ """
162
+ prefixes = [f"{name}." for name, m in model.named_modules() if isinstance(m, BinaryGripperModel)]
163
+ if len(prefixes) != 1:
164
+ raise ValueError("Expected exactly one binary-gripper wrapper")
165
+ wrapped = prefixes[0] + "base."
166
+ digest = hashlib.sha256()
167
+ for name, tensor in model.state_dict().items():
168
+ if not name.startswith(wrapped):
169
+ raise ValueError(f"State outside the wrapped model: {name}")
170
+ digest.update((prefixes[0] + name[len(wrapped):]).encode())
171
+ digest.update(tensor.detach().cpu().contiguous().numpy().tobytes())
172
+ return digest.hexdigest()
173
+
174
+
175
+ class BinaryGripperEnvConfig(BaseModel, frozen=True):
176
+ model_config = ConfigDict(
177
+ arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
178
+ )
179
+ env: Any
180
+ """Physical environment receiving controller commands after temporal averaging."""
181
+
182
+
183
+ class BinaryGripperEnv:
184
+ def __init__(self, config: BinaryGripperEnvConfig):
185
+ self.config = config
186
+ self.commands = 0
187
+ self.open_commands = 0
188
+ self.close_commands = 0
189
+ self.switches = 0
190
+ self.previous_gripper = None
191
+
192
+ def __getattr__(self, name):
193
+ return getattr(self.config.env, name)
194
+
195
+ def reset(self, *args, **kwargs):
196
+ self.previous_gripper = None
197
+ return self.config.env.reset(*args, **kwargs)
198
+
199
+ def step(self, action):
200
+ command = np.array(action, copy=True)
201
+ score = command[..., -1]
202
+ if not np.isfinite(score).all():
203
+ raise ValueError("Nonfinite ensembled gripper probability")
204
+ gripper = np.where(score >= 0, 1.0, -1.0)
205
+ command[..., -1] = gripper # p(open)>=0.5 opens, including exact ties.
206
+ self.commands += gripper.size
207
+ self.open_commands += int((gripper == 1).sum())
208
+ self.close_commands += int((gripper == -1).sum())
209
+ if self.previous_gripper is not None:
210
+ self.switches += int(
211
+ (
212
+ np.isfinite(self.previous_gripper)
213
+ & (self.previous_gripper != gripper)
214
+ ).sum()
215
+ )
216
+ result = self.config.env.step(command)
217
+ # Vector SAME_STEP autoreset starts a new episode after this last command.
218
+ done = np.asarray(result[2]) | np.asarray(result[3])
219
+ self.previous_gripper = np.where(done, np.nan, gripper)
220
+ return result
221
+
222
+ def diagnostics(self):
223
+ return {
224
+ "commands": self.commands,
225
+ "open_commands": self.open_commands,
226
+ "close_commands": self.close_commands,
227
+ "within_episode_switches": self.switches,
228
+ "rule": "average p(open) with native weights; >=0.5 opens; no hysteresis",
229
+ }
fair-comparison/extract-train-v1/code/lim/bspline_chunk.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """B-spline action segments for dense pose chunks (B-spline Policy, arXiv:2607.09648).
2
+
3
+ Each demonstration's dense world controller targets, followed by its measured
4
+ terminal pose, are fitted once with a cubic B-spline. Knots are inserted where
5
+ the reconstruction error is largest (FITPACK, scipy.interpolate.generate_knots)
6
+ until every sample of every fitted coordinate is within the tolerance, as in
7
+ the authors' ScipyBSplineCompression. The fitted coordinates are position (m),
8
+ the nine rotation-matrix entries and the gripper command: re-expressing control
9
+ points in an observation's TCP frame is then affine, and because the basis sums
10
+ to one on the domain, the re-expressed spline is exactly the re-expressed curve.
11
+
12
+ The observation at step i is labelled with the segment whose first domain
13
+ interval contains i (the authors start at the first knot at or after i, which
14
+ leaves the steps before that knot uncovered). A segment has ``domain_knots``
15
+ unique knots plus DEGREE support knots on each side, ``rows = domain_knots +
16
+ 2 * DEGREE``. Row r holds knot r in steps relative to i, then control point r in
17
+ the observation's own TCP frame (pose6D target10). Only the first
18
+ ``rows - DEGREE - 1`` control points enter the curve; the remaining rows carry
19
+ the following control points, as the authors' targets do. Past the fitted end,
20
+ knots and control points repeat the last one.
21
+ """
22
+
23
+ import numpy as np
24
+ import torch
25
+ from mani_skill.utils.geometry.rotation_conversions import quaternion_to_matrix
26
+ from scipy.interpolate import BSpline, generate_knots, make_lsq_spline
27
+
28
+ from lim.action_encoding import matrix_to_sixd, sixd_to_matrix
29
+
30
+ DEGREE = 3
31
+ FIT_TOLERANCE = 0.002
32
+ """The authors' fitting tolerance; here in m, rotation-matrix entries and gripper."""
33
+ GRID_ITEMS = 50
34
+ """Integer offsets a prediction is decoded on for execution (as the Q50 dense chunk)."""
35
+ KNOT_GAP = 1e-6
36
+ """Predicted knots below their predecessor move to predecessor + KNOT_GAP (the
37
+ authors' rollout projection)."""
38
+ WORLD_DIMENSIONS = 13
39
+ """Fitted world coordinates: xyz (m), rotation matrix row-major, gripper."""
40
+
41
+
42
+ def world_coordinates(goals):
43
+ """World target10 (xyz, pose6D, gripper) -> fitted world13 coordinates."""
44
+ if goals.shape[-1] != 10 or not torch.isfinite(goals).all():
45
+ raise ValueError("Expected finite world target10")
46
+ rotation = sixd_to_matrix(goals[..., 3:9]).flatten(-2)
47
+ return torch.cat([goals[..., :3], rotation, goals[..., 9:]], -1)
48
+
49
+
50
+ def fit_trajectory(world, tolerance):
51
+ """Cubic B-spline over steps 0..len-1 within ``tolerance`` at every sample.
52
+
53
+ Returns the spline and its largest absolute sample error; a trajectory the
54
+ knot sequence cannot bring under the tolerance keeps the last (densest)
55
+ knot vector, as the authors' fitter does."""
56
+ values = np.asarray(world, dtype=np.float64)
57
+ if values.ndim != 2 or values.shape[1] != WORLD_DIMENSIONS or len(values) < DEGREE + 1:
58
+ raise ValueError("Expected at least four world13 samples")
59
+ steps = np.arange(len(values), dtype=np.float64)
60
+ spline, error = None, None
61
+ for knots in generate_knots(steps, values, k=DEGREE, s=1e-12):
62
+ spline = make_lsq_spline(steps, values, knots, k=DEGREE)
63
+ error = float(np.abs(spline(steps) - values).max())
64
+ if error < tolerance:
65
+ break
66
+ return spline, error
67
+
68
+
69
+ def unique_knots(spline):
70
+ """Domain knots without FITPACK's repeated boundary copies."""
71
+ return spline.t[DEGREE:-DEGREE]
72
+
73
+
74
+ def to_anchor(world, anchor):
75
+ """World13 points (or control points) -> target10 relative to a TCP7 anchor.
76
+
77
+ Same coordinates as chunk_coordinates.world_to_chunk_relative, but affine in
78
+ the rotation-matrix entries rather than requiring orthonormal rotations."""
79
+ rotation = world[..., 3:12].unflatten(-1, (3, 3)) @ quaternion_to_matrix(
80
+ anchor[..., 3:]
81
+ ).transpose(-1, -2)
82
+ return torch.cat(
83
+ [(world[..., :3] - anchor[..., :3]) / 0.1, matrix_to_sixd(rotation), world[..., 12:]],
84
+ -1,
85
+ )
86
+
87
+
88
+ def segment_labels(spline, anchors, domain_knots):
89
+ """Segment parameters (rows, 1 + 10) for every observation step 0..len(anchors)-1.
90
+
91
+ ``anchors`` are the observations' measured TCP7 poses."""
92
+ if domain_knots < 2:
93
+ raise ValueError("A segment needs at least one domain interval")
94
+ rows = domain_knots + 2 * DEGREE
95
+ knots = np.asarray(spline.t, dtype=np.float64)
96
+ control = np.asarray(spline.c, dtype=np.float64)
97
+ unique = unique_knots(spline)
98
+ labels = []
99
+ for step in range(len(anchors)):
100
+ first = int(np.searchsorted(unique, step, side="right")) - 1
101
+ first = min(max(first, 0), len(unique) - 2)
102
+ segment_knots = knots[first : first + rows]
103
+ segment_control = control[first : first + rows]
104
+ segment_knots = np.concatenate(
105
+ [segment_knots, np.full(rows - len(segment_knots), knots[-1])]
106
+ )
107
+ segment_control = np.concatenate(
108
+ [segment_control, np.repeat(control[-1:], rows - len(segment_control), 0)]
109
+ )
110
+ relative = to_anchor(
111
+ torch.from_numpy(segment_control), anchors[step].double()[None]
112
+ )
113
+ labels.append(
114
+ torch.cat([torch.from_numpy(segment_knots - step)[:, None], relative], -1).float()
115
+ )
116
+ return torch.stack(labels)
117
+
118
+
119
+ def demonstration_segments(goals, tcp, domain_knots):
120
+ """Labels (actions, rows, 11) of one demonstration, and its fit summary.
121
+
122
+ ``goals``: world target10 of every action, then the terminal TCP target;
123
+ ``tcp``: measured TCP7 of every observation (the anchors)."""
124
+ spline, error = fit_trajectory(world_coordinates(goals), FIT_TOLERANCE)
125
+ labels = segment_labels(spline, tcp[: len(goals) - 1], domain_knots)
126
+ return labels, {
127
+ "knots": len(unique_knots(spline)),
128
+ "control_points": len(spline.c),
129
+ "max_error": error,
130
+ }
131
+
132
+
133
+ def segment_reconstruction(prediction, actions, config):
134
+ """Group-balanced L1 of the target10 columns with the knot column as a
135
+ fourth equal group (lim.action_objective.pose_reconstruction)."""
136
+ from lim.action_objective import pose_reconstruction
137
+
138
+ if prediction.shape != actions.shape or actions.shape[-1] != 11:
139
+ raise ValueError("Expected matching segment parameters (rows, 1 + target10)")
140
+ if config.method != "group_balanced":
141
+ raise ValueError("Segment labels use the group-balanced pose objective")
142
+ knot = torch.nn.functional.l1_loss(prediction[..., 0], actions[..., 0])
143
+ losses = pose_reconstruction(prediction[..., 1:], actions[..., 1:], config)
144
+ return {
145
+ **losses,
146
+ "knot_l1": knot,
147
+ "reconstruction": (3 * losses["reconstruction"] + knot) / 4,
148
+ }
149
+
150
+
151
+ class Segment:
152
+ """One predicted (or labelled) segment as a curve of relative target10 in steps."""
153
+
154
+ def __init__(self, parameters):
155
+ values = np.asarray(
156
+ parameters.detach().cpu() if torch.is_tensor(parameters) else parameters,
157
+ dtype=np.float64,
158
+ )
159
+ if values.ndim != 2 or values.shape[1] != 11 or len(values) < 2 * DEGREE + 2:
160
+ raise ValueError("Expected segment parameters (rows, 1 + target10)")
161
+ if not np.isfinite(values).all():
162
+ raise ValueError("Nonfinite segment parameters")
163
+ knots = values[:, 0].copy()
164
+ self.projected = 0
165
+ for index in range(1, len(knots)):
166
+ if knots[index] < knots[index - 1]:
167
+ knots[index] = knots[index - 1] + KNOT_GAP
168
+ self.projected += 1
169
+ self.knots = knots
170
+ self.spline = BSpline(knots, values[: -(DEGREE + 1), 1:], DEGREE, extrapolate=False)
171
+ self.start = float(knots[DEGREE])
172
+ self.end = float(knots[-(DEGREE + 1)])
173
+ if not self.end > self.start:
174
+ raise ValueError("Empty segment domain")
175
+
176
+ def __call__(self, offsets):
177
+ """Relative target10 at step offsets from the query, clamped to the domain.
178
+
179
+ The domain end takes its left limit: end padding repeats the last knot
180
+ more than DEGREE + 1 times, and scipy evaluates the end point on the
181
+ last (zero-width) interval, which returns zero."""
182
+ times = np.clip(
183
+ np.asarray(offsets, dtype=np.float64),
184
+ self.start,
185
+ np.nextafter(self.end, -np.inf),
186
+ )
187
+ return torch.from_numpy(self.spline(times)).float()
188
+
189
+ def grid(self, items):
190
+ """Values at integer offsets 0..items-1; offsets past the end hold the end."""
191
+ return self(np.arange(items))
fair-comparison/extract-train-v1/code/lim/chunk_coordinates.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "bspline",
36
+ ]
37
+ ChunkGripperSupervision = Literal["future", "current"]
38
+ ChunkPadding = Literal["terminal", "current_target"]
39
+
40
+
41
+ def pose_target_contract(
42
+ anchor: ChunkAnchor,
43
+ supervision: ChunkPoseSupervision,
44
+ gripper: ChunkGripperSupervision = "future",
45
+ padding: ChunkPadding = "terminal",
46
+ normalization_population: Literal["dense", "supervised"] = "dense",
47
+ label_offset: int = 0,
48
+ waypoint_threshold_m: float | None = None,
49
+ bspline_knots: int | None = None,
50
+ ):
51
+ """Persist target semantics for the audited StackCube world-frame dataset.
52
+
53
+ An identity anchor keeps coordinates in the stored TCP/keyframe frame; that
54
+ frame is world in this simulator, not a universal property of absolute poses.
55
+ Existing dense-population recipes retain their checkpoint contract exactly.
56
+ """
57
+ if anchor not in ("chunk_start_tcp", "identity"):
58
+ raise ValueError(f"Unknown chunk anchor mode: {anchor}")
59
+ if (supervision == "future_waypoint") != (waypoint_threshold_m is not None):
60
+ raise ValueError("Exactly the waypoint supervision carries a waypoint threshold")
61
+ if (supervision == "bspline") != (bspline_knots is not None):
62
+ raise ValueError("Exactly the B-spline supervision carries a knot count")
63
+ if supervision == "bspline":
64
+ from lim.bspline_chunk import DEGREE, FIT_TOLERANCE
65
+
66
+ if (anchor, gripper, padding, normalization_population, label_offset) != (
67
+ "chunk_start_tcp", "future", "terminal", "dense", 0
68
+ ):
69
+ raise ValueError("B-spline labels use the TCP anchor and default label fields")
70
+ return {
71
+ **RELATIVE_POSE_CONTRACT,
72
+ "version": f"chunk_start_pose6d_bspline_k{bspline_knots}_tol{FIT_TOLERANCE:g}_v1",
73
+ "pose_supervision": supervision,
74
+ "bspline_knots": bspline_knots,
75
+ "target_source": "each demonstration's dense targets and terminal TCP fitted once"
76
+ f" by a degree-{DEGREE} B-spline (FITPACK knot insertion, max abs sample error"
77
+ f" < {FIT_TOLERANCE:g} in xyz m / rotation-matrix entries / gripper); the"
78
+ " observation's segment starts at the knot interval containing it",
79
+ "layout": f"{bspline_knots + 2 * DEGREE} rows of [knot steps relative to the"
80
+ " observation, control point target10 in the observation's TCP frame]",
81
+ "gripper": "fitted with the pose in the same spline, not a relative offset",
82
+ "padding": "past the fitted end, knots and control points repeat the last",
83
+ "normalization_population": "every row of every observation's segment",
84
+ }
85
+ if supervision == "future_waypoint":
86
+ if (anchor, gripper, padding, normalization_population, label_offset) != (
87
+ "chunk_start_tcp", "future", "terminal", "dense", 0
88
+ ):
89
+ raise ValueError("Waypoint labels use the TCP anchor and default label fields")
90
+ return {
91
+ **RELATIVE_POSE_CONTRACT,
92
+ "version": f"chunk_start_pose6d_future_waypoint_eta{waypoint_threshold_m:g}_v1",
93
+ "pose_supervision": supervision,
94
+ "waypoint_threshold_m": waypoint_threshold_m,
95
+ "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",
96
+ "gripper": "original future dense gripper command at each slot, unchanged",
97
+ "normalization_population": "original dense valid anchor/future-target pairs, no terminal padding",
98
+ }
99
+ if supervision == "phase_segments":
100
+ if (anchor, gripper, padding, normalization_population, label_offset) != (
101
+ "chunk_start_tcp", "future", "terminal", "dense", 0
102
+ ):
103
+ raise ValueError("Phase segments use the TCP anchor and default label fields")
104
+ return {
105
+ **RELATIVE_POSE_CONTRACT,
106
+ "version": "chunk_start_pose6d_phase_segments_v1",
107
+ "pose_supervision": supervision,
108
+ "target_source": "slot0 current primitive endpoint, slot1 next primitive endpoint (last primitive repeats)",
109
+ "gripper": "each slot carries its own primitive gripper command",
110
+ "padding": "none; both slots always exist",
111
+ "switch": "remaining steps in the current primitive, min(steps,30)/30, from decoder query zero",
112
+ "normalization_population": "frozen statistics from a completed training; never refit",
113
+ }
114
+ if label_offset:
115
+ if label_offset < 0 or supervision != "future_endpoint" or anchor != "chunk_start_tcp":
116
+ raise ValueError("Lookahead offsets apply to TCP-anchored future endpoints")
117
+ original = pose_target_contract(
118
+ anchor, supervision, gripper, padding, normalization_population
119
+ )
120
+ return {
121
+ **original,
122
+ "version": original["version"] + f"_lookahead{label_offset}_v1",
123
+ "label_offset": label_offset,
124
+ "target_source": f"primitive endpoint and gripper at time t+{label_offset}+i",
125
+ "normalization_population": "frozen statistics from a completed training; never refit",
126
+ }
127
+ if normalization_population == "supervised":
128
+ if (
129
+ supervision != "current_endpoint"
130
+ or gripper != "current"
131
+ or padding != "current_target"
132
+ ):
133
+ raise ValueError(
134
+ "Supervised normalization requires repeated complete current-target endpoint labels"
135
+ )
136
+ original = pose_target_contract(anchor, supervision, gripper, padding)
137
+ return {
138
+ **original,
139
+ "version": original["version"] + "_supervised_population_v1",
140
+ "anchor": anchor,
141
+ "normalization_population": "query-zero complete current endpoint once per original observation; no future-pair or padding reweighting",
142
+ }
143
+ if normalization_population != "dense":
144
+ raise ValueError("Unknown chunk normalization population")
145
+ if padding == "current_target":
146
+ if supervision != "current_endpoint" or gripper != "current":
147
+ raise ValueError(
148
+ "Current-target padding requires current endpoint and gripper"
149
+ )
150
+ original = pose_target_contract(anchor, supervision, gripper)
151
+ return {
152
+ **original,
153
+ "version": original["version"] + "_current_padding_v1",
154
+ "padding": "repeat current observation complete endpoint target in all out-of-range slots",
155
+ "gripper": "current observation command repeated in every slot including padding",
156
+ }
157
+ if padding != "terminal":
158
+ raise ValueError("Unknown chunk padding")
159
+ if gripper == "current":
160
+ original = pose_target_contract(anchor, supervision)
161
+ return {
162
+ **original,
163
+ "version": original["version"] + "_current_gripper_v1",
164
+ "gripper": "current observation command repeated in valid slots; terminal padding unchanged",
165
+ "gripper_supervision": "current",
166
+ }
167
+ if gripper != "future":
168
+ raise ValueError("Unknown chunk gripper supervision")
169
+ base = (
170
+ RELATIVE_POSE_CONTRACT
171
+ if anchor == "chunk_start_tcp"
172
+ else ABSOLUTE_POSE_CONTRACT
173
+ )
174
+ if supervision == "dense":
175
+ return base
176
+ if supervision not in ("future_endpoint", "current_endpoint"):
177
+ raise ValueError("Unknown endpoint supervision")
178
+ return {
179
+ **base,
180
+ "version": (
181
+ f"chunk_start_pose6d_{supervision}_v1"
182
+ if anchor == "chunk_start_tcp"
183
+ else f"absolute_world_pose6d_{supervision}_v1"
184
+ ),
185
+ "pose_supervision": supervision,
186
+ "target_source": (
187
+ "primitive endpoint at each future action time"
188
+ if supervision == "future_endpoint"
189
+ else "current observation primitive endpoint repeated in valid future slots"
190
+ ),
191
+ "gripper": "original future dense gripper command at each slot, unchanged",
192
+ "normalization_population": "original dense valid anchor/future-target pairs, no terminal padding",
193
+ **(
194
+ {
195
+ "anchor": "identity",
196
+ "coordinate_frame": "stored TCP/keyframe frame, world in this audited StackCube dataset",
197
+ }
198
+ if anchor == "identity"
199
+ else {}
200
+ ),
201
+ }
202
+
203
+
204
+ def resolve_anchor(anchor, mode: ChunkAnchor):
205
+ """Pick the label origin; identity preserves the stored pose coordinate frame.
206
+
207
+ Only the label/restore frame changes. Converting an absolute goal into a physical
208
+ controller delta always uses the real measured TCP, so this stays a pure
209
+ representation switch rather than a change of what is commanded.
210
+ """
211
+ if mode == "chunk_start_tcp":
212
+ return anchor
213
+ if mode != "identity":
214
+ raise ValueError(f"Unknown chunk anchor mode: {mode}")
215
+ shape = (*anchor.shape[:-1], 7)
216
+ fixed = torch.zeros(shape, dtype=anchor.dtype, device=anchor.device)
217
+ fixed[..., 3] = 1.0 # identity quaternion, zero translation
218
+ return fixed
219
+
220
+
221
+ def controller_pose_targets(actions, tcp):
222
+ """Reconstruct actual CPU controller goals in audited world-aligned root axes."""
223
+ if actions.shape[-1] != 7 or tcp.shape[-1] != 7:
224
+ raise ValueError("Expected controller7 and world TCP7")
225
+ delta = controller_to_sixd(actions)
226
+ rotation = sixd_to_matrix(delta[..., 3:9]) @ quaternion_to_matrix(tcp[..., 3:])
227
+ return torch.cat(
228
+ [
229
+ tcp[..., :3] + actions[..., :3].clamp(-1, 1) * 0.1,
230
+ matrix_to_sixd(rotation),
231
+ actions[..., -1:],
232
+ ],
233
+ -1,
234
+ )
235
+
236
+
237
+ def world_to_chunk_relative(target, anchor):
238
+ """World target10 -> fixed-origin translation and root-aligned relative rotation."""
239
+ rotation = sixd_to_matrix(target[..., 3:9]) @ quaternion_to_matrix(
240
+ anchor[..., 3:]
241
+ ).transpose(-1, -2)
242
+ return torch.cat(
243
+ [
244
+ (target[..., :3] - anchor[..., :3]) / 0.1,
245
+ matrix_to_sixd(rotation),
246
+ target[..., -1:],
247
+ ],
248
+ -1,
249
+ )
250
+
251
+
252
+ def chunk_relative_to_world(target, anchor):
253
+ """Restore every goal using the SAME anchor; never integrate or clip offsets."""
254
+ rotation = sixd_to_matrix(target[..., 3:9]) @ quaternion_to_matrix(anchor[..., 3:])
255
+ return torch.cat(
256
+ [
257
+ anchor[..., :3] + target[..., :3] * 0.1,
258
+ matrix_to_sixd(rotation),
259
+ target[..., -1:],
260
+ ],
261
+ -1,
262
+ )
fair-comparison/extract-train-v1/code/lim/chunk_done.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-item end of the demonstration, predicted beside every chunk item.
2
+
3
+ Label of item i at observation t: t + i is past the demonstration's last
4
+ action, i.e. exactly the items that carry terminal padding. The action labels,
5
+ padding and normalization are unchanged. Every label row is 0...0 1...1 and
6
+ item 0 is never done, so the end is read from one prediction only: what the
7
+ policy does once a demonstration has ended was never observed.
8
+ """
9
+
10
+ import hashlib
11
+
12
+ import torch
13
+ from pydantic import BaseModel, ConfigDict
14
+ from torch import nn
15
+
16
+ DONE_LOGIT = 0.0
17
+ """An item counts as done at probability >= 0.5 (logit >= 0); fixed before any run."""
18
+
19
+
20
+ class ChunkDoneHeadConfig(BaseModel, frozen=True):
21
+ model_config = ConfigDict(
22
+ arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
23
+ )
24
+ action_head: nn.Module
25
+ """Existing action projection, optionally wrapped by the phase or switch head."""
26
+
27
+
28
+ def wrapped_linear(module):
29
+ """The native action projection inside any chain of `.action` wrappers."""
30
+ while not isinstance(module, nn.Linear):
31
+ if not hasattr(module, "action"):
32
+ raise ValueError("Done head wraps a linear action projection")
33
+ module = module.action
34
+ return module
35
+
36
+
37
+ class ChunkDoneHead(nn.Module):
38
+ def __init__(self, config: ChunkDoneHeadConfig):
39
+ super().__init__()
40
+ self.config = config
41
+ self.action = config.action_head
42
+ linear = wrapped_linear(self.action)
43
+ device = linear.weight.device
44
+ devices = [device.index] if device.type == "cuda" else []
45
+ # Preserve the original parameters' initialization, later EMA
46
+ # construction and every sampling/dropout RNG draw.
47
+ with torch.random.fork_rng(devices=devices):
48
+ self.done = nn.Linear(
49
+ linear.in_features, 1, device=device, dtype=linear.weight.dtype
50
+ )
51
+ self.done_logits = None
52
+
53
+ def forward(self, features):
54
+ if features.ndim != 3 or features.shape[1] < 1:
55
+ raise ValueError("Expected ACT decoder features batch x query x hidden")
56
+ actions = self.action(features)
57
+ self.done_logits = self.done(features).squeeze(-1)
58
+ return actions
59
+
60
+
61
+ def read_done_logits(model):
62
+ """Batch x query logits from the latest forward, without detaching or rerunning it."""
63
+ heads = [part for part in model.modules() if isinstance(part, ChunkDoneHead)]
64
+ if len(heads) != 1:
65
+ raise ValueError("Expected exactly one enabled chunk done head")
66
+ logits = heads[0].done_logits
67
+ if logits is None:
68
+ raise RuntimeError("Done logits require a completed policy forward")
69
+ return logits
70
+
71
+
72
+ def labels_from_valid(valid):
73
+ """Float labels from the dataset's in-range mask: 1 exactly on padded items."""
74
+ return (~valid).float()
75
+
76
+
77
+ def batch_done_items(logits):
78
+ """Items before the end under the suffix rule, for every row of batch x items:
79
+ the end is the first item from which every later item is also done. All
80
+ items if the last one is not done; 0 if every item is done."""
81
+ pending = logits < DONE_LOGIT
82
+ index = torch.arange(1, logits.shape[-1] + 1, device=logits.device)
83
+ return (pending * index).amax(-1)
84
+
85
+
86
+ def done_items(logits):
87
+ """batch_done_items for one prediction's logits."""
88
+ if logits.ndim != 1 or not torch.isfinite(logits).all():
89
+ raise ValueError("Expected one finite logit per chunk item")
90
+ return int(batch_done_items(logits[None])[0])
91
+
92
+
93
+ def first_done_item(logits):
94
+ """Diagnostic only: index of the first done item, all items if none is."""
95
+ if logits.ndim != 1 or not torch.isfinite(logits).all():
96
+ raise ValueError("Expected one finite logit per chunk item")
97
+ done = torch.nonzero(logits >= DONE_LOGIT).flatten()
98
+ return int(done[0]) if len(done) else len(logits)
99
+
100
+
101
+ def original_state_sha256(model):
102
+ """Hash parameters/buffers as they would be named without the done head.
103
+
104
+ With the same seed this equals the full initial-state hash of the matching
105
+ recipe trained without the head, because the head draws no RNG.
106
+ """
107
+ digest = hashlib.sha256()
108
+ for name, tensor in model.state_dict().items():
109
+ if ".action_head.done." in name:
110
+ continue
111
+ name = name.replace(".action_head.action.", ".action_head.", 1)
112
+ digest.update(name.encode())
113
+ digest.update(tensor.detach().cpu().contiguous().numpy().tobytes())
114
+ return digest.hexdigest()
fair-comparison/extract-train-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/extract-train-v1/code/lim/chunk_ensemble.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Several separately trained models predicting one observation, and how their chunks combine.
2
+
3
+ Phase information comes from a boundary probe fitted on a frozen model's
4
+ decoder features (experiments/fair-comparison/fit_phase_probe.py), so the
5
+ members' actions are exactly their checkpoints'. Boundary k (1-6) of an item
6
+ means its time is at or past the start of StackCube primitive k, where 6 is
7
+ the done class (past the demonstration's end); being past k + 1 implies being
8
+ past k. Each boundary's transition is read by lim.chunk_done's suffix rule and
9
+ transitions are then made non-decreasing (a later boundary cannot be crossed
10
+ before an earlier one), so every member's phase sequence is monotone.
11
+
12
+ Rules combine the members' executed items (the first ``span``), K x n x 10
13
+ world targets:
14
+
15
+ - mean: equal-weight average (6D re-orthonormalized, gripper averaged).
16
+ - medoid: the member closest to the others (lim.chunk_samples distance), as is.
17
+ - mode: members linked when their executed positions are on average closer
18
+ than MODE_RADIUS_M and every executed gripper sign agrees; the largest
19
+ single-linkage group is averaged (ties: the group nearer the others).
20
+ - phase: consensus transitions are the lower median of the members' (still
21
+ monotone); each executed item takes the consensus phase and averages, over
22
+ the members that have that phase among their executed items, each member's
23
+ own items of that phase; with none, the item falls back to the plain mean.
24
+ - split: exactly two members; the first member's poses with the second
25
+ member's gripper values (pose and gripper from separately trained models).
26
+ """
27
+
28
+ from contextlib import contextmanager
29
+ from typing import Literal
30
+
31
+ import torch
32
+ from torch import nn
33
+
34
+ from lim.chunk_done import done_items
35
+ from lim.chunk_samples import combine, decide, mean_targets
36
+
37
+ EnsembleRule = Literal["mean", "medoid", "mode", "phase", "split"]
38
+ BOUNDARIES = 6
39
+ MODE_RADIUS_M = 0.010
40
+ """Fixed before any ensemble run: 10 mm, about the seeds' median spread before success."""
41
+
42
+
43
+ class BoundaryProbe(nn.Module):
44
+ """One hidden layer: a linear probe of the frozen features underfits (held-out
45
+ phase accuracy 91.8% at 10 epochs, 95.0% at 60 (95.2% at lr 3e-3); this probe 96.0%, seed 100)."""
46
+
47
+ def __init__(self, features=256, hidden=256):
48
+ super().__init__()
49
+ self.net = nn.Sequential(nn.Linear(features, hidden), nn.GELU(), nn.Linear(hidden, BOUNDARIES))
50
+
51
+ def forward(self, features):
52
+ return self.net(features)
53
+
54
+
55
+ def decoder_head(agent):
56
+ """The outermost module the native decoder calls as its action head."""
57
+ heads = [(name, m) for name, m in agent.named_modules() if name.endswith("action_head")]
58
+ if not heads:
59
+ raise ValueError("No ACT action head found")
60
+ return min(heads, key=lambda pair: len(pair[0]))[1]
61
+
62
+
63
+ @contextmanager
64
+ def decoder_features(agent):
65
+ """Yield a list that receives the decoder features (batch x Q x hidden) of each forward."""
66
+ captured = []
67
+ handle = decoder_head(agent).register_forward_pre_hook(
68
+ lambda module, args: captured.append(args[0].detach())
69
+ )
70
+ try:
71
+ yield captured
72
+ finally:
73
+ handle.remove()
74
+
75
+
76
+ def boundary_labels(phases):
77
+ """Integer phases 0-6 (... x Q) -> float labels (... x Q x 6), 1 where past boundary k."""
78
+ return (phases[..., None] >= torch.arange(1, BOUNDARIES + 1, device=phases.device)).float()
79
+
80
+
81
+ def transitions(logits):
82
+ """Q x 6 boundary logits -> 6 non-decreasing item indices where each boundary is crossed
83
+ (Q if not within the chunk)."""
84
+ if logits.ndim != 2 or logits.shape[1] != BOUNDARIES:
85
+ raise ValueError("Expected items x six boundary logits")
86
+ raw = torch.tensor([done_items(logits[:, k]) for k in range(BOUNDARIES)])
87
+ # A later boundary crossed at item t means every earlier one is crossed by t.
88
+ return raw.flip(0).cummin(0).values.flip(0)
89
+
90
+
91
+ def phases_from(transitions, items):
92
+ """Phase (0-6) of items 0..items-1 from monotone transitions."""
93
+ index = torch.arange(items)
94
+ return (transitions[None, :] <= index[:, None]).sum(-1)
95
+
96
+
97
+ def consensus(member_transitions):
98
+ """Lower median over members of each boundary's transition; monotone when theirs are."""
99
+ ordered = member_transitions.sort(0).values
100
+ return ordered[(len(ordered) - 1) // 2]
101
+
102
+
103
+ def mode_weights(items):
104
+ """Largest single-linkage group of members (MODE_RADIUS_M, equal gripper signs)."""
105
+ count = len(items)
106
+ distance = (items[:, None, :, :3] - items[None, :, :, :3]).norm(dim=-1).mean(-1)
107
+ close = items[..., 9] < 0
108
+ same = (close[:, None] == close[None]).all(-1)
109
+ linked = (distance < MODE_RADIUS_M) & same
110
+ parent = list(range(count))
111
+
112
+ def find(i):
113
+ while parent[i] != i:
114
+ parent[i] = parent[parent[i]]
115
+ i = parent[i]
116
+ return i
117
+
118
+ for a in range(count):
119
+ for b in range(a + 1, count):
120
+ if linked[a, b]:
121
+ parent[find(a)] = find(b)
122
+ roots = torch.tensor([find(i) for i in range(count)])
123
+ groups = [roots == r for r in roots.unique()]
124
+ size = max(int(g.sum()) for g in groups)
125
+ largest = [g for g in groups if int(g.sum()) == size]
126
+ nearness = distance.sum(-1)
127
+ group = min(largest, key=lambda g: float(nearness[g].mean()))
128
+ return group.float()
129
+
130
+
131
+ def phase_combine(items, member_transitions):
132
+ """The phase rule; returns the combined items, consensus transitions and fallback count."""
133
+ count, n = items.shape[:2]
134
+ agreed = consensus(member_transitions)
135
+ target = phases_from(agreed, n)
136
+ own = torch.stack([phases_from(t, n) for t in member_transitions])
137
+ out, fallback, used = [], 0, []
138
+ for i in range(n):
139
+ estimates = []
140
+ for m in range(count):
141
+ mine = own[m] == target[i]
142
+ if mine.any():
143
+ estimates.append(mean_targets(items[m, mine], torch.ones(int(mine.sum()))))
144
+ used.append(len(estimates))
145
+ if estimates:
146
+ out.append(mean_targets(torch.stack(estimates), torch.ones(len(estimates))))
147
+ else:
148
+ fallback += 1
149
+ out.append(mean_targets(items[:, i], torch.ones(count)))
150
+ return torch.stack(out), agreed, fallback, used
151
+
152
+
153
+ def combine_members(rule: EnsembleRule, items, member_transitions=None):
154
+ """The executed items (n x 10) the rule forms, and what it decided."""
155
+ if items.ndim != 3 or items.shape[-1] != 10:
156
+ raise ValueError("Expected members x items x 10 world targets")
157
+ if rule == "phase":
158
+ if member_transitions is None:
159
+ raise ValueError("The phase rule needs every member's boundary transitions")
160
+ combined, agreed, fallback, used = phase_combine(items, member_transitions)
161
+ return combined, {"consensus": agreed.tolist(), "fallback_items": fallback, "members_per_item": used}
162
+ if rule == "split":
163
+ if len(items) != 2:
164
+ raise ValueError("The split rule takes poses from one member and the gripper from another")
165
+ return torch.cat([items[0, :, :-1], items[1, :, -1:]], dim=-1), {"pose_member": 0, "gripper_member": 1}
166
+ if rule == "mean":
167
+ weights = torch.ones(len(items))
168
+ elif rule == "medoid":
169
+ weights = decide("medoid", items)
170
+ elif rule == "mode":
171
+ weights = mode_weights(items)
172
+ else:
173
+ raise ValueError(f"Unknown ensemble rule {rule}")
174
+ return combine("medoid" if rule == "medoid" else "mean", items, weights), {"weights": weights.tolist()}
fair-comparison/extract-train-v1/code/lim/chunk_flow.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Flow-matching action head on the native ACT observation encoder (PLAN.md).
2
+
3
+ The observation is encoded exactly as the native DETRVAE encodes it at
4
+ inference: both cameras' backbone features, the proprioceptive token and the
5
+ z = 0 latent token through the same transformer encoder. The CVAE posterior is
6
+ not used. The decoder's input, zeros in the native model, becomes the embedded
7
+ noisy action and flow time of every item; the query embeddings, the decoder
8
+ output taken (stack entry 0) and the action head are the native ones, so with
9
+ a zero decoder input the model reproduces native zero-latent inference.
10
+
11
+ Path, time sampling and embedding follow openpi's pi0
12
+ (src/openpi/models/pi0.py): x_t = t * noise + (1 - t) * actions, t = 1 is
13
+ noise, the target is noise - actions, t = 0.001 + 0.999 * Beta(1.5, 1), and the
14
+ item embedding is out(swish(in(concat(W a, posemb(t))))). Inference integrates
15
+ from t = 1 to 0 with Euler steps. Everything is in the normalized action space.
16
+
17
+ The "modulated" decoder (PLAN.md, flow-mod-v1) differs in two places only. The
18
+ output is the last decoder layer's (all layers act), and time enters only
19
+ through per-layer modulation, as pi0.5's adaRMSNorm conditioning: the noisy
20
+ action is projected linearly, posemb(t) goes through a two-layer swish MLP, and
21
+ a zero-initialized linear map of it gives each self-attention, cross-attention
22
+ and FFN sublayer a scale, shift and gate, LN(x + (1 + gate) f(x)) (1 + scale) +
23
+ shift on ACT's own post-norm LayerNorms; the final LayerNorm gets a scale and
24
+ shift. At initialization every layer equals the native one.
25
+ """
26
+
27
+ import math
28
+ from typing import Any, Literal
29
+
30
+ import torch
31
+ import torch.nn.functional as F
32
+ from pydantic import BaseModel, ConfigDict, PositiveInt
33
+ from torch import nn
34
+
35
+ TIME_MIN, TIME_SCALE = 0.001, 0.999
36
+ """Training flow time t = 0.001 + 0.999 * Beta(1.5, 1) (openpi compute_loss)."""
37
+ BETA_ALPHA = 1.5
38
+ PERIOD_MIN, PERIOD_MAX = 4e-3, 4.0
39
+ """Sine-cosine periods of the flow-time embedding (openpi embed_suffix)."""
40
+ GROUPS = {"position": slice(0, 3), "rotation": slice(3, 9), "gripper": slice(9, 10)}
41
+ """The group_balanced groups of a pose6D item."""
42
+
43
+
44
+ def sample_time(batch, device):
45
+ """Beta(1.5, 1) has CDF x**1.5, so r**(2/3) with r ~ U(0, 1) samples it exactly."""
46
+ return TIME_MIN + TIME_SCALE * torch.rand(batch, device=device) ** (1 / BETA_ALPHA)
47
+
48
+
49
+ def time_embedding(time, width):
50
+ """openpi posemb_sincos: batch -> batch x width."""
51
+ fraction = torch.linspace(0, 1, width // 2, device=time.device, dtype=time.dtype)
52
+ period = PERIOD_MIN * (PERIOD_MAX / PERIOD_MIN) ** fraction
53
+ angles = time[:, None] * (1.0 / period * 2 * math.pi)[None]
54
+ return torch.cat([angles.sin(), angles.cos()], dim=-1)
55
+
56
+
57
+ def flow_reconstruction(velocity, target):
58
+ """Mean squared velocity error per group, averaged over the three groups."""
59
+ if velocity.shape != target.shape or target.shape[-1] != 10:
60
+ raise ValueError("Flow objectives require matching ten-dimensional pose chunks")
61
+ groups = {f"{name}_mse": F.mse_loss(velocity[..., part], target[..., part])
62
+ for name, part in GROUPS.items()}
63
+ return {"reconstruction": sum(groups.values()) / len(groups), **groups}
64
+
65
+
66
+ class ChunkFlowConfig(BaseModel, frozen=True):
67
+ model_config = ConfigDict(
68
+ arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
69
+ )
70
+ native_model: Any
71
+ """Newly initialized pinned DETRVAE; its encoder-side modules are reused."""
72
+ steps: PositiveInt
73
+ """Euler steps from t = 1 to t = 0 per fresh observation."""
74
+ decoder: Literal["native", "modulated"] = "native"
75
+ """native: decoder stack entry 0 with time in the input (pi0); modulated: the
76
+ last layer, time through per-layer modulation (pi0.5-style)."""
77
+
78
+
79
+ SUBLAYERS = 3
80
+ """Self-attention, cross-attention and FFN of a DETR decoder layer."""
81
+
82
+
83
+ def modulated_layer(layer, tgt, memory, pos, query_pos, modulation):
84
+ """One post-norm DETR decoder layer (forward_post) with every sublayer's
85
+ norm(x + (1 + gate) f(x)) * (1 + scale) + shift; zero modulation is the layer.
86
+ tgt: query x batch x width, modulation: batch x (3 * 3 * width)."""
87
+ parts = modulation.unsqueeze(0).chunk(3 * SUBLAYERS, dim=-1)
88
+
89
+ def residual(x, y, index, norm):
90
+ scale, shift, gate = parts[3 * index : 3 * index + 3]
91
+ return norm(x + (1 + gate) * y) * (1 + scale) + shift
92
+
93
+ q = k = layer.with_pos_embed(tgt, query_pos)
94
+ tgt = residual(tgt, layer.dropout1(layer.self_attn(q, k, value=tgt)[0]), 0, layer.norm1)
95
+ attended = layer.multihead_attn(
96
+ query=layer.with_pos_embed(tgt, query_pos), key=layer.with_pos_embed(memory, pos), value=memory
97
+ )[0]
98
+ tgt = residual(tgt, layer.dropout2(attended), 1, layer.norm2)
99
+ hidden = layer.linear2(layer.dropout(layer.activation(layer.linear1(tgt))))
100
+ return residual(tgt, layer.dropout3(hidden), 2, layer.norm3)
101
+
102
+
103
+ class ChunkFlowModel(nn.Module):
104
+ def __init__(self, config: ChunkFlowConfig):
105
+ super().__init__()
106
+ native = config.native_model
107
+ self.steps = config.steps
108
+ # Only these native modules are registered: the CVAE posterior (encoder,
109
+ # cls/state/action projections, latent_proj, pos_table) is dropped.
110
+ self.backbones = native.backbones
111
+ self.input_proj = native.input_proj
112
+ self.input_proj_robot_state = native.input_proj_robot_state
113
+ self.transformer = native.transformer
114
+ self.query_embed = native.query_embed
115
+ self.action_head = native.action_head
116
+ self.additional_pos_embed = native.additional_pos_embed
117
+ self.latent_out_proj = native.latent_out_proj
118
+ self.latent_dim = native.latent_dim
119
+ self.num_queries = native.num_queries
120
+ self.decoder = config.decoder
121
+ width, dimension = self.transformer.d_model, self.action_head.out_features
122
+ device = self.action_head.weight.device
123
+ devices = [device.index] if device.type == "cuda" else []
124
+ layers = self.transformer.decoder.layers
125
+ # Preserve the native parameters' initialization, later EMA
126
+ # construction and every sampling/dropout RNG draw.
127
+ with torch.random.fork_rng(devices=devices):
128
+ self.action_in = nn.Linear(dimension, width, device=device)
129
+ if self.decoder == "native":
130
+ self.time_in = nn.Linear(2 * width, width, device=device)
131
+ self.time_out = nn.Linear(width, width, device=device)
132
+ else:
133
+ if any(layer.normalize_before for layer in layers):
134
+ raise ValueError("Modulation is written for ACT's post-norm decoder layers")
135
+ self.time_mlp_in = nn.Linear(width, width, device=device)
136
+ self.time_mlp_out = nn.Linear(width, width, device=device)
137
+ self.modulation = nn.ModuleList(
138
+ nn.Linear(width, 3 * SUBLAYERS * width, device=device) for _ in layers
139
+ )
140
+ self.final_modulation = nn.Linear(width, 2 * width, device=device)
141
+ for linear in [*self.modulation, self.final_modulation]:
142
+ nn.init.zeros_(linear.weight)
143
+ nn.init.zeros_(linear.bias)
144
+ self.generator = None
145
+
146
+ def encode(self, obs):
147
+ """Encoder memory and positions, as DETRVAE builds them with z = 0."""
148
+ state = obs["state"]
149
+ batch = state.shape[0]
150
+ features, positions = [], []
151
+ for camera in range(obs["rgb"].shape[1]):
152
+ feature, position = self.backbones[0](obs["rgb"][:, camera])
153
+ features.append(self.input_proj(feature[0]))
154
+ positions.append(position[0])
155
+ src = torch.cat(features, dim=3).flatten(2).permute(2, 0, 1)
156
+ pos = torch.cat(positions, dim=3).flatten(2).permute(2, 0, 1).repeat(1, batch, 1)
157
+ extra = self.additional_pos_embed.weight.unsqueeze(1).repeat(1, batch, 1)
158
+ latent = self.latent_out_proj(
159
+ torch.zeros(batch, self.latent_dim, dtype=torch.float32, device=state.device)
160
+ )
161
+ src = torch.cat([torch.stack([latent, self.input_proj_robot_state(state)]), src])
162
+ pos = torch.cat([extra, pos])
163
+ return self.transformer.encoder(src, src_key_padding_mask=None, pos=pos), pos
164
+
165
+ def decode(self, target, memory, pos):
166
+ """batch x query x width decoder input -> batch x query x action."""
167
+ queries = self.query_embed.weight.unsqueeze(1).repeat(1, target.shape[0], 1)
168
+ hidden = self.transformer.decoder(
169
+ target.transpose(0, 1), memory, memory_key_padding_mask=None, pos=pos,
170
+ query_pos=queries,
171
+ ).transpose(1, 2)[0]
172
+ return self.action_head(hidden)
173
+
174
+ def modulated_decode(self, target, condition, memory, pos):
175
+ """All decoder layers, modulated by the time condition; the last layer's output."""
176
+ queries = self.query_embed.weight.unsqueeze(1).repeat(1, target.shape[0], 1)
177
+ tgt = target.transpose(0, 1)
178
+ for layer, modulation in zip(self.transformer.decoder.layers, self.modulation, strict=True):
179
+ tgt = modulated_layer(layer, tgt, memory, pos, queries, modulation(condition))
180
+ scale, shift = self.final_modulation(condition).unsqueeze(0).chunk(2, dim=-1)
181
+ hidden = self.transformer.decoder.norm(tgt) * (1 + scale) + shift
182
+ return self.action_head(hidden.transpose(0, 1))
183
+
184
+ def velocity(self, noisy, time, memory, pos):
185
+ if self.decoder == "modulated":
186
+ embedded = time_embedding(time, self.time_mlp_in.in_features)
187
+ condition = F.silu(self.time_mlp_out(F.silu(self.time_mlp_in(embedded))))
188
+ return self.modulated_decode(self.action_in(noisy), condition, memory, pos)
189
+ embedded = time_embedding(time, self.time_in.out_features)
190
+ embedded = embedded[:, None].expand(-1, noisy.shape[1], -1)
191
+ target = self.time_out(F.silu(self.time_in(torch.cat([self.action_in(noisy), embedded], -1))))
192
+ return self.decode(target, memory, pos)
193
+
194
+ def forward(self, obs, actions=None):
195
+ """Training (normalized labels given): (predicted velocity, velocity target)
196
+ in place of (prediction, latent). Inference: (actions, (None, None))."""
197
+ memory, pos = self.encode(obs)
198
+ if actions is not None:
199
+ noise = torch.randn_like(actions)
200
+ time = sample_time(actions.shape[0], actions.device)
201
+ noisy = time[:, None, None] * noise + (1 - time[:, None, None]) * actions
202
+ return self.velocity(noisy, time, memory, pos), noise - actions
203
+ if self.generator is None:
204
+ raise RuntimeError("Flow inference noise must be seeded (seed_flow_noise)")
205
+ batch = obs["state"].shape[0]
206
+ sample = torch.randn(
207
+ batch, self.num_queries, self.action_head.out_features,
208
+ device=memory.device, generator=self.generator,
209
+ )
210
+ step = 1 / self.steps
211
+ for index in range(self.steps):
212
+ time = sample.new_full((batch,), 1 - index * step)
213
+ sample = sample - step * self.velocity(sample, time, memory, pos)
214
+ return sample, (None, None)
215
+
216
+
217
+ def flow_model(model):
218
+ """The one flow head inside a policy's wrappers."""
219
+ heads = [part for part in model.modules() if isinstance(part, ChunkFlowModel)]
220
+ if len(heads) != 1:
221
+ raise ValueError("Expected exactly one flow-matching head")
222
+ return heads[0]
223
+
224
+
225
+ def seed_flow_noise(model, seed):
226
+ """Restart the inference noise stream (the evaluator does this per episode)."""
227
+ head = flow_model(model)
228
+ device = head.action_head.weight.device
229
+ head.generator = torch.Generator(device=device)
230
+ head.generator.manual_seed(seed)
fair-comparison/extract-train-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/extract-train-v1/code/lim/chunk_samples.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Several predictions of one observation from CVAE prior latents, and how they are combined.
2
+
3
+ Deployment normally decodes the prior mean (z = 0). Here each of K predictions
4
+ decodes its own z ~ N(0, I), batched as K copies of the observation. The rules
5
+ choose from or average the K chunks; their decisions use only the items that
6
+ will be executed (the first ``span``), then apply to the whole chunk.
7
+
8
+ - mean: every sample, equal weights.
9
+ - vote: per executed item the majority phase over samples (ties: lower class);
10
+ samples agreeing with it on the most items are averaged.
11
+ - conf: weights proportional to each sample's mean maximum phase probability
12
+ over the executed items.
13
+ - medoid: the sample with the smallest summed distance to the others over the
14
+ executed items (positions in 0.1 m controller units, 6D and gripper as they
15
+ are); executed as predicted, nothing averaged.
16
+ """
17
+
18
+ from typing import Literal
19
+
20
+ import numpy as np
21
+ import torch
22
+
23
+ from lim.action_encoding import matrix_to_sixd, sixd_to_matrix
24
+
25
+ Aggregate = Literal["mean", "vote", "conf", "medoid"]
26
+ PHASE_RULES = ("vote", "conf")
27
+ """Rules that read a trained phase head."""
28
+ POSITION_UNIT_M = 0.1
29
+
30
+
31
+ def predict_with_latents(agent, inputs, latents):
32
+ """Policy outputs (N x Q x D, after denormalization) for a batch of N
33
+ observations, row n decoding latents[n] instead of the prior mean."""
34
+ modules = [m for name, m in agent.named_modules() if name.endswith("latent_out_proj")]
35
+ if len(modules) != 1:
36
+ raise ValueError("Expected the native CVAE latent projection exactly once")
37
+ if latents.ndim != 2 or latents.shape[1] != modules[0].in_features:
38
+ raise ValueError("Expected N x latent_dim prior samples")
39
+ handle = modules[0].register_forward_pre_hook(lambda module, args: (latents,))
40
+ try:
41
+ with torch.inference_mode():
42
+ return agent.get_action(dict(inputs)).cpu()
43
+ finally:
44
+ handle.remove()
45
+
46
+
47
+ def predict_samples(agent, observation, latents):
48
+ """K predictions of one observation, row k decoding latents[k]; same path as
49
+ batch-one inference otherwise."""
50
+ inputs = {
51
+ k: torch.as_tensor(v, device=latents.device)[None].repeat(len(latents), *[1] * np.ndim(v))
52
+ for k, v in observation.items()
53
+ }
54
+ return predict_with_latents(agent, inputs, latents)
55
+
56
+
57
+ def mean_targets(chunks, weights):
58
+ """Weighted mean of world targets (K x ... x 10); the 6D mean is re-orthonormalized."""
59
+ w = weights.to(chunks.dtype).reshape(-1, *[1] * (chunks.ndim - 1))
60
+ mean = (chunks * w).sum(0) / w.sum()
61
+ rotation = matrix_to_sixd(sixd_to_matrix(mean[..., 3:9]))
62
+ return torch.cat([mean[..., :3], rotation, mean[..., 9:]], -1)
63
+
64
+
65
+ def majority(phases):
66
+ """Per-item majority class of K x n integer phases; ties go to the lower class."""
67
+ classes = int(phases.max()) + 1
68
+ counts = torch.nn.functional.one_hot(phases, classes).sum(0)
69
+ return counts.argmax(-1)
70
+
71
+
72
+ def distances(items):
73
+ """K x K summed L1 distance between samples' executed items (K x n x 10)."""
74
+ scaled = torch.cat([items[..., :3] / POSITION_UNIT_M, items[..., 3:]], -1)
75
+ return (scaled[:, None] - scaled[None]).abs().sum((-1, -2))
76
+
77
+
78
+ def decide(rule: Aggregate, items, phases=None, max_prob=None):
79
+ """Sample weights (K) from the executed items alone; zero weight drops a sample.
80
+
81
+ items: K x n x 10 world targets; phases: K x n argmax classes; max_prob:
82
+ K x n maximum softmax phase probabilities.
83
+ """
84
+ count = len(items)
85
+ if rule == "mean":
86
+ return torch.ones(count)
87
+ if rule == "vote":
88
+ agree = (phases == majority(phases)[None]).sum(-1)
89
+ return (agree == agree.max()).float()
90
+ if rule == "conf":
91
+ return max_prob.mean(-1)
92
+ if rule == "medoid":
93
+ weights = torch.zeros(count)
94
+ weights[int(distances(items).sum(-1).argmin())] = 1.0
95
+ return weights
96
+ raise ValueError(f"Unknown aggregate rule {rule}")
97
+
98
+
99
+ def combine(rule: Aggregate, chunks, weights):
100
+ """The chunk to execute: the medoid itself, or the weighted mean of the samples."""
101
+ if rule == "medoid":
102
+ return chunks[int(weights.argmax())].clone()
103
+ return mean_targets(chunks, weights)
fair-comparison/extract-train-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/extract-train-v1/code/lim/collect_keyposes.py ADDED
@@ -0,0 +1,592 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Collect annotated native StackCube experts 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/extract-train-v1/code/lim/evaluate_phase_chunk.py ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ run(CliApp.run(PhaseChunkEvaluationConfig))
fair-comparison/extract-train-v1/code/lim/evaluate_planned_keypose.py ADDED
@@ -0,0 +1,1210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/extract-train-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/extract-train-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/extract-train-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/extract-train-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/extract-train-v1/code/lim/job.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ extra_gpus: tuple[NonNegativeInt, ...] = ()
25
+ """Further devices of a data-parallel training, visible after `gpu`."""
26
+ timeout_s: PositiveInt = 7200
27
+ """Maximum allocated job duration, including startup, loading and evaluation."""
28
+
29
+
30
+ class JobCLIConfig(BaseModel, frozen=True):
31
+ model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
32
+ spec: Path
33
+ """JSON file containing the single validated JobConfig."""
34
+
35
+
36
+ def run_job(config: JobConfig):
37
+ config.output_dir.mkdir(parents=True, exist_ok=True)
38
+ if (config.output_dir / "launch.json").exists():
39
+ raise ValueError("Job was already launched; use a new declared run directory")
40
+ env = os.environ.copy()
41
+ env.update(
42
+ CUDA_VISIBLE_DEVICES=",".join(map(str, (config.gpu, *config.extra_gpus))),
43
+ PYTHONUNBUFFERED="1",
44
+ )
45
+ started = time.monotonic()
46
+ epoch = time.time()
47
+ result = {"config": config.model_dump(mode="json"), "started_epoch": epoch}
48
+ (config.output_dir / "launch.json").write_text(json.dumps(result, indent=2))
49
+ process = None
50
+
51
+ def interrupt(signum, frame):
52
+ raise KeyboardInterrupt(f"Job runner received signal {signum}")
53
+
54
+ late = []
55
+ previous = signal.signal(signal.SIGTERM, interrupt)
56
+ try:
57
+ with (config.output_dir / "process.log").open("w") as log:
58
+ process = subprocess.Popen(
59
+ config.command,
60
+ cwd=config.cwd,
61
+ env=env,
62
+ stdin=subprocess.DEVNULL,
63
+ stdout=log,
64
+ stderr=subprocess.STDOUT,
65
+ start_new_session=True,
66
+ )
67
+ result["pid"] = process.pid
68
+ result["exit_code"] = process.wait(timeout=config.timeout_s)
69
+ result["status"] = "complete" if result["exit_code"] == 0 else "failed"
70
+ except subprocess.TimeoutExpired:
71
+ result.update(status="timeout", exit_code=None)
72
+ except KeyboardInterrupt:
73
+ result.update(status="interrupted", exit_code=None)
74
+ except (OSError, ValueError) as error:
75
+ result.update(
76
+ status="failed", exit_code=None, error=f"{type(error).__name__}: {error}"
77
+ )
78
+ finally:
79
+ # A repeated or late SIGTERM must not abort cleanup (child kill and
80
+ # result.json); it is recorded here and honoured once the ledger exists.
81
+ signal.signal(signal.SIGTERM, lambda signum, frame: late.append(signum))
82
+ if process is not None and process.poll() is None:
83
+ os.killpg(process.pid, signal.SIGTERM)
84
+ try:
85
+ process.wait(timeout=20)
86
+ except subprocess.TimeoutExpired:
87
+ os.killpg(process.pid, signal.SIGKILL)
88
+ process.wait()
89
+ result.update(
90
+ ended_epoch=time.time(), allocated_device_wall_s=time.monotonic() - started
91
+ )
92
+ result["timing_scope"] = (
93
+ "one assigned GPU job process lifetime, including CPU startup/data/evaluation; not GPU utilization integration"
94
+ )
95
+ (config.output_dir / "result.json").write_text(json.dumps(result, indent=2))
96
+ signal.signal(signal.SIGTERM, signal.SIG_DFL if previous is None else previous)
97
+ print("JOB_COMPLETE", json.dumps(result), flush=True)
98
+ if result["status"] != "complete":
99
+ raise SystemExit(1)
100
+ if late:
101
+ # The job itself finished; the stop request still ends the caller's queue.
102
+ raise KeyboardInterrupt(f"Job runner received signal {late[0]} during cleanup")
103
+
104
+
105
+ if __name__ == "__main__":
106
+ args = CliApp.run(JobCLIConfig)
107
+ run_job(JobConfig.model_validate_json(args.spec.read_text()))
fair-comparison/extract-train-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/extract-train-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/extract-train-v1/code/lim/keypose_data.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/extract-train-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/extract-train-v1/code/lim/keypose_diagnostics.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Explicit, logged interventions for frozen keypose 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 obs, info
fair-comparison/extract-train-v1/code/lim/keypose_extract.py ADDED
@@ -0,0 +1,580 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extract keypose segments from recorded demonstrations, with stages set per task.
2
+
3
+ Without a planner there are no commanded phase targets. A task names its stages in
4
+ order (STAGES): moves, gripper closings and gripper openings. Every kept
5
+ demonstration gets exactly that many segments, however it was executed; one whose
6
+ gripper events do not match the task's (count or order) is excluded and listed.
7
+
8
+ Gripper events come from what the recording holds:
9
+
10
+ - ``width`` (recorded hands, lim.umi_data): the gripper opening alone, for a task
11
+ with a single grasp. ``close_gripper`` runs from the last fully-open frame to the
12
+ first closed frame, ``open_gripper`` from the last closed frame to the first
13
+ fully-open frame, and the demonstration is cropped there: the retreat after the
14
+ release carries little of the task. A recording that stops before the gripper is
15
+ back at the open stop ends its ``open_gripper`` at its last frame. A
16
+ demonstration that leaves the open stop more than once is excluded.
17
+ - ``command`` (simulated demonstrations, lim.collect_keyposes): the recorded
18
+ actions. A closing or opening starts at the action whose gripper command changes
19
+ sign and lasts until the first later action whose commanded arm pose differs
20
+ from the previous one (or the demonstration's end).
21
+
22
+ Consecutive moves between two gripper events are split by the task's stage
23
+ configuration: a move marked ``adjacent="next"`` is the straight motion just
24
+ before the next event (a final approach), one marked ``"previous"`` the straight
25
+ motion just after the previous event (a lift); the one unmarked move of the run
26
+ takes the rest. A straight motion is the longest stretch of the reached path,
27
+ pauses removed, that stays within a distance of its chord and an angle of the
28
+ orientation interpolated along it; its boundary is the first frame at which the
29
+ path arrives at its far end. A task may set such a move's least rise above its
30
+ gripper event, so that a pause next to the gripper is not taken for that arrival.
31
+
32
+ Paths and endpoints use the poses the recording commands when it holds commands
33
+ (simulated: the pd_ee_delta_pose goal of every action, the same targets the dense
34
+ labels use), and the poses reached otherwise (recorded hands). The reached path
35
+ lags the commanded one by several millimetres and rounds its corners. Frames index observations; ``action`` t is the move from frame t to
36
+ t + 1, so the labels keep lim.keypose_data's convention: segment k covers actions
37
+ ``[start, end)`` and frame ``end`` is its endpoint. The output repeats the
38
+ dataset's traj group names, holding a ``keyframes`` group in the simulated
39
+ datasets' schema and the number of frames kept; dropped demonstrations have no
40
+ group, so the keyframes file also fixes which demonstrations, and which of their
41
+ frames, both representations train on.
42
+ """
43
+
44
+ import json
45
+ from pathlib import Path
46
+ from typing import Literal
47
+
48
+ import h5py
49
+ import numpy as np
50
+ from pydantic import BaseModel, ConfigDict, NonNegativeInt, PositiveFloat, model_validator
51
+ from pydantic_settings import CliApp
52
+
53
+ from lim import keypose_data
54
+ from lim.keypose_data import AnnotationConfig, KeyposeSegment, annotation_arrays
55
+ from lim.umi_data import FORMAT, file_digest
56
+
57
+
58
+ class Stage(BaseModel, frozen=True):
59
+ model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
60
+ name: str
61
+ kind: Literal["move", "close", "open"]
62
+ adjacent: Literal["next", "previous"] | None = None
63
+ """Moves only: the straight motion right before the next gripper event, or
64
+ right after the previous one; unmarked, the move takes what is left."""
65
+ min_rise_m: PositiveFloat | None = None
66
+ """Adjacent moves only: the boundary they leave to the neighbouring move lies at
67
+ least this far above (pose z) the gripper event they are anchored on."""
68
+
69
+
70
+ STAGES = {
71
+ "umi-open-drawer": (
72
+ Stage(name="approach", kind="move"),
73
+ Stage(name="close_gripper", kind="close"),
74
+ Stage(name="transport", kind="move"),
75
+ Stage(name="open_gripper", kind="open"),
76
+ ),
77
+ # The native ManiSkill StackCube expert's six primitives. The grasp holds the
78
+ # TCP at the centre of a 4 cm cube: the descent starts above its top (2 cm, and
79
+ # 5 mm to spare), and the lift carries it at least a cube height, over cube B.
80
+ "StackCube-v1": (
81
+ Stage(name="approach", kind="move"),
82
+ Stage(name="grasp_pose", kind="move", adjacent="next", min_rise_m=0.025),
83
+ Stage(name="close_gripper", kind="close"),
84
+ Stage(name="lift", kind="move", adjacent="previous", min_rise_m=0.04),
85
+ Stage(name="place_pose", kind="move"),
86
+ Stage(name="open_gripper", kind="open"),
87
+ ),
88
+ }
89
+
90
+
91
+ def check_stages(stages):
92
+ """Each run of moves between gripper events: one unmarked move at most, the
93
+ ``previous`` moves before it and the ``next`` ones after it, each with an event
94
+ on that side; more than one move needs exactly one unmarked."""
95
+ if not stages or stages[0].kind == "open":
96
+ raise ValueError("A task starts with the gripper open")
97
+ events = [s.kind for s in stages if s.kind != "move"]
98
+ if any(a == b for a, b in zip(events, events[1:])) or (events and events[0] != "close"):
99
+ raise ValueError("Closings and openings must alternate, starting with a closing")
100
+ if any(s.min_rise_m is not None and s.adjacent is None for s in stages):
101
+ raise ValueError("Only a move adjacent to a gripper event has a minimum rise")
102
+ runs, run = [], []
103
+ for index, stage in enumerate(stages):
104
+ if stage.kind == "move":
105
+ run.append(index)
106
+ else:
107
+ runs.append(run)
108
+ run = []
109
+ runs.append(run)
110
+ for position, run in enumerate(runs):
111
+ marks = [stages[i].adjacent for i in run]
112
+ if any(m == "previous" for m in marks) and position == 0:
113
+ raise ValueError("A move before the first event cannot follow one")
114
+ if any(m == "next" for m in marks) and position == len(runs) - 1:
115
+ raise ValueError("A move after the last event cannot precede one")
116
+ order = {"previous": 0, None: 1, "next": 2}
117
+ if [order[m] for m in marks] != sorted(order[m] for m in marks):
118
+ raise ValueError("Moves after an event come first, moves before an event last")
119
+ if len(run) > 1 and marks.count(None) != 1:
120
+ raise ValueError("A run of several moves needs exactly one unmarked move")
121
+ return runs
122
+
123
+
124
+ class KeyposeExtractConfig(BaseModel, frozen=True):
125
+ model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
126
+ dataset: Path
127
+ """Converted recordings (lim.umi_data) or simulated demonstrations (trajectory.h5)."""
128
+ output: Path
129
+ """New keyframes H5, one traj group per kept demonstration."""
130
+ audit: Path
131
+ """New audit JSON."""
132
+ task: str = "umi-open-drawer"
133
+ """Stage configuration (STAGES)."""
134
+ open_above: float | None = None
135
+ """Width events: gripper value at or above which the gripper is fully open."""
136
+ closed_below: float | None = None
137
+ """Width events: gripper value at or below which it is closed."""
138
+ stationary_m: PositiveFloat = 0.001
139
+ """Path points closer than this to the previous kept point are dropped (pauses)."""
140
+ straight_m: PositiveFloat = 0.003
141
+ """Largest distance of a straight motion's points from its chord."""
142
+ straight_deg: PositiveFloat = 3.0
143
+ """Largest angle between its orientations and the ones interpolated along it."""
144
+ motion_m: PositiveFloat = 1e-4
145
+ """Command events: an action moves the arm when its commanded pose moves more than this,"""
146
+ motion_rad: PositiveFloat = float(np.deg2rad(0.1))
147
+ """or turns more than this, from the previous action's."""
148
+ demos: NonNegativeInt | None = None
149
+ """Simulated datasets: only the first this many demonstrations (training order)."""
150
+ boundary_margin: NonNegativeInt = 3
151
+ """Frames either side of an endpoint checked for interpolated poses (audit only)."""
152
+ sheets: Path | None = None
153
+ """New directory for contact sheets of the first camera at every endpoint."""
154
+
155
+ @model_validator(mode="after")
156
+ def check(self):
157
+ if self.task not in STAGES:
158
+ raise ValueError(f"Unknown task {self.task}; known: {sorted(STAGES)}")
159
+ check_stages(STAGES[self.task])
160
+ if (self.open_above is None) != (self.closed_below is None):
161
+ raise ValueError("Width events need both thresholds")
162
+ if self.closed_below is not None and self.closed_below >= self.open_above:
163
+ raise ValueError("The closed threshold must lie below the open one")
164
+ return self
165
+
166
+
167
+ def segment_ends(gripper, open_above, closed_below):
168
+ """Width events: end frames of the segments of the single grasp, the last being
169
+ where the demonstration is cropped, or the number of excursions from the open
170
+ stop when there is more than one."""
171
+ gripper = np.asarray(gripper)
172
+ full = gripper >= open_above
173
+ if not full[0]:
174
+ raise ValueError("The gripper must start fully open")
175
+ leaving = np.flatnonzero(full[:-1] & ~full[1:]) + 1
176
+ returning = np.flatnonzero(~full[:-1] & full[1:]) + 1
177
+ if len(leaving) == 0:
178
+ raise ValueError("The gripper never leaves the open stop")
179
+ if len(leaving) > 1:
180
+ return len(leaving)
181
+ last = len(gripper) - 1
182
+ back = int(returning[0]) if len(returning) else None
183
+ closed = np.flatnonzero(gripper[leaving[0]:back] <= closed_below) + leaving[0]
184
+ if len(closed) == 0:
185
+ raise ValueError("The gripper never closes")
186
+ if closed[-1] == last:
187
+ raise ValueError("The recording ends before the gripper starts opening")
188
+ return [int(leaving[0] - 1), int(closed[0]), int(closed[-1]), last if back is None else back]
189
+
190
+
191
+ def width_events(gripper, open_above, closed_below):
192
+ """[(start, end)] of the closing and the opening, or the excursion count."""
193
+ ends = segment_ends(gripper, open_above, closed_below)
194
+ if isinstance(ends, int):
195
+ return ends
196
+ return [(ends[0], ends[1]), (ends[2], ends[3])]
197
+
198
+
199
+ def command_events(actions, commanded, motion_m, motion_rad):
200
+ """[(start, end)] of every gripper event from the recorded commands: from the
201
+ action whose gripper command changes sign to the first later action whose
202
+ commanded pose (``commanded``, per frame) moves by more than the thresholds from
203
+ the previous action's, or to the last action."""
204
+ actions = np.asarray(actions, dtype=np.float64)
205
+ closed = actions[:, -1] < 0
206
+ if closed[0]:
207
+ raise ValueError("The gripper must start open")
208
+ starts = np.flatnonzero(closed[1:] != closed[:-1]) + 1
209
+ moving = (np.linalg.norm(np.diff(commanded[:, :3], axis=0), axis=1) > motion_m) | (
210
+ _quaternion_angle(commanded[1:, 3:7], commanded[:-1, 3:7]) > motion_rad
211
+ )
212
+ events = []
213
+ for index, start in enumerate(starts):
214
+ limit = starts[index + 1] if index + 1 < len(starts) else len(actions)
215
+ later = np.flatnonzero(moving[start + 1:limit]) + start + 1
216
+ events.append((int(start), int(later[0]) if len(later) else int(limit)))
217
+ return events
218
+
219
+
220
+ CONTROLLER_ROTATION_SCALE = -0.1
221
+ """lim.action_encoding.ROTATION_SCALE (ManiSkill 3.0.1 CPU PDEEPoseController)."""
222
+
223
+
224
+ def _wxyz_to_matrix(q):
225
+ w, x, y, z = np.moveaxis(q / np.linalg.norm(q, axis=-1, keepdims=True), -1, 0)
226
+ return np.stack([
227
+ np.stack([1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], -1),
228
+ np.stack([2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], -1),
229
+ np.stack([2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)], -1),
230
+ ], -2)
231
+
232
+
233
+ def _matrix_to_wxyz(m):
234
+ """Shepperd's method, w >= 0."""
235
+ trace = np.trace(m, axis1=-2, axis2=-1)
236
+ q = np.empty(m.shape[:-2] + (4,))
237
+ for index in np.ndindex(m.shape[:-2]):
238
+ r, t = m[index], trace[index]
239
+ if t > 0:
240
+ s = 2 * np.sqrt(t + 1)
241
+ v = [s / 4, (r[2, 1] - r[1, 2]) / s, (r[0, 2] - r[2, 0]) / s, (r[1, 0] - r[0, 1]) / s]
242
+ else:
243
+ i = int(np.argmax(np.diag(r)))
244
+ j, k = (i + 1) % 3, (i + 2) % 3
245
+ s = 2 * np.sqrt(1 + r[i, i] - r[j, j] - r[k, k])
246
+ v = [0.0] * 4
247
+ v[0] = (r[k, j] - r[j, k]) / s
248
+ v[1 + i], v[1 + j], v[1 + k] = s / 4, (r[j, i] + r[i, j]) / s, (r[k, i] + r[i, k]) / s
249
+ v = np.asarray(v)
250
+ q[index] = v if v[0] >= 0 else -v
251
+ return q
252
+
253
+
254
+ def _euler_xyz(e):
255
+ """Rx(e0) @ Ry(e1) @ Rz(e2), mani_skill's euler_angles_to_matrix(..., "XYZ")."""
256
+ c, s = np.cos(e), np.sin(e)
257
+ o, i = np.zeros(e.shape[:-1]), np.ones(e.shape[:-1])
258
+ rx = np.stack([np.stack([i, o, o], -1), np.stack([o, c[..., 0], -s[..., 0]], -1),
259
+ np.stack([o, s[..., 0], c[..., 0]], -1)], -2)
260
+ ry = np.stack([np.stack([c[..., 1], o, s[..., 1]], -1), np.stack([o, i, o], -1),
261
+ np.stack([-s[..., 1], o, c[..., 1]], -1)], -2)
262
+ rz = np.stack([np.stack([c[..., 2], -s[..., 2], o], -1), np.stack([s[..., 2], c[..., 2], o], -1),
263
+ np.stack([o, o, i], -1)], -2)
264
+ return rx @ ry @ rz
265
+
266
+
267
+ def commanded_poses(actions, tcp):
268
+ """Per frame, the pose the recording commands: frame 0 the reached start, frame
269
+ t + 1 the pd_ee_delta_pose goal of action t, as
270
+ lim.chunk_coordinates.controller_pose_targets reconstructs it (xyz,wxyz)."""
271
+ actions, tcp = np.asarray(actions, dtype=np.float64), np.asarray(tcp, dtype=np.float64)
272
+ position = tcp[:-1, :3] + np.clip(actions[:, :3], -1, 1) * 0.1
273
+ rotation = actions[:, 3:6] / np.maximum(np.linalg.norm(actions[:, 3:6], axis=1, keepdims=True), 1)
274
+ matrix = _euler_xyz(rotation * CONTROLLER_ROTATION_SCALE) @ _wxyz_to_matrix(tcp[:-1, 3:7])
275
+ goals = np.concatenate([position, _matrix_to_wxyz(matrix)], 1)
276
+ return np.concatenate([tcp[:1], goals], 0)
277
+
278
+
279
+ def _quaternion_angle(a, b):
280
+ """Angle between wxyz unit quaternions."""
281
+ dot = np.abs(np.sum(a * b, axis=-1)).clip(max=1.0)
282
+ return 2 * np.arccos(dot)
283
+
284
+
285
+ def _slerp(a, b, alpha):
286
+ if np.dot(a, b) < 0:
287
+ b = -b
288
+ dot = float(np.clip(np.dot(a, b), -1, 1))
289
+ angle = np.arccos(dot)
290
+ if angle < 1e-8:
291
+ return np.broadcast_to(a, (len(alpha), 4))
292
+ alpha = np.asarray(alpha)[:, None]
293
+ return (np.sin((1 - alpha) * angle) * a + np.sin(alpha * angle) * b) / np.sin(angle)
294
+
295
+
296
+ def straight_boundary(pose, anchor, limit, config: KeyposeExtractConfig, min_rise=None):
297
+ """Boundary frame of the straight motion that ends (limit < anchor) or starts
298
+ (limit > anchor) at frame ``anchor``, searched no further than ``limit``; with
299
+ ``min_rise``, no rest frame lower than that above the anchor."""
300
+ step = -1 if limit < anchor else 1
301
+ frames = np.arange(anchor, limit + step, step)
302
+ position, rotation = pose[frames, :3], pose[frames, 3:7]
303
+ kept = [0]
304
+ for i in range(1, len(frames)):
305
+ if np.linalg.norm(position[i] - position[kept[-1]]) >= config.stationary_m:
306
+ kept.append(i)
307
+ kept = np.asarray(kept)
308
+ best = 0
309
+ for c in range(1, len(kept)):
310
+ points = position[kept[: c + 1]]
311
+ chord = points[-1] - points[0]
312
+ length = np.linalg.norm(chord)
313
+ offsets = points - points[0]
314
+ if length > 0:
315
+ along = offsets @ chord / length
316
+ distance = np.linalg.norm(offsets - np.outer(along / length, chord), axis=1)
317
+ else:
318
+ distance = np.linalg.norm(offsets, axis=1)
319
+ arc = np.r_[0, np.cumsum(np.linalg.norm(np.diff(points, axis=0), axis=1))]
320
+ alpha = arc / arc[-1] if arc[-1] > 0 else np.linspace(0, 1, len(points))
321
+ expected = _slerp(rotation[kept[0]], rotation[kept[c]], alpha)
322
+ angle = _quaternion_angle(rotation[kept[: c + 1]], expected)
323
+ if distance.max() > config.straight_m or np.rad2deg(angle.max()) > config.straight_deg:
324
+ break
325
+ best = c
326
+ far = kept[best]
327
+ # The stretch includes the frames still at its far end (the arrival there).
328
+ while far + 1 < len(frames) and np.linalg.norm(position[far + 1] - position[far]) < config.stationary_m:
329
+ far += 1
330
+ # Inside that stretch the boundary is where the arm comes to rest at the far
331
+ # end: the farthest group of rest frames (reached by a step no longer than
332
+ # stationary_m and no longer than the steps before and after it; groups at most
333
+ # two frames apart), and the earliest frame of that group. A pause inside the
334
+ # motion is a nearer group. Without a rest frame, the far end itself.
335
+ times = frames[: far + 1]
336
+ speed = np.linalg.norm(np.diff(pose[:, :3], axis=0), axis=1)
337
+ arrival = np.r_[np.inf, speed][times]
338
+ after = np.r_[speed, np.inf][times]
339
+ before = np.r_[np.inf, np.inf, speed][times]
340
+ rest = times[(arrival <= config.stationary_m) & (arrival <= after) & (arrival <= before)]
341
+ rest = rest[rest != anchor]
342
+ # A demonstration sped up need not slow down at the far end; a pause next to
343
+ # the gripper is then the only rest, and lies below the task's rise.
344
+ if min_rise is not None:
345
+ rest = rest[pose[rest, 2] - pose[anchor, 2] >= min_rise]
346
+ if len(rest) == 0:
347
+ return int(frames[far])
348
+ farthest_first = sorted(rest, key=lambda frame: -abs(frame - anchor))
349
+ group = [farthest_first[0]]
350
+ for frame in farthest_first[1:]:
351
+ if abs(frame - group[-1]) > 2:
352
+ break
353
+ group.append(frame)
354
+ return int(min(group))
355
+
356
+
357
+ def stage_ends(pose, events, stages, config: KeyposeExtractConfig):
358
+ """End frame of every stage, given the gripper events [(start, end)] and the
359
+ cropped length (the last event's end, or the last frame)."""
360
+ runs = check_stages(stages)
361
+ kinds = [s.kind for s in stages if s.kind != "move"]
362
+ if len(events) != len(kinds):
363
+ return None
364
+ bounds = [0]
365
+ for start, end in events:
366
+ bounds += [start, end]
367
+ last = events[-1][1] if stages[-1].kind != "move" else len(pose) - 1
368
+ bounds.append(last)
369
+ ends = {}
370
+ for position, run in enumerate(runs):
371
+ left, right = bounds[2 * position], bounds[2 * position + 1]
372
+ if right < left:
373
+ raise ValueError("Gripper events overlap")
374
+ if not run:
375
+ continue
376
+ if len(run) == 1:
377
+ ends[run[0]] = right
378
+ continue
379
+ for i in [i for i in run if stages[i].adjacent == "previous"]:
380
+ left = ends[i] = straight_boundary(pose, left, right, config, stages[i].min_rise_m)
381
+ for i in reversed([i for i in run if stages[i].adjacent == "next"]):
382
+ ends[i] = right
383
+ right = straight_boundary(pose, right, left, config, stages[i].min_rise_m)
384
+ ends[next(i for i in run if stages[i].adjacent is None)] = right
385
+ event_index = 0
386
+ for i, stage in enumerate(stages):
387
+ if stage.kind != "move":
388
+ ends[i] = events[event_index][1]
389
+ event_index += 1
390
+ result = [ends[i] for i in range(len(stages))]
391
+ if any(b <= a for a, b in zip([0, *result], result)):
392
+ raise ValueError(f"Empty or reversed stage: ends {result}")
393
+ return result
394
+
395
+
396
+ def extract(pose, gripper, config: KeyposeExtractConfig, actions=None):
397
+ """Keyframe arrays of the cropped demonstration, or the reason it is excluded
398
+ (an int: excursions from the open stop; a str otherwise). With ``actions``,
399
+ ``pose`` is the commanded pose per frame (commanded_poses)."""
400
+ stages = STAGES[config.task]
401
+ if actions is None:
402
+ events = width_events(gripper, config.open_above, config.closed_below)
403
+ if isinstance(events, int):
404
+ return events
405
+ else:
406
+ events = command_events(actions, pose, config.motion_m, config.motion_rad)
407
+ ends = stage_ends(pose, events, stages, config)
408
+ if ends is None:
409
+ return f"{len(events)} gripper events, the task has {sum(s.kind != 'move' for s in stages)}"
410
+ starts = (0, *ends[:-1])
411
+ if actions is None:
412
+ state, commands = 1.0, []
413
+ for stage in stages:
414
+ state = {"close": -1.0, "open": 1.0}.get(stage.kind, state)
415
+ commands.append(state)
416
+ else:
417
+ commands = [float(actions[start, -1]) for start in starts]
418
+ for start, end, command in zip(starts, ends, commands):
419
+ if not np.all(actions[start:end, -1] == command):
420
+ raise ValueError("The gripper command changes inside a stage")
421
+ segments = tuple(
422
+ KeyposeSegment(name=stage.name, kind=stage.kind, start=start, end=end, gripper=command,
423
+ target_pose=tuple(float(v) for v in pose[end]))
424
+ for stage, start, end, command in zip(stages, starts, ends, commands)
425
+ )
426
+ return annotation_arrays(AnnotationConfig(
427
+ segments=segments, source_steps=ends[-1], target_to_source=tuple(range(ends[-1]))))
428
+
429
+
430
+ def contact_sheets(directory, data, kept, names, camera, columns=15, tile=112):
431
+ """One sheet per endpoint: the camera frame there for every kept demonstration."""
432
+ from PIL import Image, ImageDraw
433
+
434
+ directory.mkdir(parents=True)
435
+ rows = -(-len(kept) // columns)
436
+ for k, name in enumerate(names):
437
+ sheet = Image.new("RGB", (columns * tile, rows * tile))
438
+ for i, (traj, ends) in enumerate(kept):
439
+ image = Image.fromarray(data[f"{traj}/obs/rgb/{camera}"][ends[k]]).resize((tile, tile))
440
+ ImageDraw.Draw(image).text((3, 2), traj.removeprefix("traj_"), fill=(255, 255, 0))
441
+ sheet.paste(image, ((i % columns) * tile, (i // columns) * tile))
442
+ sheet.save(directory / f"{k}_{name}.jpg", quality=85)
443
+
444
+
445
+ def write_keyframes(out, traj, arrays, stages, reached, frames, attrs):
446
+ keyframes = out.create_group(f"{traj}/keyframes")
447
+ keyframes.attrs.update(frames=frames, schema_version=1, **attrs,
448
+ interval="actions[start:end]; obs[end] is the achieved endpoint",
449
+ label_scope="supervision only; never policy input")
450
+ for name, values in arrays.items():
451
+ keyframes.create_dataset(name, data=values)
452
+ for name, values in (("name", [s.name for s in stages]), ("kind", [s.kind for s in stages])):
453
+ keyframes.create_dataset(name, data=list(values), dtype=h5py.string_dtype("utf-8"))
454
+ keyframes.create_dataset("achieved_pose_world", data=reached[arrays["end_action"]])
455
+
456
+
457
+ def run(config: KeyposeExtractConfig):
458
+ with h5py.File(config.dataset, "r") as data:
459
+ recorded = data.attrs.get("format") == FORMAT
460
+ result = run_recorded(config) if recorded else run_simulated(config)
461
+ with config.audit.open("x") as stream:
462
+ stream.write(json.dumps(result, indent=1) + "\n")
463
+ if config.sheets is not None and recorded:
464
+ with h5py.File(config.dataset, "r") as data:
465
+ camera = next(iter(json.loads(data.attrs["config"])["cameras"]))
466
+ kept = [(row["traj"], row["end_frames"]) for row in result["rows"]]
467
+ contact_sheets(config.sheets, data, kept, [s.name for s in STAGES[config.task]], camera)
468
+ return result
469
+
470
+
471
+ def _header(out, config):
472
+ out.attrs.update(
473
+ dataset=str(config.dataset), dataset_sha256=file_digest(config.dataset),
474
+ extractor_sha256=file_digest(__file__), keypose_data_sha256=file_digest(keypose_data.__file__),
475
+ config=config.model_dump_json(),
476
+ )
477
+
478
+
479
+ def run_recorded(config: KeyposeExtractConfig):
480
+ """Recordings converted by lim.umi_data: width events."""
481
+ if config.open_above is None:
482
+ raise ValueError("Recorded hands need the width thresholds")
483
+ stages = STAGES[config.task]
484
+ names = [s.name for s in stages]
485
+ rows, excluded = [], []
486
+ with h5py.File(config.dataset, "r") as data, h5py.File(config.output, "x") as out:
487
+ _header(out, config)
488
+ for traj in sorted(data, key=lambda name: int(name.split("_")[-1])):
489
+ group = data[traj]
490
+ pose, gripper = group["obs/hand_pose"][:], group["obs/gripper_width"][:]
491
+ try:
492
+ arrays = extract(pose, gripper, config)
493
+ except ValueError as error:
494
+ raise ValueError(f"{traj} ({group.attrs['source']}): {error}") from error
495
+ if not isinstance(arrays, dict):
496
+ reason = f"leaves the open stop {arrays} times" if isinstance(arrays, int) else arrays
497
+ excluded.append({"traj": traj, "source": group.attrs["source"], "reason": reason})
498
+ continue
499
+ ends = arrays["end_action"]
500
+ write_keyframes(out, traj, arrays, stages, pose, ends[-1] + 1, {
501
+ "source": "extracted from gripper events; no commanded targets",
502
+ "pose_frame": "VIO world (lim.umi_data)", "pose_encoding": "xyz,wxyz"})
503
+ times = group["timestamps"][:]
504
+ flagged = group["obs/hand_pose_interpolated"][:] | group["obs/head_pose_interpolated"][:]
505
+ margin = config.boundary_margin
506
+ close, open_ = names.index("close_gripper"), names.index("open_gripper")
507
+ rows.append({
508
+ "traj": traj, "source": group.attrs["source"], "recorded_frames": len(pose),
509
+ "end_frames": ends.tolist(), "reaches_open_stop": bool(gripper[ends[-1]] >= config.open_above),
510
+ "segment_seconds": dict(zip(names, np.diff(times[np.r_[0, ends]]).round(3).tolist())),
511
+ "interpolated_endpoints": [name for name, e in zip(names, ends)
512
+ if flagged[max(0, e - margin):e + margin + 1].any()],
513
+ "grasp_min_gripper": float(gripper[ends[close - 1]:ends[open_] + 1].min()),
514
+ })
515
+ summary = {}
516
+ for name in names:
517
+ seconds = [r["segment_seconds"][name] for r in rows]
518
+ summary[name] = {
519
+ "median_s": float(np.median(seconds)),
520
+ "min_s": min(seconds), "max_s": max(seconds),
521
+ "endpoints_interpolated": sum(name in r["interpolated_endpoints"] for r in rows),
522
+ }
523
+ return {
524
+ "dataset": str(config.dataset), "output": str(config.output), "output_sha256": file_digest(config.output),
525
+ "kept": len(rows), "excluded": excluded,
526
+ "frames_kept": sum(r["end_frames"][-1] + 1 for r in rows),
527
+ "frames_cropped": sum(r["recorded_frames"] - r["end_frames"][-1] - 1 for r in rows),
528
+ "cut_before_open_stop": [[r["traj"], r["source"]] for r in rows if not r["reaches_open_stop"]],
529
+ "segments": summary,
530
+ # A grasp that closes much further than the others may have lost the object.
531
+ "lowest_grasp_gripper": [[r["traj"], r["grasp_min_gripper"]]
532
+ for r in sorted(rows, key=lambda r: r["grasp_min_gripper"])[:5]],
533
+ "config": config.model_dump(mode="json"),
534
+ "rows": rows,
535
+ }
536
+
537
+
538
+ def run_simulated(config: KeyposeExtractConfig):
539
+ """Simulated demonstrations (lim.collect_keyposes): command events, paths and
540
+ endpoints on the commanded poses of the recorded actions. The expert's own
541
+ keyframes are never read."""
542
+ stages = STAGES[config.task]
543
+ names = [s.name for s in stages]
544
+ rows, excluded = [], []
545
+ with h5py.File(config.dataset, "r") as data, h5py.File(config.output, "x") as out:
546
+ _header(out, config)
547
+ trajs = sorted(data, key=lambda name: int(name.split("_")[-1]))
548
+ if config.demos is not None:
549
+ trajs = trajs[: config.demos]
550
+ for traj in trajs:
551
+ group = data[traj]
552
+ actions, reached = group["actions"][:], group["obs/extra/tcp_pose"][:]
553
+ pose = commanded_poses(actions, reached)
554
+ try:
555
+ arrays = extract(pose, None, config, actions=actions)
556
+ except ValueError as error:
557
+ raise ValueError(f"{traj}: {error}") from error
558
+ if not isinstance(arrays, dict):
559
+ excluded.append({"traj": traj, "reason": arrays})
560
+ continue
561
+ ends = arrays["end_action"]
562
+ write_keyframes(out, traj, arrays, stages, reached, ends[-1] + 1, {
563
+ "source": "extracted from the recorded actions' commanded poses and gripper commands; "
564
+ "no planner primitives", "pose_frame": "world", "pose_encoding": "xyz,wxyz"})
565
+ rows.append({"traj": traj, "actions": len(actions), "end_frames": ends.tolist(),
566
+ "cropped_actions": len(actions) - int(ends[-1])})
567
+ lengths = {name: [int(e - s) for r in rows for k, (s, e) in enumerate(zip([0, *r["end_frames"]], r["end_frames"]))
568
+ if names[k] == name] for name in names}
569
+ return {
570
+ "dataset": str(config.dataset), "output": str(config.output), "output_sha256": file_digest(config.output),
571
+ "kept": len(rows), "excluded": excluded,
572
+ "segments": {name: {"median_actions": float(np.median(v)), "min": min(v), "max": max(v)}
573
+ for name, v in lengths.items()} if rows else {},
574
+ "config": config.model_dump(mode="json"),
575
+ "rows": rows,
576
+ }
577
+
578
+
579
+ if __name__ == "__main__":
580
+ run(CliApp.run(KeyposeExtractConfig))
fair-comparison/extract-train-v1/code/lim/keypose_oracle.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/extract-train-v1/code/lim/keypose_phase.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 hashlib
10
+
11
+ import torch
12
+ from pydantic import BaseModel, ConfigDict
13
+ from torch import nn
14
+
15
+ KEYPOSE_PHASE_NAMES = (
16
+ "approach",
17
+ "grasp_pose",
18
+ "close_gripper",
19
+ "lift",
20
+ "place_pose",
21
+ "open_gripper",
22
+ )
23
+ DONE_PHASE = len(KEYPOSE_PHASE_NAMES)
24
+ """Seventh class of a done-class head: the item lies past the demonstration's end."""
25
+
26
+
27
+ class KeyposePhaseHeadConfig(BaseModel, frozen=True):
28
+ model_config = ConfigDict(
29
+ arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
30
+ )
31
+ action_head: nn.Linear
32
+ """Existing native action projection, reused without reinitialization."""
33
+ all_queries: bool = False
34
+ """Classify every future action; false retains the original query-zero head."""
35
+ done_class: bool = False
36
+ """Add a seventh "done" class (DONE_PHASE) as a separate one-row projection, so
37
+ the six original rows and every other parameter start exactly as without it."""
38
+
39
+
40
+ class KeyposePhaseHead(nn.Module):
41
+ def __init__(self, config: KeyposePhaseHeadConfig):
42
+ super().__init__()
43
+ self.config = config
44
+ self.action = config.action_head
45
+ device = self.action.weight.device
46
+ devices = [device.index] if device.type == "cuda" else []
47
+ # The extra head must not perturb later model/EMA construction, dropout,
48
+ # native posterior sampling, or the training sample-order RNG.
49
+ with torch.random.fork_rng(devices=devices):
50
+ self.phase = nn.Linear(
51
+ self.action.in_features,
52
+ len(KEYPOSE_PHASE_NAMES),
53
+ device=device,
54
+ dtype=self.action.weight.dtype,
55
+ )
56
+ if config.done_class:
57
+ if not config.all_queries:
58
+ raise ValueError("The done class labels padded chunk items")
59
+ with torch.random.fork_rng(devices=devices):
60
+ # The seventh row a seven-class projection would draw from the
61
+ # same RNG state (its first six weight rows equal self.phase's).
62
+ full = nn.Linear(
63
+ self.action.in_features,
64
+ len(KEYPOSE_PHASE_NAMES) + 1,
65
+ device=device,
66
+ dtype=self.action.weight.dtype,
67
+ )
68
+ self.done_class = nn.Linear(
69
+ self.action.in_features, 1, device=device, dtype=self.action.weight.dtype
70
+ )
71
+ with torch.no_grad():
72
+ self.done_class.weight.copy_(full.weight[DONE_PHASE:])
73
+ self.done_class.bias.copy_(full.bias[DONE_PHASE:])
74
+ self.phase_logits = None
75
+
76
+ def forward(self, features):
77
+ if features.ndim != 3 or features.shape[1] < 1:
78
+ raise ValueError(
79
+ "Expected ACT decoder features with shape batch, query, hidden"
80
+ )
81
+ actions = self.action(features)
82
+ selected = features if self.config.all_queries else features[:, 0]
83
+ self.phase_logits = self.phase(selected)
84
+ if self.config.done_class:
85
+ self.phase_logits = torch.cat([self.phase_logits, self.done_class(selected)], -1)
86
+ return actions
87
+
88
+
89
+ def done_phase_logits(phase_logits):
90
+ """Items x classes logits -> +1 where the argmax is DONE_PHASE, else -1: the
91
+ signal lim.chunk_done's suffix rule reads, so both heads end chunks alike."""
92
+ if phase_logits.ndim != 2 or phase_logits.shape[-1] != DONE_PHASE + 1:
93
+ raise ValueError("Expected items x seven phase logits")
94
+ return torch.where(phase_logits.argmax(-1) == DONE_PHASE, 1.0, -1.0)
95
+
96
+
97
+ def done_class_free_state_sha256(model):
98
+ """Hash of the state without the done-class row; with the same seed it equals
99
+ initial_state_sha256 of the six-class recipe, because the row draws no RNG."""
100
+ digest = hashlib.sha256()
101
+ for name, tensor in model.state_dict().items():
102
+ if ".action_head.done_class." in name:
103
+ continue
104
+ digest.update(name.encode())
105
+ digest.update(tensor.detach().cpu().contiguous().numpy().tobytes())
106
+ return digest.hexdigest()
107
+
108
+
109
+ def read_phase_logits(model):
110
+ """Return six (seven with a done class) raw class logits from the latest forward.
111
+
112
+ Accept the native agent or any registered model wrapper. Does not invoke the
113
+ network, sample a latent, detach gradients, or change the action output.
114
+ """
115
+ heads = [part for part in model.modules() if isinstance(part, KeyposePhaseHead)]
116
+ if len(heads) != 1:
117
+ raise ValueError("Expected exactly one enabled keypose phase head")
118
+ logits = heads[0].phase_logits
119
+ if logits is None:
120
+ raise RuntimeError("Phase logits require a completed policy forward")
121
+ return logits
fair-comparison/extract-train-v1/code/lim/keypose_policy.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/extract-train-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/extract-train-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/extract-train-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/extract-train-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/extract-train-v1/code/lim/normalization.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # 11: B-spline segment rows, a knot column before target10.
87
+ (10, 11) if self.action_encoding == "rotation6d" else (4, 7)
88
+ ):
89
+ raise ValueError(
90
+ "Fitted statistics differ from the supported state/action layout"
91
+ )
92
+ if self.config.method == "none":
93
+ raise ValueError("The unnormalized control must not have fitted statistics")
94
+ if self.action.center[-1] != 0 or self.action.scale[-1] != 1:
95
+ raise ValueError("Gripper must remain unchanged")
96
+ identity = self.action if self.config.method == "state_zscore" else self.state
97
+ if any(identity.center) or any(s != 1 for s in identity.scale):
98
+ raise ValueError(
99
+ "An independent candidate must leave the other modality unchanged"
100
+ )
101
+ return self
102
+
103
+
104
+ class FitNormalizationConfig(BaseModel, frozen=True):
105
+ model_config = ConfigDict(
106
+ arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
107
+ )
108
+ dataset: Any
109
+ """Native delta dataset after action encoding, before chunk/padding normalization."""
110
+ normalization: NormalizationConfig
111
+ """Single-factor fitting recipe."""
112
+ action_encoding: ActionEncoding
113
+ """Coordinates of the dataset actions."""
114
+ source: Path
115
+ """Training HDF5 used by this dataset."""
116
+ action_samples: Any | None = None
117
+ """Explicit encoded population for sample-dependent labels; excludes padding."""
118
+
119
+
120
+ def fit_normalization(config: FitNormalizationConfig):
121
+ if config.normalization.method == "none":
122
+ return None
123
+ dataset = config.dataset
124
+ if not dataset.delta_control or dataset.norm_stats is not None:
125
+ raise ValueError(
126
+ "Normalization requires raw native delta-control observations/actions"
127
+ )
128
+ actions, states = [], []
129
+ for action, obs in zip(
130
+ dataset.trajectories["actions"],
131
+ dataset.trajectories["observations"],
132
+ strict=True,
133
+ ):
134
+ state = obs["state"]
135
+ if not len(action) or len(state) != len(action) + 1:
136
+ raise ValueError("Expected one terminal observation per trajectory")
137
+ actions.append(action.double())
138
+ states.append(state[: len(action)].double())
139
+ action = torch.cat(actions)
140
+ if config.action_samples is not None:
141
+ action = torch.as_tensor(config.action_samples).double()
142
+ if action.ndim != 2 or not len(action):
143
+ raise ValueError("Expected nonempty encoded action population")
144
+ state = torch.cat(states)
145
+ if not torch.isfinite(action).all() or not torch.isfinite(state).all():
146
+ raise ValueError("Nonfinite training data")
147
+ state_center, state_scale = (
148
+ torch.zeros(state.shape[-1]),
149
+ torch.ones(state.shape[-1]),
150
+ )
151
+ action_center, action_scale = (
152
+ torch.zeros(action.shape[-1]),
153
+ torch.ones(action.shape[-1]),
154
+ )
155
+ method = config.normalization.method
156
+ if method == "state_zscore":
157
+ state_center = state.mean(0)
158
+ state_scale = torch.maximum(
159
+ state.std(0, correction=0),
160
+ state.new_tensor(config.normalization.state_floor),
161
+ )
162
+ elif method == "action_zscore":
163
+ action_center = action.mean(0)
164
+ action_scale = action.std(0, correction=0).clamp_min(
165
+ config.normalization.action_floor
166
+ )
167
+ else:
168
+ low, high = torch.quantile(action, action.new_tensor([0.01, 0.99]), dim=0)
169
+ action_center = (low + high) / 2
170
+ action_scale = ((high - low) / 2).clamp_min(config.normalization.action_floor)
171
+ action_center[-1], action_scale[-1] = 0, 1
172
+ with config.source.open("rb") as stream:
173
+ source_sha256 = hashlib.file_digest(stream, "sha256").hexdigest()
174
+ return FittedNormalizationConfig(
175
+ config=config.normalization,
176
+ action_encoding=config.action_encoding,
177
+ source_sha256=source_sha256,
178
+ trajectories=len(actions),
179
+ samples=len(action),
180
+ state=AffineConfig(center=state_center.tolist(), scale=state_scale.tolist()),
181
+ action=AffineConfig(center=action_center.tolist(), scale=action_scale.tolist()),
182
+ )
183
+
184
+
185
+ class NormalizedDatasetConfig(BaseModel, frozen=True):
186
+ model_config = ConfigDict(
187
+ arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
188
+ )
189
+ dataset: Any
190
+ """Encoded native dataset, still owning physical stop padding."""
191
+ statistics: FittedNormalizationConfig
192
+ """Training-only fitted affine parameters."""
193
+
194
+
195
+ class NormalizedDataset(Dataset):
196
+ def __init__(self, config: NormalizedDatasetConfig):
197
+ self.config = config
198
+ self.dataset = config.dataset
199
+ self.center = torch.tensor(config.statistics.action.center)
200
+ self.scale = torch.tensor(config.statistics.action.scale)
201
+
202
+ def __getattr__(self, name):
203
+ return getattr(self.dataset, name)
204
+
205
+ def __len__(self):
206
+ return len(self.dataset)
207
+
208
+ def __getitem__(self, index):
209
+ sample = self.dataset[index]
210
+ # Native dataset has already padded zero motion and held the last gripper.
211
+ return {**sample, "actions": (sample["actions"] - self.center) / self.scale}
212
+
213
+
214
+ class NormalizedModelConfig(BaseModel, frozen=True):
215
+ model_config = ConfigDict(
216
+ arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
217
+ )
218
+ model: Any
219
+ """Native CVAE; receives normalized labels and the same normalized state in both branches."""
220
+ statistics: FittedNormalizationConfig
221
+ """Checkpoint-owned transforms; these do not consume random initialization draws."""
222
+
223
+
224
+ class NormalizedModel(nn.Module):
225
+ def __init__(self, config: NormalizedModelConfig):
226
+ super().__init__()
227
+ self.config = config
228
+ self.base = config.model
229
+ # Saved once as checkpoint metadata, not averaged as EMA parameters/buffers.
230
+ for name, values in (
231
+ ("state_center", config.statistics.state.center),
232
+ ("state_scale", config.statistics.state.scale),
233
+ ("action_center", config.statistics.action.center),
234
+ ("action_scale", config.statistics.action.scale),
235
+ ):
236
+ self.register_buffer(name, torch.tensor(values), persistent=False)
237
+
238
+ def forward(self, obs, actions=None):
239
+ obs = {**obs, "state": (obs["state"] - self.state_center) / self.state_scale}
240
+ prediction, latent = self.base(obs, actions)
241
+ if actions is None:
242
+ # Invert BEFORE native time ensembling and Rotation6DEnv projection.
243
+ # No clipping, including predictions outside q01/q99.
244
+ prediction = prediction * self.action_scale + self.action_center
245
+ return prediction, latent
246
+
247
+
248
+ def checked_statistics(raw, normalization, encoding):
249
+ if normalization.method == "none":
250
+ if raw is not None:
251
+ raise ValueError(
252
+ "Unnormalized control unexpectedly contains fitted statistics"
253
+ )
254
+ return None
255
+ if raw is None:
256
+ raise ValueError(
257
+ "Normalized policy requires its training-fitted checkpoint statistics"
258
+ )
259
+ fitted = FittedNormalizationConfig.model_validate(raw)
260
+ if fitted.config != normalization or fitted.action_encoding != encoding:
261
+ raise ValueError(
262
+ "Fitted statistics differ from the policy normalization contract"
263
+ )
264
+ return fitted
fair-comparison/extract-train-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/extract-train-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/extract-train-v1/code/lim/pi05_policy.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """pi0.5 (RLinf's PyTorch port of openpi) on the StackCube chunk labels.
2
+
3
+ The network, its flow-matching loss and its Euler sampler are RLinf's, loaded
4
+ unchanged through lim.rlinf_openpi. This module supplies what RLinf takes from
5
+ openpi's data pipeline, reproduced from openpi (rlinf-openpi 0.1.1):
6
+
7
+ - quantile normalization of state and actions to [-1, 1] (pi0.5 configs use
8
+ ``use_quantile_norm``), actions zero-padded to the model's 32 dimensions;
9
+ - the pi0.5 prompt with the normalized state discretized into 256 bins
10
+ (``discrete_state_input=True``, ``PaligemmaTokenizer.tokenize``), or without
11
+ state the pi0-format prompt (``discrete_state_input=False``, RLinf's default);
12
+ the pi0.5 network never reads the state otherwise, so the observation's state
13
+ is zeroed then;
14
+ - the three image slots: base camera, wrist camera, an all-zero right wrist slot
15
+ with mask False (``LiberoInputs`` for pi0/pi0.5).
16
+
17
+ Labels are exactly the ACT run's: ChunkRelativeDataset items of 10 values
18
+ (chunk-start-relative position, rotation6d, gripper), Q50. A training checkpoint
19
+ is a JSON record (Pi05Checkpoint) beside an EMA safetensors file whose sha256 it
20
+ pins; evaluation hashes the JSON as the checkpoint identity.
21
+ """
22
+
23
+ import hashlib
24
+ import math
25
+ from pathlib import Path
26
+ from typing import Literal
27
+
28
+ import numpy as np
29
+ import torch
30
+ from pydantic import BaseModel, ConfigDict, Field, PositiveInt
31
+
32
+ from lim import rlinf_openpi
33
+ from lim.act_policy import ACTPolicyConfig
34
+
35
+ MODEL_ACTION_DIM = 32
36
+ IMAGE_SLOTS = ("base_0_rgb", "left_wrist_0_rgb", "right_wrist_0_rgb")
37
+ CAMERAS = ("base_camera", "hand_camera")
38
+ """Order of obs["rgb"] (ManiSkill sensor order) mapped onto the first two slots."""
39
+ STATE_BINS = 256
40
+ QUANTILE_EPS = 1e-6
41
+ PROMPT = "stack the red cube on top of the green cube"
42
+ FP32_PROJECTIONS = ("action_in_proj", "action_out_proj", "time_mlp_in", "time_mlp_out")
43
+ NO_SPLIT_CLASSES = ("Block", "Encoder1DBlock", "Encoder", "RMSNorm", "Embedder", "SigLIPViT")
44
+ NO_SPLIT_NAMES = (
45
+ "action_in_proj", "action_out_proj", "state_proj", "action_time_mlp_in",
46
+ "action_time_mlp_out", "time_mlp_in", "time_mlp_out", "stem", "head",
47
+ )
48
+
49
+
50
+ class QuantileStatistics(BaseModel, frozen=True):
51
+ model_config = ConfigDict(extra="forbid")
52
+ q01: list[float]
53
+ q99: list[float]
54
+
55
+ def normalize(self, x):
56
+ q01, q99 = (np.asarray(v, dtype=np.float32) for v in (self.q01, self.q99))
57
+ return (x - q01) / (q99 - q01 + QUANTILE_EPS) * 2.0 - 1.0
58
+
59
+ def unnormalize(self, x):
60
+ q01, q99 = (torch.as_tensor(v, dtype=x.dtype, device=x.device) for v in (self.q01, self.q99))
61
+ return (x + 1.0) / 2.0 * (q99 - q01 + QUANTILE_EPS) + q01
62
+
63
+
64
+ class Pi05Normalization(BaseModel, frozen=True):
65
+ model_config = ConfigDict(extra="forbid")
66
+ source_sha256: str
67
+ """Training H5 the statistics were fitted on (same check as the ACT checkpoints)."""
68
+ state: QuantileStatistics
69
+ actions: QuantileStatistics
70
+ population: str = "every state25 observation and every (sample, item) label row"
71
+
72
+
73
+ class Pi05ModelConfig(BaseModel, frozen=True):
74
+ model_config = ConfigDict(extra="forbid")
75
+ action_horizon: PositiveInt = 50
76
+ action_dim: PositiveInt = 10
77
+ """Real label width; the model sees it zero-padded to MODEL_ACTION_DIM."""
78
+ max_token_len: PositiveInt = 200
79
+ discrete_state_input: bool = True
80
+ """Deviates from RLinf's pi05_maniskill (False), which leaves pi0.5 without state."""
81
+ num_steps: PositiveInt = 10
82
+ prompt: str = PROMPT
83
+
84
+
85
+ def fit_quantiles(rows):
86
+ """Exact 1st/99th percentiles per dimension (openpi approximates them with a histogram)."""
87
+ rows = np.asarray(rows, dtype=np.float64)
88
+ return QuantileStatistics(
89
+ q01=np.quantile(rows, 0.01, axis=0).tolist(), q99=np.quantile(rows, 0.99, axis=0).tolist()
90
+ )
91
+
92
+
93
+ class Tokenizer:
94
+ """openpi PaligemmaTokenizer.tokenize: the pi0.5 branch (state in the prompt) when
95
+ `discrete_state`, otherwise the pi0 branch (prompt, then "\n" encoded separately)."""
96
+
97
+ def __init__(self, path: Path, max_len: int, discrete_state: bool):
98
+ import sentencepiece
99
+
100
+ self.sha256 = hashlib.sha256(Path(path).read_bytes()).hexdigest()
101
+ self.processor = sentencepiece.SentencePieceProcessor(model_file=str(path))
102
+ self.max_len = max_len
103
+ self.discrete_state = discrete_state
104
+
105
+ @staticmethod
106
+ def clean(text):
107
+ return text.strip().replace("_", " ").replace("\n", " ")
108
+
109
+ def prompt(self, text, state):
110
+ bins = np.digitize(state, bins=np.linspace(-1, 1, STATE_BINS + 1)[:-1]) - 1
111
+ return f"Task: {self.clean(text)}, State: {' '.join(map(str, bins))};\nAction: "
112
+
113
+ def encode(self, text, state):
114
+ if self.discrete_state:
115
+ return self.processor.encode(self.prompt(text, state), add_bos=True)
116
+ return self.processor.encode(self.clean(text), add_bos=True) + self.processor.encode("\n")
117
+
118
+ def __call__(self, text, state):
119
+ tokens = self.encode(text, state)
120
+ if len(tokens) > self.max_len:
121
+ raise ValueError(f"Prompt has {len(tokens)} tokens, more than {self.max_len}")
122
+ mask = [True] * len(tokens) + [False] * (self.max_len - len(tokens))
123
+ return np.asarray(tokens + [0] * (self.max_len - len(tokens))), np.asarray(mask)
124
+
125
+
126
+ def build_observation(rl, rgb, normalized_state, tokenizer, prompt):
127
+ """RLinf Observation from obs["rgb"] (B, 2, 3, H, W) uint8 and normalized state25."""
128
+ batch, cameras = rgb.shape[:2]
129
+ if cameras != len(CAMERAS) or rgb.dtype != torch.uint8:
130
+ raise ValueError("Expected the two uint8 StackCube cameras")
131
+ device = rgb.device
132
+ tokens, masks = zip(*(tokenizer(prompt, s) for s in normalized_state))
133
+ state = np.zeros((batch, MODEL_ACTION_DIM), dtype=np.float32)
134
+ if tokenizer.discrete_state:
135
+ state[:, : normalized_state.shape[1]] = normalized_state
136
+ images = {IMAGE_SLOTS[0]: rgb[:, 0], IMAGE_SLOTS[1]: rgb[:, 1], IMAGE_SLOTS[2]: torch.zeros_like(rgb[:, 0])}
137
+ present = torch.ones(batch, dtype=torch.bool, device=device)
138
+ return rl.Observation.from_dict({
139
+ "image": images,
140
+ "image_mask": {IMAGE_SLOTS[0]: present, IMAGE_SLOTS[1]: present, IMAGE_SLOTS[2]: ~present},
141
+ "state": torch.from_numpy(state).to(device),
142
+ "tokenized_prompt": torch.as_tensor(np.stack(tokens), device=device),
143
+ "tokenized_prompt_mask": torch.as_tensor(np.stack(masks), device=device),
144
+ })
145
+
146
+
147
+ def pad_actions(actions):
148
+ padded = actions.new_zeros(*actions.shape[:-1], MODEL_ACTION_DIM)
149
+ padded[..., : actions.shape[-1]] = actions
150
+ return padded
151
+
152
+
153
+ def build_network(rl, model: Pi05ModelConfig):
154
+ config = rl.Pi0Config(
155
+ pi05=True, action_horizon=model.action_horizon, action_dim=MODEL_ACTION_DIM,
156
+ max_token_len=model.max_token_len, discrete_state_input=model.discrete_state_input,
157
+ dtype="bfloat16", paligemma_variant="gemma_2b", action_expert_variant="gemma_300m",
158
+ )
159
+ return rl.Pi0(config, num_steps=model.num_steps)
160
+
161
+
162
+ def load_weights(network, path):
163
+ import safetensors.torch
164
+
165
+ missing, unexpected = network.load_state_dict(safetensors.torch.load_file(str(path)), strict=False)
166
+ if missing or unexpected:
167
+ raise ValueError(f"Weights do not match the network: {missing[:5]} {unexpected[:5]}")
168
+
169
+
170
+ def openpi_cosine(step, *, peak=2.5e-5, warmup=1000, decay_steps=30_000, end=2.5e-6):
171
+ """openpi CosineDecaySchedule (optax warmup_cosine_decay_schedule) at an update index."""
172
+ if step < warmup:
173
+ start = peak / (warmup + 1)
174
+ return start + (peak - start) * step / warmup
175
+ progress = min(1.0, (step - warmup) / (decay_steps - warmup))
176
+ return end + (peak - end) * 0.5 * (1.0 + math.cos(math.pi * progress))
177
+
178
+
179
+ def keeps_float32(name):
180
+ """Parameters openpi's to_bfloat16_for_selected_params leaves in fp32 (RLinf pi0.py)."""
181
+ selected = ("img.stem.weight", "img.stem.bias", "img.pos_embedding",
182
+ "pre_attention_norms", "pre_ffw_norms", "final_norms")
183
+ return not name.startswith(("llm.", "img.")) or any(s in name for s in selected)
184
+
185
+
186
+ class FlowLoss(torch.nn.Module):
187
+ """FSDP root: openpi's training augmentation, then RLinf's flow-matching loss."""
188
+
189
+ def __init__(self, rl, network):
190
+ super().__init__()
191
+ self.preprocess = rl.preprocess_observation
192
+ self.network = network
193
+
194
+ def forward(self, observation, actions, generator):
195
+ observation = self.preprocess(observation, train=True, rng=generator)
196
+ # train=False: the augmentation above already ran; this only rebuilds masks.
197
+ return self.network.compute_loss(observation, actions, train=False).mean()
198
+
199
+
200
+ def wrap_fsdp(root, device_id):
201
+ """FSDP1 NO_SHARD with RLinf's openpi_fsdp precision profile around FlowLoss.
202
+
203
+ Units: RLinf's base policy (Pi0._no_split_modules classes and _no_split_names
204
+ leaves). bf16 compute with fp32 reduction everywhere, except fp32 action/time
205
+ projections and fp32 RMSNorm / SigLIP stem / position embedding that keep their
206
+ inputs' dtype (hybrid_engines/openpi_fsdp.yaml).
207
+ """
208
+ from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
209
+ from torch.distributed.fsdp import MixedPrecision, ShardingStrategy
210
+ from torch.distributed.fsdp.wrap import CustomPolicy
211
+
212
+ fp32, bf16 = torch.float32, torch.bfloat16
213
+ default = MixedPrecision(param_dtype=bf16, reduce_dtype=fp32, buffer_dtype=fp32,
214
+ cast_forward_inputs=False, cast_root_forward_inputs=False)
215
+ full = MixedPrecision(param_dtype=fp32, reduce_dtype=fp32, buffer_dtype=fp32, cast_forward_inputs=True)
216
+ preserve = MixedPrecision(param_dtype=fp32, reduce_dtype=fp32, buffer_dtype=fp32, cast_forward_inputs=False)
217
+ paths = {module: path.removeprefix("network.") for path, module in root.named_modules()
218
+ if path.startswith("network.")}
219
+ classes = {}
220
+ for module in paths:
221
+ classes.setdefault(type(module).__name__, set()).add(type(module))
222
+ # RLinf resolves each class name to one class (transformers get_module_class_from_name).
223
+ assert all(len(classes.get(name, ())) <= 1 for name in NO_SPLIT_CLASSES)
224
+
225
+ def unit(module):
226
+ path = paths.get(module)
227
+ if path is None:
228
+ return False
229
+ name = path.rsplit(".", 1)[-1]
230
+ if name in FP32_PROJECTIONS:
231
+ return {"mixed_precision": full}
232
+ if type(module).__name__ == "RMSNorm" or path in ("img", "img.stem"):
233
+ return {"mixed_precision": preserve}
234
+ return type(module).__name__ in NO_SPLIT_CLASSES or name in NO_SPLIT_NAMES
235
+
236
+ return FSDP(root, auto_wrap_policy=CustomPolicy(unit), mixed_precision=default,
237
+ sharding_strategy=ShardingStrategy.NO_SHARD, device_id=device_id,
238
+ use_orig_params=True, sync_module_states=True)
239
+
240
+
241
+ class Pi05Checkpoint(BaseModel, frozen=True):
242
+ model_config = ConfigDict(extra="forbid")
243
+ format: Literal["lim-pi05-v1"] = "lim-pi05-v1"
244
+ rlinf_commit: str
245
+ weights: str
246
+ """EMA safetensors file name beside this record."""
247
+ weights_sha256: str
248
+ base_sha256: str
249
+ """model.safetensors of the converted pi05_base the run started from."""
250
+ tokenizer_sha256: str
251
+ update: int = Field(ge=1)
252
+ """Updates the EMA weights include."""
253
+ model: Pi05ModelConfig
254
+ normalization: Pi05Normalization
255
+ policy: ACTPolicyConfig
256
+ """Label and anchor contract shared with the ACT runs (chunk_relative, rotation6d)."""
257
+
258
+
259
+ class HostTokenEmbedding(torch.nn.Module):
260
+ """An nn.Embedding whose table stays in host memory; only the looked-up rows go
261
+ to the tokens' device. A gather copies rows exactly, so the output equals the
262
+ original lookup bit for bit. The table is a plain attribute, not a parameter or
263
+ buffer, so moving the module (.cuda()) leaves it on the host."""
264
+
265
+ def __init__(self, embedding: torch.nn.Embedding):
266
+ super().__init__()
267
+ if embedding.padding_idx is not None or embedding.max_norm is not None:
268
+ raise ValueError("Only a plain lookup table can stay on the host")
269
+ self.table = embedding.weight.detach().cpu()
270
+
271
+ def forward(self, tokens):
272
+ return self.table[tokens.cpu()].to(tokens.device)
273
+
274
+
275
+ class Pi05Agent(torch.nn.Module):
276
+ """Evaluation wrapper with the ACT agent's get_action contract (lim.keypose_diagnostics).
277
+
278
+ `host_token_embedding` keeps the Gemma token embedding table (257,152 x 2,048,
279
+ 0.98 GiB in bf16) in host memory, for GPUs of about 8 GB. Inference only looks
280
+ up the prompt's tokens in it (the sampler never projects onto the vocabulary),
281
+ and the outputs are bit-identical."""
282
+
283
+ def __init__(self, record_path: Path, tokenizer_path: Path, host_token_embedding: bool = False):
284
+ super().__init__()
285
+ self.record = Pi05Checkpoint.model_validate_json(Path(record_path).read_text())
286
+ weights = Path(record_path).parent / self.record.weights
287
+ if hashlib.sha256(weights.read_bytes()).hexdigest() != self.record.weights_sha256:
288
+ raise ValueError("EMA weights differ from the checkpoint record")
289
+ self.rl = rlinf_openpi.load()
290
+ self.rl.set_torch_compile(False)
291
+ if self.rl.commit != self.record.rlinf_commit:
292
+ raise ValueError("RLinf checkout differs from the one that trained the checkpoint")
293
+ self.tokenizer = Tokenizer(tokenizer_path, self.record.model.max_token_len,
294
+ self.record.model.discrete_state_input)
295
+ if self.tokenizer.sha256 != self.record.tokenizer_sha256:
296
+ raise ValueError("Tokenizer differs from the one used in training")
297
+ self.network = build_network(self.rl, self.record.model)
298
+ load_weights(self.network, weights)
299
+ # openpi inference precision: Gemma/SigLIP bf16 with fp32 norms and stem.
300
+ self.network.to_bfloat16_for_selected_params("bfloat16")
301
+ if host_token_embedding:
302
+ embedder = self.network.llm.embedder
303
+ embedder.embedding = HostTokenEmbedding(embedder.embedding)
304
+ self.network.eval()
305
+ self.generator = None
306
+
307
+ def seed_noise(self, seed):
308
+ """Restart the inference noise stream (per episode, as for lim.chunk_flow)."""
309
+ device = next(self.network.parameters()).device
310
+ self.generator = torch.Generator(device=device)
311
+ self.generator.manual_seed(seed)
312
+
313
+ def get_action(self, obs):
314
+ if self.generator is None:
315
+ raise RuntimeError("seed_noise must be called before the first query")
316
+ model, norm = self.record.model, self.record.normalization
317
+ state = norm.state.normalize(obs["state"].float().cpu().numpy())
318
+ observation = build_observation(self.rl, obs["rgb"], state, self.tokenizer, model.prompt)
319
+ noise = torch.randn(state.shape[0], model.action_horizon, MODEL_ACTION_DIM,
320
+ generator=self.generator, device=self.generator.device)
321
+ actions = self.network.sample_actions(observation, num_steps=model.num_steps, noise=noise)
322
+ return norm.actions.unnormalize(actions[..., : model.action_dim].float())
fair-comparison/extract-train-v1/code/lim/planned_keypose.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/extract-train-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/extract-train-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/extract-train-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/extract-train-v1/code/lim/real_chunks.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Chunk labels for recorded real demonstrations (lim.umi_data, lim.keypose_extract).
2
+
3
+ Each item has the ten values of the simulated chunk-relative labels -- translation
4
+ / 0.1 m, lim.action_encoding 6D rotation, gripper -- but in the current hand frame:
5
+ ``item = inv(T_t) @ T_target``. The simulated labels keep world axes because the
6
+ Panda root is fixed. A hand-held recording has no fixed root (the VIO origin is the
7
+ head at the start of each recording), so only the hand's own frame carries across
8
+ demonstrations, and a robot executes ``T_t @ item`` from its measured TCP.
9
+
10
+ Item i of the chunk at frame t stands for frame ``tau = t + stride * (i + 1)``:
11
+
12
+ - ``dense``: the pose reached at tau;
13
+ - ``future_endpoint``: the endpoint of the segment that the move into tau belongs
14
+ to (``fendpoint_fg`` of the simulated comparison);
15
+ - both: the gripper width at tau.
16
+
17
+ Items past the cropped end repeat the final frame. The final frame is also the last
18
+ segment's endpoint, so both supervisions pad identically. Every frame with a
19
+ following frame is a sample; the policy state is the current gripper width alone,
20
+ since an absolute pose has no meaning across recordings.
21
+
22
+ Statistics, fitted on the training demonstrations and shared by both supervisions
23
+ as in simulation: pose values are z-scored over the dense in-range items (std
24
+ floored at ``action_floor``); the gripper width, label and state alike, is mapped
25
+ to [-1, 1] by the widest opening, ``2 * width / open - 1``.
26
+ """
27
+
28
+ import json
29
+ from pathlib import Path
30
+ from typing import Literal
31
+
32
+ import h5py
33
+ import numpy as np
34
+ import torch
35
+ from mani_skill.utils.geometry.rotation_conversions import quaternion_to_matrix
36
+ from pydantic import (
37
+ BaseModel,
38
+ ConfigDict,
39
+ Field,
40
+ NonNegativeInt,
41
+ PositiveFloat,
42
+ PositiveInt,
43
+ )
44
+ from torch.utils.data import Dataset
45
+
46
+ from lim.action_encoding import matrix_to_sixd, sixd_to_matrix
47
+ from lim.umi_data import FORMAT, file_digest
48
+
49
+ TRANSLATION_SCALE = 0.1
50
+ """Metres per translation label unit, as the simulated labels."""
51
+ SHA256 = r"^[0-9a-f]{64}$"
52
+
53
+
54
+ class RealChunkConfig(BaseModel, frozen=True):
55
+ model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
56
+ dataset: Path
57
+ """Converted demonstrations (lim.umi_data)."""
58
+ dataset_sha256: str = Field(pattern=SHA256)
59
+ keyframes: Path
60
+ """Extracted segments of the same dataset (lim.keypose_extract); fixes the kept
61
+ demonstrations and where each is cropped."""
62
+ keyframes_sha256: str = Field(pattern=SHA256)
63
+ supervision: Literal["dense", "future_endpoint"]
64
+ num_queries: PositiveInt = 50
65
+ frame_stride: PositiveInt = 2
66
+ """Recorded frames per item (2 at 30 Hz: items 1/15 s apart)."""
67
+ camera: str = "wrist"
68
+ dev_demonstrations: NonNegativeInt = 15
69
+ """Kept demonstrations held out for development, drawn once by split_seed."""
70
+ split_seed: int = 0
71
+ action_floor: PositiveFloat = 0.01
72
+ """Minimum std of a pose value, in label units."""
73
+
74
+
75
+ class RealNormalization(BaseModel, frozen=True):
76
+ model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
77
+ dataset_sha256: str = Field(pattern=SHA256)
78
+ keyframes_sha256: str = Field(pattern=SHA256)
79
+ trajectories: PositiveInt
80
+ samples: PositiveInt
81
+ """Dense in-range items the pose statistics were fitted on."""
82
+ pose_center: tuple[float, ...] = Field(min_length=9, max_length=9)
83
+ pose_scale: tuple[PositiveFloat, ...] = Field(min_length=9, max_length=9)
84
+ gripper_open_m: PositiveFloat
85
+ """Widest opening in the training demonstrations; maps to +1."""
86
+
87
+ def affine(self):
88
+ """(center, scale) of the ten action values; the gripper's maps [0, open] to [-1, 1]."""
89
+ half = self.gripper_open_m / 2
90
+ return (torch.tensor([*self.pose_center, half], dtype=torch.float64),
91
+ torch.tensor([*self.pose_scale, half], dtype=torch.float64))
92
+
93
+ def state(self, width):
94
+ half = self.gripper_open_m / 2
95
+ return (width - half) / half
96
+
97
+
98
+ def split(trajs, config: RealChunkConfig):
99
+ """Training and development demonstrations, each in recorded order."""
100
+ order = sorted(trajs, key=lambda name: int(name.split("_")[-1]))
101
+ if config.dev_demonstrations >= len(order):
102
+ raise ValueError("No training demonstrations would remain")
103
+ rng = np.random.default_rng(config.split_seed)
104
+ dev = set(rng.choice(order, config.dev_demonstrations, replace=False).tolist())
105
+ return {"train": [t for t in order if t not in dev], "dev": [t for t in order if t in dev]}
106
+
107
+
108
+ def item_frames(frames, num_queries, stride):
109
+ """(frames - 1, num_queries) frames the items stand for, clamped to the last, and
110
+ whether each is in range."""
111
+ tau = torch.arange(frames - 1)[:, None] + stride * (torch.arange(num_queries)[None] + 1)
112
+ return tau.clamp(max=frames - 1), tau <= frames - 1
113
+
114
+
115
+ def relative_items(anchor, target):
116
+ """inv(T(anchor)) @ T(target) as translation / 0.1 and 6D; poses are xyz,wxyz."""
117
+ rotation = quaternion_to_matrix(anchor[..., 3:]).transpose(-1, -2)
118
+ return torch.cat([
119
+ torch.einsum("...ij,...j->...i", rotation, target[..., :3] - anchor[..., :3]) / TRANSLATION_SCALE,
120
+ matrix_to_sixd(rotation @ quaternion_to_matrix(target[..., 3:])),
121
+ ], -1)
122
+
123
+
124
+ def restore(anchor, items):
125
+ """World position and rotation matrix of hand-frame items (inverse of relative_items)."""
126
+ rotation = quaternion_to_matrix(anchor[..., 3:])
127
+ position = anchor[..., :3] + torch.einsum("...ij,...j->...i", rotation, items[..., :3] * TRANSLATION_SCALE)
128
+ return position, rotation @ sixd_to_matrix(items[..., 3:9])
129
+
130
+
131
+ class RealChunkDataset(Dataset):
132
+ """Samples of one part of the split, loaded into memory.
133
+
134
+ Items are ``{"observations": {"state": (1,), "rgb": (1, 3, H, W) uint8},
135
+ "actions": (num_queries, 10) normalized, "valid": (num_queries,)}``. The training
136
+ part fits the statistics; the development part takes the training part's.
137
+ """
138
+
139
+ def __init__(self, config: RealChunkConfig, part: Literal["train", "dev"],
140
+ statistics: RealNormalization | None = None):
141
+ if (part == "train") != (statistics is None):
142
+ raise ValueError("Only the training part fits statistics; others take them")
143
+ for path, expected in ((config.dataset, config.dataset_sha256), (config.keyframes, config.keyframes_sha256)):
144
+ if file_digest(path) != expected:
145
+ raise ValueError(f"{path} differs from its declared sha256")
146
+ self.config = config
147
+ anchors, chunks, valids, widths, images, population = [], [], [], [], [], []
148
+ with h5py.File(config.dataset, "r") as data, h5py.File(config.keyframes, "r") as keys:
149
+ if data.attrs["format"] != FORMAT or keys.attrs["dataset_sha256"] != config.dataset_sha256:
150
+ raise ValueError("Keyframes were extracted from another dataset")
151
+ self.trajs = split(list(keys), config)[part]
152
+ for traj in self.trajs:
153
+ key = keys[f"{traj}/keyframes"]
154
+ frames = int(key.attrs["frames"])
155
+ ends = torch.from_numpy(key["end_action"][:])
156
+ segment = torch.from_numpy(key["action_keyframe_index"][:])
157
+ if ends[-1] != frames - 1 or len(segment) != frames - 1:
158
+ raise ValueError(f"{traj}: keyframes do not cover the cropped frames")
159
+ pose = torch.from_numpy(data[f"{traj}/obs/hand_pose"][:frames])
160
+ width = torch.from_numpy(data[f"{traj}/obs/gripper_width"][:frames])
161
+ tau, valid = item_frames(frames, config.num_queries, config.frame_stride)
162
+ anchor = pose[:-1, None]
163
+ dense = relative_items(anchor, pose[tau])
164
+ population.append(dense[valid])
165
+ if config.supervision == "dense":
166
+ items = dense
167
+ else:
168
+ items = relative_items(anchor, pose[ends[segment[tau - 1]]])
169
+ chunks.append(torch.cat([items, width[tau, None]], -1))
170
+ anchors.append(pose[:-1])
171
+ valids.append(valid)
172
+ widths.append(width[:-1])
173
+ rgb = data[f"{traj}/obs/rgb/{config.camera}"][:frames - 1]
174
+ images.append(torch.from_numpy(rgb).permute(0, 3, 1, 2)[:, None].contiguous())
175
+ if statistics is None:
176
+ population = torch.cat(population)
177
+ statistics = RealNormalization(
178
+ dataset_sha256=config.dataset_sha256, keyframes_sha256=config.keyframes_sha256,
179
+ trajectories=len(self.trajs), samples=len(population),
180
+ pose_center=population.mean(0).tolist(),
181
+ pose_scale=population.std(0, correction=0).clamp_min(config.action_floor).tolist(),
182
+ gripper_open_m=float(torch.cat(widths).max()),
183
+ )
184
+ elif (statistics.dataset_sha256, statistics.keyframes_sha256) != (config.dataset_sha256,
185
+ config.keyframes_sha256):
186
+ raise ValueError("Statistics belong to another dataset")
187
+ self.statistics = statistics
188
+ center, scale = statistics.affine()
189
+ self.anchors = anchors
190
+ # Unnormalized items and gripper widths, for policies with their own statistics.
191
+ self.raw = chunks
192
+ self.widths = widths
193
+ self.chunks = [((c - center) / scale).float() for c in chunks]
194
+ self.valid = valids
195
+ self.states = [statistics.state(w)[:, None].float() for w in widths]
196
+ self.images = images
197
+ self.slices = [(j, t) for j, chunk in enumerate(chunks) for t in range(len(chunk))]
198
+ self.num_traj = len(self.trajs)
199
+
200
+ def __len__(self):
201
+ return len(self.slices)
202
+
203
+ def __getitem__(self, index):
204
+ j, t = self.slices[index]
205
+ return {"observations": {"state": self.states[j][t], "rgb": self.images[j][t]},
206
+ "actions": self.chunks[j][t], "valid": self.valid[j][t]}
207
+
208
+ def describe(self):
209
+ return {"trajs": self.trajs, "samples": len(self), "statistics": json.loads(self.statistics.model_dump_json())}
210
+
211
+
212
+ def unnormalize(prediction, statistics: RealNormalization):
213
+ center, scale = statistics.affine()
214
+ return prediction.double() * scale.to(prediction.device) + center.to(prediction.device)
215
+
216
+
217
+ def item_errors(prediction, label):
218
+ """Per-item position (m), rotation (rad) and gripper (m) errors of unnormalized items."""
219
+ position = (prediction[..., :3] - label[..., :3]).norm(dim=-1) * TRANSLATION_SCALE
220
+ relative = sixd_to_matrix(prediction[..., 3:9]).transpose(-1, -2) @ sixd_to_matrix(label[..., 3:9])
221
+ trace = relative.diagonal(dim1=-2, dim2=-1).sum(-1)
222
+ rotation = torch.arccos(((trace - 1) / 2).clamp(-1, 1))
223
+ return position, rotation, (prediction[..., 9] - label[..., 9]).abs()
fair-comparison/extract-train-v1/code/lim/reference_act.py ADDED
@@ -0,0 +1,856 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ declared.chunk_bspline_knots,
105
+ )
106
+ if checkpoint.get("action_target_contract") != expected:
107
+ raise ValueError(
108
+ "Checkpoint contract does not match its anchor, pose or gripper supervision"
109
+ )
110
+
111
+
112
+ def source_provenance(config):
113
+ declared = json.loads(Path("round2/reference-source.json").read_text())
114
+ source = Path("third_party/ManiSkill/examples/baselines/act/train_rgbd.py")
115
+ if config.source.resolve() != source.resolve():
116
+ raise ValueError("Reference source must match the pinned official loader")
117
+ actual = {
118
+ p: hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in declared["sha256"]
119
+ }
120
+ if actual != declared["sha256"]:
121
+ raise ValueError("Official source differs from audited hashes")
122
+ return {"official_source_sha256": actual, "reference_commit": declared["commit"]}
123
+
124
+
125
+ class ACTArchitectureConfig(BaseModel, frozen=True):
126
+ model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
127
+ hidden_dim: PositiveInt = 256
128
+ """Official ACT transformer hidden width."""
129
+ dim_feedforward: PositiveInt = 512
130
+ """Official transformer feed-forward width."""
131
+ enc_layers: PositiveInt = 2
132
+ """Encoder layers in the official architecture."""
133
+ dec_layers: PositiveInt = 4
134
+ """Decoder layers in the official architecture."""
135
+
136
+
137
+ class ReferenceConfig(BaseModel, frozen=True):
138
+ model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
139
+ mode: Literal["witness", "evaluate", "profile"] = "witness"
140
+ """Environment witness, fixed-checkpoint evaluation, or simulator-free profile."""
141
+ source: Path = Path("third_party/ManiSkill/examples/baselines/act/train_rgbd.py")
142
+ """Pinned, unmodified official implementation containing Agent and preprocessing."""
143
+ checkpoint: Path | None = None
144
+ """Official final checkpoint; evaluation and profile load its ema_agent entry."""
145
+ output_dir: Path = Path("artifacts/round2/witness")
146
+ """New output directory, with raw episode or timing records."""
147
+ episodes: PositiveInt = 100
148
+ """Fixed number of complete evaluation episodes."""
149
+ num_envs: PositiveInt = 10
150
+ """CPU physics vector environments; episodes must be divisible by this count."""
151
+ seed_start: int = 50000
152
+ """Explicit, disjoint per-episode seed block."""
153
+ observations: Path | None = None
154
+ """Folder with saved raw RGB/proprioceptive inputs for profiling."""
155
+ iterations: PositiveInt = 500
156
+ """Measured warmed profile calls; 30 additional warmup calls precede these."""
157
+ demonstration_metadata: Path = Path(
158
+ "data/official-demos/StackCube-v1/motionplanning/trajectory.rgb.pd_ee_delta_pos.physx_cpu.json"
159
+ )
160
+ """Converted demonstration metadata supplying the evaluation sensor configuration."""
161
+ architecture: ACTArchitectureConfig = ACTArchitectureConfig()
162
+ """Explicit trained model shape; defaults preserve the Round2 small reference."""
163
+ policy: ACTPolicyConfig = ACTPolicyConfig()
164
+ """Trained architecture/input variant; must match checkpoint metadata."""
165
+ num_queries: PositiveInt = 30
166
+ """Actual trained decoder query count, including one for a single-target model;
167
+ native evaluation queries fresh observations each control step."""
168
+ video_seeds: tuple[int, ...] = ()
169
+ """Optional explicit scene seeds to record, including raw RGB and observer view."""
170
+ keypose_trace: bool = False
171
+ """Record read-only target, TCP error, and arrival-gate diagnostics for keyposes."""
172
+ control_mode: ACTControlMode = "pd_ee_delta_pos"
173
+ """Controller shared by the trained action labels and online environment."""
174
+ gripper_execution: GripperExecutionConfig = GripperExecutionConfig()
175
+ """Optional inference-only gripper intervention and chunk-level diagnostics."""
176
+
177
+ @model_validator(mode="after")
178
+ def validate_execution(self):
179
+ if self.keypose_trace and (
180
+ self.mode != "evaluate" or self.policy.keypose is None
181
+ ):
182
+ raise ValueError("Keypose diagnostics require keypose evaluation")
183
+ if self.policy.keypose is not None and (
184
+ self.mode != "evaluate" or self.control_mode != "pd_ee_delta_pose"
185
+ ):
186
+ raise ValueError(
187
+ "Keypose transport currently supports pose evaluation only"
188
+ )
189
+ if self.gripper_execution.active and (
190
+ self.mode != "evaluate"
191
+ or self.control_mode != "pd_ee_delta_pose"
192
+ or self.policy.method != "cvae"
193
+ or self.policy.action_encoding != "rotation6d"
194
+ or self.policy.keypose is not None
195
+ ):
196
+ raise ValueError(
197
+ "Gripper execution experiments require CVAE pose6D evaluation"
198
+ )
199
+ return self
200
+
201
+
202
+ def load_official(config):
203
+ source_provenance(config)
204
+ # The vendor's act/ is a namespace directory; its setup.find_packages()
205
+ # does not install it. Match direct train_rgbd.py execution's import root.
206
+ source_root = str(config.source.resolve().parent)
207
+ if source_root not in sys.path:
208
+ sys.path.insert(0, source_root)
209
+ # Use the file's importable name so forkserver CPU workers can reconstruct
210
+ # the official observation-wrapper class from the inherited sys.path.
211
+ spec = importlib.util.spec_from_file_location(config.source.stem, config.source)
212
+ module = importlib.util.module_from_spec(spec)
213
+ sys.modules[spec.name] = module
214
+ spec.loader.exec_module(module)
215
+ # Agent and Dataset reference the script's module-global args at runtime.
216
+ module.args = module.Args(
217
+ **config.architecture.model_dump(),
218
+ include_depth=False,
219
+ env_id="StackCube-v1",
220
+ control_mode=config.control_mode,
221
+ max_episode_steps=200,
222
+ sim_backend="physx_cpu",
223
+ temporal_agg=True,
224
+ num_queries=config.num_queries,
225
+ )
226
+ return module
227
+
228
+
229
+ class AuditConfig(BaseModel, frozen=True):
230
+ model_config = ConfigDict(
231
+ arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
232
+ )
233
+ env: Any
234
+ """Official environment, before visual preprocessing and CPU metric wrappers."""
235
+ snapshots: Path
236
+ """Raw policy-input snapshots, saved only from the first vector slot."""
237
+ stride: int
238
+ """Number of vector slots for deterministic snapshot ownership."""
239
+ seed_start: int
240
+ """First held-out seed, used only for snapshot ownership."""
241
+
242
+
243
+ class ReleasedSupportAudit(gym.Wrapper):
244
+ def __init__(self, config: AuditConfig):
245
+ super().__init__(config.env)
246
+ self.config = config
247
+ self.streak = 0
248
+ self.once = False
249
+ self.explicit_seed = None
250
+ self.step_index = 0
251
+
252
+ def snapshot(self, obs):
253
+ if (
254
+ self.explicit_seed is None
255
+ or (self.explicit_seed - self.config.seed_start) % self.config.stride
256
+ ):
257
+ return
258
+ if self.step_index not in (0, 10, 30, 70, 120, 199):
259
+ return
260
+ folder = self.config.snapshots
261
+ folder.mkdir(parents=True, exist_ok=True)
262
+ if len(list(folder.glob("*.pt"))) >= 12:
263
+ return
264
+
265
+ def cpu(value):
266
+ if isinstance(value, dict):
267
+ return {k: cpu(v) for k, v in value.items()}
268
+ return value.detach().cpu().clone() if torch.is_tensor(value) else value
269
+
270
+ torch.save(
271
+ cpu(obs), folder / f"seed{self.explicit_seed}_step{self.step_index}.pt"
272
+ )
273
+
274
+ def reset(self, **kwargs):
275
+ obs, info = self.env.reset(**kwargs)
276
+ self.streak, self.once, self.step_index = 0, False, 0
277
+ self.explicit_seed = kwargs.get("seed")
278
+ self.snapshot(obs)
279
+ return obs, info
280
+
281
+ def step(self, action):
282
+ obs, reward, terminated, truncated, info = self.env.step(action)
283
+ base = self.env.unwrapped
284
+ if base.spec.id != "StackCube-v1":
285
+ # The released-support audit is StackCube's cube-on-cube rule; other
286
+ # tasks only need the observation snapshots.
287
+ self.step_index += 1
288
+ self.snapshot(obs)
289
+ return obs, reward, terminated, truncated, info
290
+ source, target = base.cubeA, base.cubeB
291
+ support_force = base.scene.get_pairwise_contact_forces(source, target)
292
+ contact = 0.0
293
+ for link in base.agent.robot.get_links():
294
+ contact = max(
295
+ contact,
296
+ float(
297
+ torch.linalg.norm(
298
+ base.scene.get_pairwise_contact_forces(source, link), dim=-1
299
+ ).item()
300
+ ),
301
+ )
302
+ strict = (
303
+ abs(float(support_force[0, 2])) > 0.1
304
+ and float((source.pose.p - target.pose.p)[0, 2]) > 0.025
305
+ and bool(source.is_static(lin_thresh=1e-2, ang_thresh=0.5).item())
306
+ and contact < 0.01
307
+ and bool((base.agent.robot.get_qpos()[0, -2:] >= 0.035).all())
308
+ )
309
+ self.streak = self.streak + 1 if strict else 0
310
+ self.once = self.once or self.streak >= 20
311
+ info["audit_release_once"] = self.once
312
+ info["audit_release_at_end"] = self.streak >= 20
313
+ info["audit_robot_contact"] = contact
314
+ self.step_index += 1
315
+ self.snapshot(obs)
316
+ return obs, reward, terminated, truncated, info
317
+
318
+
319
+ def audit_wrapper(env, snapshots, stride, seed_start):
320
+ return ReleasedSupportAudit(
321
+ AuditConfig(env=env, snapshots=snapshots, stride=stride, seed_start=seed_start)
322
+ )
323
+
324
+
325
+ class RecorderConfig(BaseModel, frozen=True):
326
+ model_config = ConfigDict(
327
+ arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
328
+ )
329
+ env: Any
330
+ """Official CPU vector environment with SAME_STEP autoreset semantics."""
331
+ run: ReferenceConfig
332
+ """Declared seed block and output destination."""
333
+
334
+
335
+ class SeededRecorder:
336
+ """Record official metrics, explicitly seed each new batch, preserve ACT evaluation."""
337
+
338
+ def __init__(self, config: RecorderConfig):
339
+ self.config = config
340
+ self.rows = []
341
+ self.calls = 0
342
+ self.seed_batch = 0
343
+ self.model_queries = 0
344
+ self.previous_model_queries = 0
345
+ self.batch_steps = 0
346
+
347
+ def count_inference(self, module, inputs):
348
+ self.model_queries += 1
349
+
350
+ def __getattr__(self, name):
351
+ return getattr(self.config.env, name)
352
+
353
+ def reset(self):
354
+ start = self.config.run.seed_start + self.seed_batch * self.num_envs
355
+ return self.config.env.reset(seed=list(range(start, start + self.num_envs)))
356
+
357
+ def step(self, action):
358
+ obs, reward, terminated, truncated, info = self.config.env.step(action)
359
+ self.calls += 1
360
+ self.batch_steps += 1
361
+ if truncated.any():
362
+ assert truncated.all()
363
+ for slot, final in enumerate(info["final_info"]):
364
+ row = {k: np.asarray(v).item() for k, v in final["episode"].items()}
365
+ row.update(
366
+ seed=self.config.run.seed_start
367
+ + self.seed_batch * self.num_envs
368
+ + slot,
369
+ audit_release_once=bool(final["audit_release_once"]),
370
+ audit_release_at_end=bool(final["audit_release_at_end"]),
371
+ steps=self.batch_steps,
372
+ policy_calls=self.model_queries - self.previous_model_queries,
373
+ )
374
+ self.rows.append(row)
375
+ with (self.config.run.output_dir / "episodes.jsonl").open("a") as f:
376
+ f.write(json.dumps(row) + "\n")
377
+ print(
378
+ json.dumps(
379
+ {
380
+ "completed": len(self.rows),
381
+ "success_once": sum(r["success_once"] for r in self.rows),
382
+ "success_at_end": sum(r["success_at_end"] for r in self.rows),
383
+ }
384
+ ),
385
+ flush=True,
386
+ )
387
+ self.seed_batch += 1
388
+ self.previous_model_queries = self.model_queries
389
+ self.batch_steps = 0
390
+ if len(self.rows) < self.config.run.episodes:
391
+ # SAME_STEP already performed an unseeded reset. Replace that
392
+ # initial state before any policy action, keeping final_info intact.
393
+ obs, _ = self.reset()
394
+ return obs, reward, terminated, truncated, info
395
+
396
+
397
+ def create_env(module, config, count):
398
+ metadata = json.loads(config.demonstration_metadata.read_text())
399
+ info = metadata["env_info"]
400
+ if info["env_id"] not in TASKS:
401
+ raise ValueError("Demonstration metadata task mismatch")
402
+ sensor_configs = info["env_kwargs"]["sensor_configs"]
403
+ if info["env_kwargs"].get("control_mode") != config.control_mode:
404
+ raise ValueError("Demonstration metadata and evaluation controller differ")
405
+ if config.policy.method == "chunk_relative" and config.control_mode != (
406
+ "pd_ee_delta_pose"
407
+ if config.policy.action_encoding == "rotation6d"
408
+ else "pd_ee_delta_pos"
409
+ ):
410
+ raise ValueError(
411
+ "Chunk-relative action encoding and physical source controller disagree"
412
+ )
413
+ wrappers = [
414
+ partial(
415
+ audit_wrapper,
416
+ snapshots=config.output_dir / "raw_observations",
417
+ stride=count,
418
+ seed_start=config.seed_start,
419
+ ),
420
+ ]
421
+ if config.video_seeds:
422
+ from lim.policy_video import policy_video_wrapper
423
+
424
+ wrappers.append(
425
+ partial(
426
+ policy_video_wrapper,
427
+ output_dir=config.output_dir / "videos",
428
+ seeds=config.video_seeds,
429
+ label="keypose"
430
+ if config.policy.keypose is not None
431
+ else config.policy.method,
432
+ )
433
+ )
434
+ wrappers.append(partial(module.FlattenRGBDObservationWrapper, depth=False))
435
+ return module.make_eval_envs(
436
+ info["env_id"],
437
+ count,
438
+ "physx_cpu",
439
+ {
440
+ "control_mode": config.control_mode,
441
+ "reward_mode": "sparse",
442
+ "obs_mode": "rgb",
443
+ "render_mode": "rgb_array",
444
+ "max_episode_steps": 200,
445
+ "sensor_configs": sensor_configs,
446
+ },
447
+ None,
448
+ wrappers=wrappers,
449
+ )
450
+
451
+
452
+ def evaluate(config):
453
+ if config.episodes % config.num_envs:
454
+ raise ValueError("Episode count must be divisible by vector environment count")
455
+ config.output_dir.mkdir(parents=True, exist_ok=False)
456
+ module = load_official(config)
457
+ official_evaluate = module.evaluate
458
+ env = create_env(module, config, config.num_envs)
459
+ gripper_trace = None
460
+ keypose_trace = None
461
+ try:
462
+ ck, provenance = load_checkpoint(config.checkpoint)
463
+ check_policy_checkpoint(ck, config)
464
+ agent = build_policy(
465
+ module, env, module.args, config.policy, ck.get("normalization")
466
+ ).cuda()
467
+ agent.load_state_dict(ck["ema_agent"])
468
+ recorder = SeededRecorder(RecorderConfig(env=env, run=config))
469
+ query_hook = agent.model.register_forward_pre_hook(recorder.count_inference)
470
+ kwargs = {
471
+ "stats": ck["norm_stats"],
472
+ "num_queries": 1
473
+ if config.policy.keypose is not None
474
+ else config.num_queries,
475
+ "temporal_agg": True,
476
+ "max_timesteps": 200,
477
+ "device": torch.device("cuda"),
478
+ "sim_backend": "physx_cpu",
479
+ }
480
+ start = time.monotonic()
481
+ physical_env = recorder
482
+ if config.gripper_execution.active:
483
+ from lim.action_objective import BinaryGripperEnv, BinaryGripperEnvConfig
484
+ from lim.gripper_execution import (
485
+ GripperAgent,
486
+ GripperBoundaryConfig,
487
+ GripperDecisionEnv,
488
+ GripperPhysicalEnv,
489
+ GripperTrace,
490
+ GripperTraceConfig,
491
+ )
492
+
493
+ gripper_trace = GripperTrace(
494
+ GripperTraceConfig(
495
+ execution=config.gripper_execution,
496
+ output_dir=config.output_dir,
497
+ num_envs=config.num_envs,
498
+ horizon=config.num_queries,
499
+ seed_start=config.seed_start,
500
+ bce=config.policy.action_loss.binary_gripper,
501
+ )
502
+ )
503
+ physical_env = GripperPhysicalEnv(
504
+ GripperBoundaryConfig(
505
+ wrapped=recorder,
506
+ trace=gripper_trace,
507
+ )
508
+ )
509
+ if config.gripper_execution.binary and not gripper_trace.config.bce:
510
+ physical_env = BinaryGripperEnv(
511
+ BinaryGripperEnvConfig(env=physical_env)
512
+ )
513
+ evaluation_agent, evaluation_env = evaluation_transport(
514
+ agent, physical_env, config.policy
515
+ )
516
+ if config.keypose_trace:
517
+ from lim.keypose_trace import KeyposeTraceConfig, KeyposeTraceEnv
518
+
519
+ keypose_trace = KeyposeTraceEnv(
520
+ KeyposeTraceConfig(
521
+ env=evaluation_env,
522
+ path=config.output_dir / "keypose_trace.jsonl",
523
+ seed_start=config.seed_start,
524
+ )
525
+ )
526
+ evaluation_env = keypose_trace
527
+ if gripper_trace is not None:
528
+ evaluation_agent = GripperAgent(
529
+ GripperBoundaryConfig(
530
+ wrapped=evaluation_agent,
531
+ trace=gripper_trace,
532
+ )
533
+ )
534
+ evaluation_env = GripperDecisionEnv(
535
+ GripperBoundaryConfig(
536
+ wrapped=evaluation_env,
537
+ trace=gripper_trace,
538
+ )
539
+ )
540
+ metrics = official_evaluate(
541
+ config.episodes, evaluation_agent, evaluation_env, kwargs
542
+ )
543
+ query_hook.remove()
544
+ assert recorder.model_queries == recorder.calls
545
+ for name in ("success_once", "success_at_end"):
546
+ assert int(np.asarray(metrics[name]).sum()) == sum(
547
+ r[name] for r in recorder.rows
548
+ )
549
+ result = {
550
+ "provenance": provenance | source_provenance(config),
551
+ "sensor_configs": json.loads(config.demonstration_metadata.read_text())[
552
+ "env_info"
553
+ ]["env_kwargs"]["sensor_configs"],
554
+ "config": config.model_dump(mode="json"),
555
+ "episodes": len(recorder.rows),
556
+ "counts": {
557
+ key: sum(r[key] for r in recorder.rows)
558
+ for key in (
559
+ "success_once",
560
+ "success_at_end",
561
+ "audit_release_once",
562
+ "audit_release_at_end",
563
+ )
564
+ },
565
+ "policy_vector_calls": recorder.model_queries,
566
+ "environment_vector_steps": recorder.calls,
567
+ "expected_policy_vector_calls": config.episodes // config.num_envs * 200,
568
+ "feedback_hz": 20,
569
+ "parameters": sum(p.numel() for p in agent.parameters()),
570
+ "wall_s": time.monotonic() - start,
571
+ "gpu": torch.cuda.get_device_name(),
572
+ "checkpoint_rule": "official final update EMA; no test checkpoint selection",
573
+ }
574
+ if config.policy.keypose is not None:
575
+ result["action_execution"] = (
576
+ "Newest first query world keypose; no temporal averaging; observed TCP controller with arrival-gated continuous gripper. No oracle stages or object states."
577
+ )
578
+ if config.policy.action_loss.binary_gripper:
579
+ result["gripper_execution"] = evaluation_env.diagnostics()
580
+ if config.gripper_execution.aggregation == "latest":
581
+ result["gripper_execution"]["rule"] = (
582
+ "newest chunk first-step p(open); >=0.5 opens; no hysteresis"
583
+ )
584
+ if gripper_trace is not None:
585
+ result["gripper_intervention"] = gripper_trace.diagnostics()
586
+ (config.output_dir / "result.json").write_text(json.dumps(result, indent=2))
587
+ print("REFERENCE_EVAL_COMPLETE", json.dumps(result), flush=True)
588
+ finally:
589
+ if keypose_trace is not None:
590
+ keypose_trace.finish()
591
+ if gripper_trace is not None:
592
+ gripper_trace.close()
593
+ env.close()
594
+
595
+
596
+ def witness(config):
597
+ config.output_dir.mkdir(parents=True, exist_ok=True)
598
+ torch.manual_seed(0)
599
+ module = load_official(config)
600
+ env = create_env(module, config, 1)
601
+ try:
602
+ obs, _ = env.reset(seed=123456)
603
+ base = env.envs[0].unwrapped
604
+ agent = build_policy(module, env, module.args, config.policy).cuda()
605
+ state_shape, rgb_shape = list(obs["state"].shape), list(obs["rgb"].shape)
606
+ with torch.inference_mode():
607
+ pred = agent.get_action(
608
+ {k: torch.as_tensor(v, device="cuda") for k, v in obs.items()}
609
+ )
610
+ assert (
611
+ pred.shape
612
+ == (
613
+ 1,
614
+ config.num_queries,
615
+ encoded_dimension(
616
+ ACTION_DIMENSIONS[config.control_mode],
617
+ config.policy.action_encoding,
618
+ ),
619
+ )
620
+ and torch.isfinite(pred).all()
621
+ )
622
+ assert base.control_freq == 20
623
+ command = (
624
+ sixd_to_controller(pred[:, 0])
625
+ if config.policy.action_encoding == "rotation6d"
626
+ else pred[:, 0]
627
+ )
628
+ if config.policy.action_loss.binary_gripper:
629
+ _, execution_env = evaluation_transport(agent, env, config.policy)
630
+ execution_env.step(pred[:, 0].cpu().numpy())
631
+ else:
632
+ env.step(command.cpu().numpy())
633
+ result = {
634
+ "status": "PASS",
635
+ "actual_sensor_shader_packs": {
636
+ k: v.config.shader_pack for k, v in base._sensors.items()
637
+ },
638
+ "gymnasium": gym.__version__,
639
+ "torch": torch.__version__,
640
+ "control_hz": base.control_freq,
641
+ "control_mode": base.control_mode,
642
+ "sim_hz": base.sim_freq,
643
+ "robot": base.agent.uid,
644
+ "state_shape": state_shape,
645
+ "rgb_shape": rgb_shape,
646
+ "action_shape": list(pred.shape),
647
+ "controller_action_shape": list(command.shape),
648
+ "action_encoding": config.policy.action_encoding,
649
+ "parameters": sum(p.numel() for p in agent.parameters()),
650
+ "gpu": torch.cuda.get_device_name(),
651
+ }
652
+ (config.output_dir / "result.json").write_text(json.dumps(result, indent=2))
653
+ print("REFERENCE_WITNESS", json.dumps(result), flush=True)
654
+ finally:
655
+ env.close()
656
+
657
+
658
+ class ReplayConfig(BaseModel, frozen=True):
659
+ model_config = ConfigDict(
660
+ arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
661
+ )
662
+ module: Any
663
+ """Pinned official module, supplying the exact RGB observation transformation."""
664
+ observations: list
665
+ """Raw CPU camera and proprioceptive observations; no encoded visual features."""
666
+
667
+
668
+ class SensorReplay:
669
+ """Feed real raw inputs through official evaluate() without a physics environment."""
670
+
671
+ def __init__(self, config: ReplayConfig):
672
+ self.config = config
673
+ self.processor = SimpleNamespace(
674
+ include_rgb=True,
675
+ include_depth=False,
676
+ include_state=True,
677
+ transforms=config.module.T.Compose(
678
+ [config.module.T.Resize((224, 224), antialias=True)]
679
+ ),
680
+ )
681
+ example = self.prepare(0)
682
+ self.single_observation_space = gym.spaces.Dict(
683
+ {
684
+ "state": gym.spaces.Box(
685
+ -np.inf, np.inf, shape=example["state"].shape[1:], dtype=np.float32
686
+ ),
687
+ "rgb": gym.spaces.Box(
688
+ 0, 255, shape=example["rgb"].shape[1:], dtype=np.uint8
689
+ ),
690
+ }
691
+ )
692
+ action_dim = ACTION_DIMENSIONS[config.module.args.control_mode]
693
+ self.single_action_space = gym.spaces.Box(
694
+ -1, 1, (action_dim,), dtype=np.float32
695
+ )
696
+ self.action_space = gym.spaces.Box(-1, 1, (1, action_dim), dtype=np.float32)
697
+ self.num_envs = 1
698
+ self.calls = 0
699
+ self.started = None
700
+ self.rows = []
701
+
702
+ def prepare(self, index):
703
+ # The official transform pops top-level keys only; preserve the raw record.
704
+ raw = dict(self.config.observations[index % len(self.config.observations)])
705
+ return self.config.module.FlattenRGBDObservationWrapper.observation(
706
+ self.processor, raw
707
+ )
708
+
709
+ def next_observation(self):
710
+ torch.cuda.synchronize()
711
+ self.started = time.perf_counter()
712
+ return self.prepare(self.calls)
713
+
714
+ def reset(self):
715
+ return self.next_observation(), {}
716
+
717
+ def step(self, action):
718
+ torch.cuda.synchronize()
719
+ elapsed = (time.perf_counter() - self.started) * 1000
720
+ if not np.isfinite(action).all():
721
+ raise FloatingPointError("Nonfinite reference policy action")
722
+ self.rows.append(
723
+ {
724
+ "index": self.calls,
725
+ "total_ms": elapsed,
726
+ "sampled_process_bytes": process_gpu_memory(),
727
+ }
728
+ )
729
+ self.calls += 1
730
+ truncated = np.array([self.calls % 200 == 0])
731
+ # Required vector episode bookkeeping, deliberately containing no task score.
732
+ info = (
733
+ {"final_info": [{"episode": {"measurement_episode": self.calls // 200}}]}
734
+ if truncated[0]
735
+ else {}
736
+ )
737
+ return (
738
+ self.next_observation(),
739
+ np.array([0.0]),
740
+ np.array([False]),
741
+ truncated,
742
+ info,
743
+ )
744
+
745
+
746
+ def profile(config):
747
+ if config.checkpoint is None or config.observations is None:
748
+ raise ValueError("Profile requires checkpoint and raw observations")
749
+ config.output_dir.mkdir(parents=True, exist_ok=False)
750
+ module = load_official(config)
751
+ paths = sorted(config.observations.glob("*.pt"))
752
+ if not paths:
753
+ raise ValueError("No raw observations for profile")
754
+ raw_inputs = {p.name: p.read_bytes() for p in paths}
755
+ replay = SensorReplay(
756
+ ReplayConfig(
757
+ module=module,
758
+ observations=[
759
+ torch.load(io.BytesIO(raw), map_location="cpu", weights_only=False)
760
+ for raw in raw_inputs.values()
761
+ ],
762
+ )
763
+ )
764
+ checkpoint, provenance = load_checkpoint(config.checkpoint)
765
+ check_policy_checkpoint(checkpoint, config)
766
+ agent = build_policy(
767
+ module, replay, module.args, config.policy, checkpoint.get("normalization")
768
+ ).cuda()
769
+ agent.load_state_dict(checkpoint["ema_agent"])
770
+ pynvml.nvmlInit()
771
+ model_queries = 0
772
+
773
+ def count_query(module, inputs):
774
+ nonlocal model_queries
775
+ model_queries += 1
776
+
777
+ query_hook = agent.model.register_forward_pre_hook(count_query)
778
+ # Complete full 200-step official evaluator episodes. Measure exactly the
779
+ # declared 500 calls after 30 warmup; trailing padding calls are separate.
780
+ total_episodes = math.ceil((30 + config.iterations) / 200)
781
+ evaluation_agent, evaluation_env = evaluation_transport(
782
+ agent, replay, config.policy
783
+ )
784
+ module.evaluate(
785
+ total_episodes,
786
+ evaluation_agent,
787
+ evaluation_env,
788
+ {
789
+ "stats": checkpoint["norm_stats"],
790
+ "num_queries": config.num_queries,
791
+ "temporal_agg": True,
792
+ "max_timesteps": 200,
793
+ "device": torch.device("cuda"),
794
+ "sim_backend": "physx_cpu",
795
+ },
796
+ )
797
+ query_hook.remove()
798
+ assert model_queries == replay.calls
799
+ measured = replay.rows[30 : 30 + config.iterations]
800
+ assert len(measured) == config.iterations
801
+ timings = [row["total_ms"] for row in measured]
802
+ result = {
803
+ "provenance": provenance
804
+ | source_provenance(config)
805
+ | {
806
+ "raw_observations_sha256": {
807
+ name: hashlib.sha256(raw).hexdigest()
808
+ for name, raw in raw_inputs.items()
809
+ }
810
+ },
811
+ "config": config.model_dump(mode="json"),
812
+ "gpu": torch.cuda.get_device_name(),
813
+ "parameters": sum(p.numel() for p in agent.parameters()),
814
+ "raw_observations": len(paths),
815
+ "warmup_calls": 30,
816
+ "measured_calls": len(measured),
817
+ "total_official_evaluator_calls": replay.calls,
818
+ "actual_model_queries": model_queries,
819
+ "trailing_unmeasured_calls": replay.calls - 30 - len(measured),
820
+ "cold_ms": replay.rows[0]["total_ms"],
821
+ "latency_ms": {
822
+ str(p): float(np.percentile(timings, p)) for p in (50, 95, 99, 100)
823
+ },
824
+ "sampled_peak_process_bytes": max(
825
+ row["sampled_process_bytes"] for row in replay.rows
826
+ ),
827
+ "peak_allocated_bytes": torch.cuda.max_memory_allocated(),
828
+ "peak_reserved_bytes": torch.cuda.max_memory_reserved(),
829
+ "scope": PROFILE_SCOPE,
830
+ }
831
+ with (config.output_dir / "iterations.jsonl").open("w") as out:
832
+ for row in replay.rows:
833
+ out.write(
834
+ json.dumps(
835
+ row | {"measured": 30 <= row["index"] < 30 + config.iterations}
836
+ )
837
+ + "\n"
838
+ )
839
+ (config.output_dir / "result.json").write_text(json.dumps(result, indent=2))
840
+ print("REFERENCE_PROFILE_COMPLETE", json.dumps(result), flush=True)
841
+
842
+
843
+ def run(config: ReferenceConfig):
844
+ torch.set_num_threads(4)
845
+ if config.mode == "witness":
846
+ witness(config)
847
+ elif config.mode == "evaluate":
848
+ if config.checkpoint is None:
849
+ raise ValueError("Evaluation requires a checkpoint")
850
+ evaluate(config)
851
+ else:
852
+ profile(config)
853
+
854
+
855
+ if __name__ == "__main__":
856
+ run(CliApp.run(ReferenceConfig))
fair-comparison/extract-train-v1/code/lim/replay_pose.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/extract-train-v1/code/lim/rlinf_openpi.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Load RLinf's PyTorch pi0/pi0.5 network from the pinned third_party/RLinf checkout.
2
+
3
+ Only the network and its flow-matching loss are used. The package __init__ files
4
+ of rlinf, rlinf.models, rlinf.models.embodiment and rlinf.models.embodiment.openpi
5
+ import RLinf's scheduler, environments and Hydra configs, so they are replaced by
6
+ empty packages that point at the same directories. Every module the network
7
+ imports is checked against the pinned source record before anything is loaded.
8
+ """
9
+
10
+ import hashlib
11
+ import json
12
+ import sys
13
+ import types
14
+ from pathlib import Path
15
+
16
+ # Relative to the repository root, the working directory of every job (frozen stage
17
+ # code lives elsewhere, so __file__ cannot locate the checkout).
18
+ ROOT = Path(".")
19
+ SOURCE_RECORD = Path("experiments/fair-comparison/evidence/pi05/rlinf-source.json")
20
+ STUB_PACKAGES = (
21
+ "rlinf",
22
+ "rlinf.models",
23
+ "rlinf.models.embodiment",
24
+ "rlinf.models.embodiment.openpi",
25
+ )
26
+
27
+
28
+ def check_source(root=ROOT):
29
+ record = json.loads((root / SOURCE_RECORD).read_text())
30
+ for relative, expected in record["sha256"].items():
31
+ actual = hashlib.sha256((root / relative).read_bytes()).hexdigest()
32
+ if actual != expected:
33
+ raise ValueError(f"{relative} differs from RLinf {record['commit']}")
34
+ return record
35
+
36
+
37
+ def load(root=ROOT):
38
+ """Return RLinf's network namespace (Pi0, Pi0Config, Observation, ...)."""
39
+ record = check_source(root)
40
+ checkout = (root / "third_party/RLinf").resolve()
41
+ for name in STUB_PACKAGES:
42
+ existing = sys.modules.get(name)
43
+ if existing is not None:
44
+ if not getattr(existing, "__lim_stub__", False):
45
+ raise RuntimeError(f"{name} was imported from {existing.__file__}")
46
+ continue
47
+ package = types.ModuleType(name)
48
+ package.__path__ = [str(checkout / name.replace(".", "/"))]
49
+ package.__lim_stub__ = True
50
+ sys.modules[name] = package
51
+ from rlinf.models.embodiment.openpi import pi0, pi0_config
52
+ from rlinf.models.embodiment.openpi.modules import model, utils
53
+
54
+ return types.SimpleNamespace(
55
+ commit=record["commit"],
56
+ Pi0=pi0.Pi0,
57
+ Pi0Config=pi0_config.Pi0Config,
58
+ Observation=model.Observation,
59
+ preprocess_observation=model.preprocess_observation,
60
+ set_torch_compile=utils.set_torch_compile,
61
+ )
fair-comparison/extract-train-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()))