Archive code-task00-centre-pilot-v9 9d2a766809eb
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- PROVENANCE.jsonAdded+13
- README.mdAdded+7
- SHA256SUMSAdded+53
- payload/CODE_SHA256SUMSAdded+49
- payload/SHA256SUMSAdded+50
- payload/config/local_cases.jsonlAdded+5
- payload/config/official_info.jsonAdded+317
- payload/config/source_provenance.jsonAdded+92
- payload/env_centre.shAdded+8
- payload/env_eai.shAdded+12
- payload/experiments/__init__.pyAdded
- payload/experiments/radio_two_arm/__init__.pyAdded
- payload/experiments/radio_two_arm/motion.pyAdded+94
- payload/experiments/radio_two_arm/navigation.pyAdded+85
- payload/experiments/radio_two_arm/perception.pyAdded+78
- payload/experiments/radio_two_arm/policy.pyAdded+197
- payload/pipeline/__init__.pyAdded
- payload/pipeline/navigation.pyAdded+72
- payload/pipeline/sensors.pyAdded+102
- payload/recovery.sbatchAdded+19
- payload/scripts/__init__.pyAdded
- payload/scripts/kinematics.pyAdded+85
- payload/task00_recovery/__init__.pyAdded
- payload/task00_recovery/grasp_evidence.pyAdded+90
- payload/task00_recovery/recording.pyAdded+110
- payload/task00_recovery/run.pyAdded+118
- payload/task00_recovery/sim.pyAdded+202
- payload/task00_recovery/source.pyAdded+73
- payload/task00_recovery/student.pyAdded+43
- payload/task00_recovery/teacher.pyAdded+480
- payload/task00_recovery/vendor/__init__.pyAdded+1
- payload/task00_recovery/vendor/data/fork_category_states.jsonAdded+1524
- payload/task00_recovery/vendor/fork_serialization.pyAdded+522
- payload/task00_recovery/vendor/fork_state.pyAdded+232
- payload/tests/fixtures/holding_anchor.jsonAdded+158
- payload/tests/fixtures/right_terminal_993.jsonAdded+66
- payload/tests/test_contracts.pyAdded+104
- payload/tests/test_free_hand_clearance.pyAdded+30
- payload/tests/test_holding_anchor.pyAdded+42
- payload/tests/test_navigation_resolution.pyAdded+22
- payload/tests/test_pilot_resource_gate.pyAdded+24
- payload/tests/test_retry_recovery.pyAdded+70
- payload/tests/test_source_contract.pyAdded+23
- payload/tools/__init__.pyAdded
- payload/tools/build_cases.pyAdded+53
- payload/tools/centre_pilot.pyAdded+129
- payload/tools/download_sources.pyAdded+94
- payload/tools/driver.pyAdded+116
- payload/tools/export_lerobot.pyAdded+304
- payload/tools/merge_datasets.pyAdded+57
12345678910111213{ "artifact_id": "code-task00-centre-pilot-v9", "producer_recipe": "evaluations/2026-09-23_task00_centre_recovery_pilot", "source_machine": "centre", "source_path": "/media/david/HDD/runs/2026-09-23_task00_centre_recovery_pilot/code/v9", "tier": "code (inputs symlink to public B1k_Rollouts excluded)", "snapshot_at": "2026-09-24T19:14:13.956087+00:00", "files": 51, "bytes": 243222, "exclusions": [], "source_policy": "independent copy; original unchanged", "checkpoint_completion": "producer completed metadata and stable copied files; no restore test implied"}1234567# code-task00-centre-pilot-v9
Private fleet archive. Canonical recipe: evaluations/2026-09-23_task00_centre_recovery_pilot
Tier: code (inputs symlink to public B1k_Rollouts excluded)
Use the exact recorded revision and verify SHA256SUMS. This package is a snapshot, not a live directory mirror.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525379ea1b5fa17fff36368ffb91bdeb08ab8b65ec46781775dc42b8293c57fb72c2 PROVENANCE.jsonf1f5a0de2e7e215503bf946815468869ea11300c7fdaeced9f4e17ff424195eb README.md3fd6c3874e81ed9074d4b12e763ab822a8b9f511b5973c42be9ded05d056c744 payload/CODE_SHA256SUMS58b0ede673d693628dab32b08af2e064575e994ede797c7916bb9b1e3fb1b50c payload/SHA256SUMSf1713b098c2fde7e5bcb4fc217edd40a0db397f77500a5415b8c6e3d995a3a9a payload/config/local_cases.jsonl24c77f7a984bcee775e666203881a946b11a899f524fbc2405922b2109757874 payload/config/official_info.json5ef9e68461c3bb379ec178b613cd2e033b3f9a4b549163b1e5f6340d0ff6b43c payload/config/source_provenance.json5ef6140bb37df541691baba2333b718c602bf7e84713610f48e883dec4042852 payload/env_centre.sh59b8a77d51a6362100e42c20409bc439428c4be317526b9237323c8ffbe6a1c5 payload/env_eai.she3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 payload/experiments/__init__.pye3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 payload/experiments/radio_two_arm/__init__.py4d808ab3b65a9ff9a58ccb0c2abc6f52aca07ce52d9e8b4ed222052aed57adcc payload/experiments/radio_two_arm/motion.py73dc513d29dbfe6b6a7e9977c181e69404ad5071a06e2c624b792ca0b720bf17 payload/experiments/radio_two_arm/navigation.py41d62b088bce0cbd0a066fc00eaf3992e0bac2eca8f07adc428c2707a6057e6c payload/experiments/radio_two_arm/perception.py57ed3c4dc197f91c9b6ba7c1a015c85e9b2d848045233f61cc117ed381665ea7 payload/experiments/radio_two_arm/policy.pye3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 payload/pipeline/__init__.py41a91ba649b4a42c31bf9a53c78c96e4d77e0ac1d5be4d454b066b616e4c3eb4 payload/pipeline/navigation.py11115210d9d0d889631a482f6f15767107329f73618c3bb32079078ce3bfc6fa payload/pipeline/sensors.py83dc3f051446a2c570c2f1a90391eea4805447ebd718673cbcafe3a436cef21a payload/recovery.sbatche3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 payload/scripts/__init__.py7d513385e0b42c7241a5e35f3c5cd27adba0aa4b4493bdb14c1b8b71de2d13ac payload/scripts/kinematics.pye3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 payload/task00_recovery/__init__.py6a5123c3c1d3f62fb6a149006725b2a84070624436555f2e6b97cf9a01ec512f payload/task00_recovery/grasp_evidence.py2f9091d6266ecc72583df7f137d7e2c16915b46b5e3b450a26db5d55a134d34a payload/task00_recovery/recording.pyb0eb9cd62cf470d5267f2aab94fbdcde6d4e875662b27702d366b018f46d675a payload/task00_recovery/run.pycee6503c891bd46c65f9bda4b553402d37fbf7c715dd853898ad3a120f5a2bc5 payload/task00_recovery/sim.py62ed078a213a8b29969b82c4ff4c0307703ee2d66eb88fa0f625891a3d6833b9 payload/task00_recovery/source.py6b53461c796700f8d4af422acb158632d1b33d791a4b49a5d8011e9cc31fb8de payload/task00_recovery/student.pyab5b8764ec00241d8dabe817f77de771e9288b6f59e1bc24053bf12b3b0e5e8b payload/task00_recovery/teacher.py1642ccb8133a4ec23c4d7a312c08fd451a75959459bd88885a50dbe566fa1b9a payload/task00_recovery/vendor/__init__.py81bcf20ae5f0d3f156e0bdd0b0bfb6aa47da84548ec5cade820e0cd02bdced1a payload/task00_recovery/vendor/data/fork_category_states.json31a5b041c1f7fcb3c433cadd96e7b681aba3f77f2b2632702be89e53279ee9ad payload/task00_recovery/vendor/fork_serialization.pyfa41f225f194050a1a987a521d95554ccb8ec3ffeb792723a06a686da18d567a payload/task00_recovery/vendor/fork_state.pyb45e654043d5f107bd8ba3f660f58d8fabe918cca2b24195e573b4bf8bde2519 payload/tests/fixtures/holding_anchor.jsoncd2d05b9c7c1ace7aef66b198991ff55f0ce8195f53f8d33119a1fd9a8576438 payload/tests/fixtures/right_terminal_993.json8b98e77b4d77d34e4c189ae79506c971bb0abd3648bd398a3ffb7603008ba8c9 payload/tests/test_contracts.py3e3f5be63f2b6b78d758687c2f07bdde8c4217d78be451afdae41cb06b9371f8 payload/tests/test_free_hand_clearance.pyb2b885abd1e71f41f3cc847492bf93728613415dd64951b33452606bbf72d189 payload/tests/test_holding_anchor.py2e6483b322fabca4f5fa2484e4e167f34234c98739209a0160d038d39ddadc61 payload/tests/test_navigation_resolution.py3be7dc5db45c663af114275dbd53083b46b1d0bc8c44a55bc7621431c8d0738f payload/tests/test_pilot_resource_gate.py1b2b64b7886a678a4b41eabe50fb3b1d9efb44c88427cea4b8e8a986877402a6 payload/tests/test_retry_recovery.py52bb3da9d6db06c121b40882069fa6d674533f2a7f3dd97ebac17a3aa093a506 payload/tests/test_source_contract.pye3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 payload/tools/__init__.py7fec584304507bf2151d4d4f8021c6bd5861af73dd8d3122563bb6cb1a02547e payload/tools/build_cases.py7fd0e5473856b20b055133bbfa6251653d3be8767db956e32c77aa9d6acb37e7 payload/tools/centre_pilot.py91f4d19f7a2e4abe8c0b6a98628f4b75c6fde1489ba7a50dbd0ad6562d72741c payload/tools/download_sources.pyf91e8673b8e870b5155d985e72c90b3f8801c70da721094e1026efb660985968 payload/tools/driver.pyd5bbe66d0674c72c49db8760cd20e7383dffbe3d676b3606dae345b03208bb69 payload/tools/export_lerobot.pye1e565570ded5ee8da82dc1d94bf51e0e95a002c8f4a8e18abd29024f6ba2fa1 payload/tools/merge_datasets.py9484d1cf11a126ce4b467a53706c158eadcedce4e2b769040564efddd97e4a86 payload/tools/prepare_centre_pilot.py969389175929881ab0e92cf42645405c227bc0237ff57a3a609dbcb3de9227d3 payload/tools/preview.pyc7f240ce6a7f4f1efd4a6744a996551723d79a9ca86fb95634b14fc0770784ca payload/tools/progress.py0ec5bf703d60e641eb70df4e29b72a02b48ca0a17b541b5a96569d6c43d41e81 payload/tools/sim_entry.py12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849f1713b098c2fde7e5bcb4fc217edd40a0db397f77500a5415b8c6e3d995a3a9a config/local_cases.jsonl24c77f7a984bcee775e666203881a946b11a899f524fbc2405922b2109757874 config/official_info.json5ef9e68461c3bb379ec178b613cd2e033b3f9a4b549163b1e5f6340d0ff6b43c config/source_provenance.json5ef6140bb37df541691baba2333b718c602bf7e84713610f48e883dec4042852 env_centre.sh59b8a77d51a6362100e42c20409bc439428c4be317526b9237323c8ffbe6a1c5 env_eai.she3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 experiments/__init__.pye3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 experiments/radio_two_arm/__init__.py4d808ab3b65a9ff9a58ccb0c2abc6f52aca07ce52d9e8b4ed222052aed57adcc experiments/radio_two_arm/motion.py73dc513d29dbfe6b6a7e9977c181e69404ad5071a06e2c624b792ca0b720bf17 experiments/radio_two_arm/navigation.py41d62b088bce0cbd0a066fc00eaf3992e0bac2eca8f07adc428c2707a6057e6c experiments/radio_two_arm/perception.py57ed3c4dc197f91c9b6ba7c1a015c85e9b2d848045233f61cc117ed381665ea7 experiments/radio_two_arm/policy.pye3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 pipeline/__init__.py41a91ba649b4a42c31bf9a53c78c96e4d77e0ac1d5be4d454b066b616e4c3eb4 pipeline/navigation.py11115210d9d0d889631a482f6f15767107329f73618c3bb32079078ce3bfc6fa pipeline/sensors.py83dc3f051446a2c570c2f1a90391eea4805447ebd718673cbcafe3a436cef21a recovery.sbatche3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 scripts/__init__.py7d513385e0b42c7241a5e35f3c5cd27adba0aa4b4493bdb14c1b8b71de2d13ac scripts/kinematics.pye3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task00_recovery/__init__.py6a5123c3c1d3f62fb6a149006725b2a84070624436555f2e6b97cf9a01ec512f task00_recovery/grasp_evidence.py2f9091d6266ecc72583df7f137d7e2c16915b46b5e3b450a26db5d55a134d34a task00_recovery/recording.pyb0eb9cd62cf470d5267f2aab94fbdcde6d4e875662b27702d366b018f46d675a task00_recovery/run.pycee6503c891bd46c65f9bda4b553402d37fbf7c715dd853898ad3a120f5a2bc5 task00_recovery/sim.py62ed078a213a8b29969b82c4ff4c0307703ee2d66eb88fa0f625891a3d6833b9 task00_recovery/source.py6b53461c796700f8d4af422acb158632d1b33d791a4b49a5d8011e9cc31fb8de task00_recovery/student.pyab5b8764ec00241d8dabe817f77de771e9288b6f59e1bc24053bf12b3b0e5e8b task00_recovery/teacher.py1642ccb8133a4ec23c4d7a312c08fd451a75959459bd88885a50dbe566fa1b9a task00_recovery/vendor/__init__.py81bcf20ae5f0d3f156e0bdd0b0bfb6aa47da84548ec5cade820e0cd02bdced1a task00_recovery/vendor/data/fork_category_states.json31a5b041c1f7fcb3c433cadd96e7b681aba3f77f2b2632702be89e53279ee9ad task00_recovery/vendor/fork_serialization.pyfa41f225f194050a1a987a521d95554ccb8ec3ffeb792723a06a686da18d567a task00_recovery/vendor/fork_state.pyb45e654043d5f107bd8ba3f660f58d8fabe918cca2b24195e573b4bf8bde2519 tests/fixtures/holding_anchor.jsoncd2d05b9c7c1ace7aef66b198991ff55f0ce8195f53f8d33119a1fd9a8576438 tests/fixtures/right_terminal_993.json8b98e77b4d77d34e4c189ae79506c971bb0abd3648bd398a3ffb7603008ba8c9 tests/test_contracts.py3e3f5be63f2b6b78d758687c2f07bdde8c4217d78be451afdae41cb06b9371f8 tests/test_free_hand_clearance.pyb2b885abd1e71f41f3cc847492bf93728613415dd64951b33452606bbf72d189 tests/test_holding_anchor.py2e6483b322fabca4f5fa2484e4e167f34234c98739209a0160d038d39ddadc61 tests/test_navigation_resolution.py3be7dc5db45c663af114275dbd53083b46b1d0bc8c44a55bc7621431c8d0738f tests/test_pilot_resource_gate.py1b2b64b7886a678a4b41eabe50fb3b1d9efb44c88427cea4b8e8a986877402a6 tests/test_retry_recovery.py52bb3da9d6db06c121b40882069fa6d674533f2a7f3dd97ebac17a3aa093a506 tests/test_source_contract.pye3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 tools/__init__.py7fec584304507bf2151d4d4f8021c6bd5861af73dd8d3122563bb6cb1a02547e tools/build_cases.py7fd0e5473856b20b055133bbfa6251653d3be8767db956e32c77aa9d6acb37e7 tools/centre_pilot.py91f4d19f7a2e4abe8c0b6a98628f4b75c6fde1489ba7a50dbd0ad6562d72741c tools/download_sources.pyf91e8673b8e870b5155d985e72c90b3f8801c70da721094e1026efb660985968 tools/driver.pyd5bbe66d0674c72c49db8760cd20e7383dffbe3d676b3606dae345b03208bb69 tools/export_lerobot.pye1e565570ded5ee8da82dc1d94bf51e0e95a002c8f4a8e18abd29024f6ba2fa1 tools/merge_datasets.py9484d1cf11a126ce4b467a53706c158eadcedce4e2b769040564efddd97e4a86 tools/prepare_centre_pilot.py969389175929881ab0e92cf42645405c227bc0237ff57a3a609dbcb3de9227d3 tools/preview.pyc7f240ce6a7f4f1efd4a6744a996551723d79a9ca86fb95634b14fc0770784ca tools/progress.py0ec5bf703d60e641eb70df4e29b72a02b48ca0a17b541b5a96569d6c43d41e81 tools/sim_entry.py12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849503fd6c3874e81ed9074d4b12e763ab822a8b9f511b5973c42be9ded05d056c744 CODE_SHA256SUMSf1713b098c2fde7e5bcb4fc217edd40a0db397f77500a5415b8c6e3d995a3a9a config/local_cases.jsonl24c77f7a984bcee775e666203881a946b11a899f524fbc2405922b2109757874 config/official_info.json5ef9e68461c3bb379ec178b613cd2e033b3f9a4b549163b1e5f6340d0ff6b43c config/source_provenance.json5ef6140bb37df541691baba2333b718c602bf7e84713610f48e883dec4042852 env_centre.sh59b8a77d51a6362100e42c20409bc439428c4be317526b9237323c8ffbe6a1c5 env_eai.she3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 experiments/__init__.pye3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 experiments/radio_two_arm/__init__.py4d808ab3b65a9ff9a58ccb0c2abc6f52aca07ce52d9e8b4ed222052aed57adcc experiments/radio_two_arm/motion.py73dc513d29dbfe6b6a7e9977c181e69404ad5071a06e2c624b792ca0b720bf17 experiments/radio_two_arm/navigation.py41d62b088bce0cbd0a066fc00eaf3992e0bac2eca8f07adc428c2707a6057e6c experiments/radio_two_arm/perception.py57ed3c4dc197f91c9b6ba7c1a015c85e9b2d848045233f61cc117ed381665ea7 experiments/radio_two_arm/policy.pye3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 pipeline/__init__.py41a91ba649b4a42c31bf9a53c78c96e4d77e0ac1d5be4d454b066b616e4c3eb4 pipeline/navigation.py11115210d9d0d889631a482f6f15767107329f73618c3bb32079078ce3bfc6fa pipeline/sensors.py83dc3f051446a2c570c2f1a90391eea4805447ebd718673cbcafe3a436cef21a recovery.sbatche3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 scripts/__init__.py7d513385e0b42c7241a5e35f3c5cd27adba0aa4b4493bdb14c1b8b71de2d13ac scripts/kinematics.pye3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task00_recovery/__init__.py6a5123c3c1d3f62fb6a149006725b2a84070624436555f2e6b97cf9a01ec512f task00_recovery/grasp_evidence.py2f9091d6266ecc72583df7f137d7e2c16915b46b5e3b450a26db5d55a134d34a task00_recovery/recording.pyb0eb9cd62cf470d5267f2aab94fbdcde6d4e875662b27702d366b018f46d675a task00_recovery/run.pycee6503c891bd46c65f9bda4b553402d37fbf7c715dd853898ad3a120f5a2bc5 task00_recovery/sim.py62ed078a213a8b29969b82c4ff4c0307703ee2d66eb88fa0f625891a3d6833b9 task00_recovery/source.py6b53461c796700f8d4af422acb158632d1b33d791a4b49a5d8011e9cc31fb8de task00_recovery/student.pyab5b8764ec00241d8dabe817f77de771e9288b6f59e1bc24053bf12b3b0e5e8b task00_recovery/teacher.py1642ccb8133a4ec23c4d7a312c08fd451a75959459bd88885a50dbe566fa1b9a task00_recovery/vendor/__init__.py81bcf20ae5f0d3f156e0bdd0b0bfb6aa47da84548ec5cade820e0cd02bdced1a task00_recovery/vendor/data/fork_category_states.json31a5b041c1f7fcb3c433cadd96e7b681aba3f77f2b2632702be89e53279ee9ad task00_recovery/vendor/fork_serialization.pyfa41f225f194050a1a987a521d95554ccb8ec3ffeb792723a06a686da18d567a task00_recovery/vendor/fork_state.pyb45e654043d5f107bd8ba3f660f58d8fabe918cca2b24195e573b4bf8bde2519 tests/fixtures/holding_anchor.jsoncd2d05b9c7c1ace7aef66b198991ff55f0ce8195f53f8d33119a1fd9a8576438 tests/fixtures/right_terminal_993.json8b98e77b4d77d34e4c189ae79506c971bb0abd3648bd398a3ffb7603008ba8c9 tests/test_contracts.py3e3f5be63f2b6b78d758687c2f07bdde8c4217d78be451afdae41cb06b9371f8 tests/test_free_hand_clearance.pyb2b885abd1e71f41f3cc847492bf93728613415dd64951b33452606bbf72d189 tests/test_holding_anchor.py2e6483b322fabca4f5fa2484e4e167f34234c98739209a0160d038d39ddadc61 tests/test_navigation_resolution.py3be7dc5db45c663af114275dbd53083b46b1d0bc8c44a55bc7621431c8d0738f tests/test_pilot_resource_gate.py1b2b64b7886a678a4b41eabe50fb3b1d9efb44c88427cea4b8e8a986877402a6 tests/test_retry_recovery.py52bb3da9d6db06c121b40882069fa6d674533f2a7f3dd97ebac17a3aa093a506 tests/test_source_contract.pye3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 tools/__init__.py7fec584304507bf2151d4d4f8021c6bd5861af73dd8d3122563bb6cb1a02547e tools/build_cases.py7fd0e5473856b20b055133bbfa6251653d3be8767db956e32c77aa9d6acb37e7 tools/centre_pilot.py91f4d19f7a2e4abe8c0b6a98628f4b75c6fde1489ba7a50dbd0ad6562d72741c tools/download_sources.pyf91e8673b8e870b5155d985e72c90b3f8801c70da721094e1026efb660985968 tools/driver.pyd5bbe66d0674c72c49db8760cd20e7383dffbe3d676b3606dae345b03208bb69 tools/export_lerobot.pye1e565570ded5ee8da82dc1d94bf51e0e95a002c8f4a8e18abd29024f6ba2fa1 tools/merge_datasets.py9484d1cf11a126ce4b467a53706c158eadcedce4e2b769040564efddd97e4a86 tools/prepare_centre_pilot.py969389175929881ab0e92cf42645405c227bc0237ff57a3a609dbcb3de9227d3 tools/preview.pyc7f240ce6a7f4f1efd4a6744a996551723d79a9ca86fb95634b14fc0770784ca tools/progress.py0ec5bf703d60e641eb70df4e29b72a02b48ca0a17b541b5a96569d6c43d41e81 tools/sim_entry.py12345{"case_id": "episode_00003680_f000300", "episode_id": "00003680", "instance_id": 368, "frame": 300, "seed_rank": 0, "start_type": "judgement_seed", "path": "/home/eai/Downloads/gpt6_b1k/task00_turning_on_radio/failure_recovery/inputs/trajectories/task-0000/episode_00003680.hdf5", "meta": "/home/eai/Downloads/gpt6_b1k/task00_turning_on_radio/failure_recovery/inputs/meta/task-0000/episodes/episode_00003680.json", "diagnostic_only": false, "annotations": [{"span": [0, 510], "learn": null, "seed": 300, "skill_label": "pick up from", "object": "radio_89", "target": "coffee_table_koagbh_0", "arm": "right", "reason": "By f300 the approach has presented the upright tabletop radio to the free right arm; before a grasp is secured, the radio begins tipping by viewed f400 and loses table support at f497."}]}{"case_id": "episode_00003990_f004000", "episode_id": "00003990", "instance_id": 399, "frame": 4000, "seed_rank": 0, "start_type": "judgement_seed", "path": "/home/eai/Downloads/gpt6_b1k/task00_turning_on_radio/failure_recovery/inputs/trajectories/task-0000/episode_00003990.hdf5", "meta": "/home/eai/Downloads/gpt6_b1k/task00_turning_on_radio/failure_recovery/inputs/meta/task-0000/episodes/episode_00003990.json", "diagnostic_only": false, "annotations": [{"span": [1498, 4009], "learn": null, "seed": 4000, "skill_label": "press", "object": "radio_89", "target": "circular front control", "arm": "right", "reason": "The right hand had reacquired and lifted the radio by f4000, but the left contacted its rear/handle face and then withdrew without toggling it on."}]}{"case_id": "episode_00005200_f004299", "episode_id": "00005200", "instance_id": 520, "frame": 4299, "seed_rank": 0, "start_type": "judgement_seed", "path": "/home/eai/Downloads/gpt6_b1k/task00_turning_on_radio/failure_recovery/inputs/trajectories/task-0000/episode_00005200.hdf5", "meta": "/home/eai/Downloads/gpt6_b1k/task00_turning_on_radio/failure_recovery/inputs/meta/task-0000/episodes/episode_00005200.json", "diagnostic_only": false, "annotations": [{"span": [851, 4299], "learn": null, "seed": 4299, "skill_label": "press", "object": "radio_89", "target": "radio_89", "arm": "left", "reason": "At f4299 the right arm still holds and presents the radio and the left hand remains beside its control, but the center is not green and no ToggledOn transition occurred; this is the last in-row frame of continuing objective-directed manipulation."}]}{"case_id": "episode_00003680_f004299", "episode_id": "00003680", "instance_id": 368, "frame": 4299, "seed_rank": 1, "start_type": "judgement_seed", "path": "/home/eai/Downloads/gpt6_b1k/task00_turning_on_radio/failure_recovery/inputs/trajectories/task-0000/episode_00003680.hdf5", "meta": "/home/eai/Downloads/gpt6_b1k/task00_turning_on_radio/failure_recovery/inputs/meta/task-0000/episodes/episode_00003680.json", "diagnostic_only": false, "annotations": [{"span": [511, 4299], "learn": null, "seed": 4299, "skill_label": "pick up from", "object": "radio_89", "target": "floor", "arm": "left", "reason": "At f4299 the left gripper has reached and is closing on the fallen radio after the floor re-approach, but the episode ends with no logged grasp and no visible lift from the floor."}]}{"case_id": "episode_00003990_f004010", "episode_id": "00003990", "instance_id": 399, "frame": 4010, "seed_rank": 1, "start_type": "judgement_seed", "path": "/home/eai/Downloads/gpt6_b1k/task00_turning_on_radio/failure_recovery/inputs/trajectories/task-0000/episode_00003990.hdf5", "meta": "/home/eai/Downloads/gpt6_b1k/task00_turning_on_radio/failure_recovery/inputs/meta/task-0000/episodes/episode_00003990.json", "diagnostic_only": false, "annotations": [{"span": [4010, 4299], "learn": null, "seed": 4010, "skill_label": "press", "object": "radio_89", "target": "circular front control", "arm": "right", "reason": "At f4010 the right hand still securely held the radio after the failed contact, but the left hand was clear and no press attempt resumed through f4299."}]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317{ "codebase_version": "v3.0", "fps": 30, "features": { "action": { "dtype": "float32", "shape": [ 23 ], "names": [ "action" ] }, "next.reward": { "dtype": "float32", "shape": [ 1 ], "names": [ "reward" ] }, "next.terminated": { "dtype": "bool", "shape": [ 1 ], "names": [ "done" ] }, "next.truncated": { "dtype": "bool", "shape": [ 1 ], "names": [ "done" ] }, "observation.state": { "dtype": "float32", "shape": [ 61 ], "names": [ null ] }, "observation.robot2cam_pose.left_realsense_link_camera_0": { "dtype": "float32", "shape": [ 7 ], "names": null }, "observation.depth_linear.left_realsense_link_camera_0": { "dtype": "video", "shape": [ 480, 480, 1 ], "names": [ "height", "width", "channel" ], "info": { "video.height": 480, "video.width": 480, "video.codec": "hevc", "video.pix_fmt": "gray12le", "video.fps": 30, "video.channels": 1, "has_audio": false, "video.g": null, "video.crf": null, "video.preset": null, "video.fast_decode": null, "video.video_backend": "pyav", "video.extra_options": null, "video.depth_min": 0.01, "video.depth_max": 10.0, "video.shift": 3.5, "video.use_log": true, "is_depth_map": true, "depth_unit": "mm", "video.output_unit": "mm" } }, "observation.rgb.left_realsense_link_camera_0": { "dtype": "video", "shape": [ 480, 480, 3 ], "names": [ "height", "width", "channel" ], "info": { "is_depth_map": false, "video.height": 480, "video.width": 480, "video.codec": "hevc", "video.pix_fmt": "yuv420p", "video.fps": 30, "video.channels": 3, "has_audio": false, "video.g": 8, "video.crf": 30, "video.preset": null, "video.fast_decode": 0, "video.video_backend": "pyav", "video.extra_options": { "x265-params": "log-level=0:bframes=0" } } }, "observation.robot2cam_pose.right_realsense_link_camera_0": { "dtype": "float32", "shape": [ 7 ], "names": null }, "observation.depth_linear.right_realsense_link_camera_0": { "dtype": "video", "shape": [ 480, 480, 1 ], "names": [ "height", "width", "channel" ], "info": { "video.height": 480, "video.width": 480, "video.codec": "hevc", "video.pix_fmt": "gray12le", "video.fps": 30, "video.channels": 1, "has_audio": false, "video.g": null, "video.crf": null, "video.preset": null, "video.fast_decode": null, "video.video_backend": "pyav", "video.extra_options": null, "video.depth_min": 0.01, "video.depth_max": 10.0, "video.shift": 3.5, "video.use_log": true, "is_depth_map": true, "depth_unit": "mm", "video.output_unit": "mm" } }, "observation.rgb.right_realsense_link_camera_0": { "dtype": "video", "shape": [ 480, 480, 3 ], "names": [ "height", "width", "channel" ], "info": { "is_depth_map": false, "video.height": 480, "video.width": 480, "video.codec": "hevc", "video.pix_fmt": "yuv420p", "video.fps": 30, "video.channels": 3, "has_audio": false, "video.g": 8, "video.crf": 30, "video.preset": null, "video.fast_decode": 0, "video.video_backend": "pyav", "video.extra_options": { "x265-params": "log-level=0:bframes=0" } } }, "observation.robot2cam_pose.zed_link_camera_0": { "dtype": "float32", "shape": [ 7 ], "names": null }, "observation.depth_linear.zed_link_camera_0": { "dtype": "video", "shape": [ 720, 720, 1 ], "names": [ "height", "width", "channel" ], "info": { "video.height": 720, "video.width": 720, "video.codec": "hevc", "video.pix_fmt": "gray12le", "video.fps": 30, "video.channels": 1, "has_audio": false, "video.g": null, "video.crf": null, "video.preset": null, "video.fast_decode": null, "video.video_backend": "pyav", "video.extra_options": null, "video.depth_min": 0.01, "video.depth_max": 10.0, "video.shift": 3.5, "video.use_log": true, "is_depth_map": true, "depth_unit": "mm", "video.output_unit": "mm" } }, "observation.rgb.zed_link_camera_0": { "dtype": "video", "shape": [ 720, 720, 3 ], "names": [ "height", "width", "channel" ], "info": { "is_depth_map": false, "video.height": 720, "video.width": 720, "video.codec": "hevc", "video.pix_fmt": "yuv420p", "video.fps": 30, "video.channels": 3, "has_audio": false, "video.g": 8, "video.crf": 30, "video.preset": null, "video.fast_decode": 0, "video.video_backend": "pyav", "video.extra_options": { "x265-params": "log-level=0:bframes=0" } } }, "timestamp": { "dtype": "float32", "shape": [ 1 ], "names": null }, "frame_index": { "dtype": "int64", "shape": [ 1 ], "names": null }, "episode_index": { "dtype": "int64", "shape": [ 1 ], "names": null }, "index": { "dtype": "int64", "shape": [ 1 ], "names": null }, "task_index": { "dtype": "int64", "shape": [ 1 ], "names": null } }, "total_episodes": 20000, "total_frames": 210916774, "total_tasks": 100, "chunks_size": 1000, "data_files_size_in_mb": 100, "video_files_size_in_mb": 200, "data_path": "data/chunk-{chunk_index:03d}/file-{file_index:03d}.parquet", "video_path": "videos/{video_key}/chunk-{chunk_index:03d}/file-{file_index:03d}.mp4", "robot_type": "R1Pro", "splits": { "train": "0:20000" }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192[ { "source": "/home/eai/Downloads/gpt6_b1k/task01_picking_up_trash/centre_human_first_recovery/campaigns/vla_failure_recovery_20260918/snapshot/task01_recovery/source.py", "target": "task00_recovery/source.py", "sha256": "62ed078a213a8b29969b82c4ff4c0307703ee2d66eb88fa0f625891a3d6833b9" }, { "source": "/home/eai/Downloads/gpt6_b1k/task01_picking_up_trash/centre_human_first_recovery/campaigns/vla_failure_recovery_20260918/snapshot/task01_recovery/sim.py", "target": "task00_recovery/sim.py", "sha256": "16199dc291c06aa7daae34f6f5f180e9d3511faea501d313f6dd5c19695e67a9" }, { "source": "/home/eai/Downloads/gpt6_b1k/task01_picking_up_trash/centre_human_first_recovery/campaigns/vla_failure_recovery_20260918/snapshot/task01_recovery/recording.py", "target": "task00_recovery/recording.py", "sha256": "65423ea7b74625f6aed1c31f63d910fb50e0c593cd78092222e867043dc9648f" }, { "source": "/home/eai/Downloads/gpt6_b1k/task01_picking_up_trash/centre_human_first_recovery/campaigns/vla_failure_recovery_20260918/snapshot/task01_recovery/student.py", "target": "task00_recovery/student.py", "sha256": "6b53461c796700f8d4af422acb158632d1b33d791a4b49a5d8011e9cc31fb8de" }, { "source": "/home/eai/Downloads/gpt6_b1k/task01_picking_up_trash/centre_human_first_recovery/campaigns/vla_failure_recovery_20260918/snapshot/task01_recovery/grasp_evidence.py", "target": "task00_recovery/grasp_evidence.py", "sha256": "0d412ba059df9e5e26b3e1f20bfd8f6c50d3ac8e3707e388eb3c4caa75061197" }, { "source": "/home/eai/Downloads/gpt6_b1k/task01_picking_up_trash/centre_human_first_recovery/campaigns/vla_failure_recovery_20260918/snapshot/task01_recovery/vendor/__init__.py", "target": "task00_recovery/vendor/__init__.py", "sha256": "1642ccb8133a4ec23c4d7a312c08fd451a75959459bd88885a50dbe566fa1b9a" }, { "source": "/home/eai/Downloads/gpt6_b1k/task01_picking_up_trash/centre_human_first_recovery/campaigns/vla_failure_recovery_20260918/snapshot/task01_recovery/vendor/fork_state.py", "target": "task00_recovery/vendor/fork_state.py", "sha256": "fa41f225f194050a1a987a521d95554ccb8ec3ffeb792723a06a686da18d567a" }, { "source": "/home/eai/Downloads/gpt6_b1k/task01_picking_up_trash/centre_human_first_recovery/campaigns/vla_failure_recovery_20260918/snapshot/task01_recovery/vendor/fork_serialization.py", "target": "task00_recovery/vendor/fork_serialization.py", "sha256": "31a5b041c1f7fcb3c433cadd96e7b681aba3f77f2b2632702be89e53279ee9ad" }, { "source": "/home/eai/Downloads/gpt6_b1k/task01_picking_up_trash/centre_human_first_recovery/campaigns/vla_failure_recovery_20260918/snapshot/task01_recovery/vendor/data/fork_category_states.json", "target": "task00_recovery/vendor/data/fork_category_states.json", "sha256": "81bcf20ae5f0d3f156e0bdd0b0bfb6aa47da84548ec5cade820e0cd02bdced1a" }, { "source": "/home/eai/Downloads/gpt6_b1k/task00_turning_on_radio/code/frozen/candidate15/pipeline/sensors.py", "target": "pipeline/sensors.py", "sha256": "11115210d9d0d889631a482f6f15767107329f73618c3bb32079078ce3bfc6fa" }, { "source": "/home/eai/Downloads/gpt6_b1k/task00_turning_on_radio/code/frozen/candidate15/pipeline/navigation.py", "target": "pipeline/navigation.py", "sha256": "41a91ba649b4a42c31bf9a53c78c96e4d77e0ac1d5be4d454b066b616e4c3eb4" }, { "source": "/home/eai/Downloads/gpt6_b1k/task00_turning_on_radio/code/frozen/candidate15/scripts/kinematics.py", "target": "scripts/kinematics.py", "sha256": "3b1e4ba6f9e2f34edc14613809400e67e804d6f1b66bf8b464ae3dff7b152856" }, { "source": "/home/eai/Downloads/gpt6_b1k/task00_turning_on_radio/code/frozen/candidate15/experiments/radio_two_arm/policy.py", "target": "experiments/radio_two_arm/policy.py", "sha256": "746d40624847f752900fa1265b372d6187d3142ff5fc3d0718cdbb6e9370e177" }, { "source": "/home/eai/Downloads/gpt6_b1k/task00_turning_on_radio/code/frozen/candidate15/experiments/radio_two_arm/motion.py", "target": "experiments/radio_two_arm/motion.py", "sha256": "707211c2f5449e1e668638b07e318a3f3e4c63a9aa587c74004d99eb6bd533f2" }, { "source": "/home/eai/Downloads/gpt6_b1k/task00_turning_on_radio/code/frozen/candidate15/experiments/radio_two_arm/navigation.py", "target": "experiments/radio_two_arm/navigation.py", "sha256": "54a420672bc9421a4b40afc6c64e0998a058f419f75b6fb7874fe8600387bbe1" }, { "source": "/home/eai/Downloads/gpt6_b1k/task00_turning_on_radio/code/frozen/candidate15/experiments/radio_two_arm/perception.py", "target": "experiments/radio_two_arm/perception.py", "sha256": "41d62b088bce0cbd0a066fc00eaf3992e0bac2eca8f07adc428c2707a6057e6c" }, { "source": "/home/eai/Downloads/gpt6_b1k/task01_picking_up_trash/centre_human_first_recovery/campaigns/vla_failure_recovery_20260918/tools/export_lerobot.py", "target": "tools/export_lerobot.py", "sha256": "32700a2a5dfc03b1650bb90504385c56e43a631e07b78b2bbd11564d8979a49b" }, { "source": "/home/eai/Downloads/gpt6_b1k/task01_picking_up_trash/centre_human_first_recovery/campaigns/vla_failure_recovery_20260918/official_info.json", "target": "config/official_info.json", "sha256": "24c77f7a984bcee775e666203881a946b11a899f524fbc2405922b2109757874" }]12345678#!/usr/bin/env bashexport B1K_REPO="${B1K_REPO:-/media/david/HDD/gpt6_behavior_solution_task00/2026/official-v3.9.2}"export B1K_PYTHON="${B1K_PYTHON:-/home/david/anaconda3/envs/behavior/bin/python}"export OMNIGIBSON_DATA_PATH="${OMNIGIBSON_DATA_PATH:-/media/david/HDD/gpt6_behavior_solution_task00/2026/data-root}"export OMNIGIBSON_APPDATA_PATH="${OMNIGIBSON_APPDATA_PATH:-/media/david/HDD/cache/task00_centre_recovery_pilot/appdata}"source "$(dirname -- "${BASH_SOURCE[0]}")/env_eai.sh"export MKL_NUM_THREADS=1export RECOVERY_SIM_ENTRY="$RECOVERY_ROOT/tools/sim_entry.py"123456789101112#!/usr/bin/env bash# Source this file; the archived full-run package is never modified.export RECOVERY_ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"export B1K_REPO="${B1K_REPO:-/home/eai/code/b1k}"export B1K_PYTHON="${B1K_PYTHON:-/home/eai/miniconda3/envs/behavior-392dev/bin/python}"export OMNIGIBSON_DATA_PATH="${OMNIGIBSON_DATA_PATH:-$B1K_REPO/datasets}"export B1K_ROBOT_URDF="$OMNIGIBSON_DATA_PATH/omnigibson-robot-assets/models/r1pro/urdf/r1pro_with_meta_links.urdf"export OMNIGIBSON_APPDATA_PATH="${OMNIGIBSON_APPDATA_PATH:-$RECOVERY_ROOT/cache/appdata}"export OMNIGIBSON_HEADLESS=1 OMNI_KIT_ACCEPT_EULA=YESexport PYTHONPATH="$RECOVERY_ROOT:$B1K_REPO/OmniGibson:$B1K_REPO/bddl3:$B1K_REPO/joylo"export PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=2 OPENBLAS_NUM_THREADS=1unset ISAAC_PATH EXP_PATH CARB_APP_PATH12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394"""Small bounded IK problems over measured robot joints and static URDF."""import timeimport numpy as npfrom scipy.optimize import least_squaresfrom scipy.spatial.transform import Rotation
def predicted_joints(s, action): """Kinematic planning state, not a simulator state or predicted image.""" from pipeline.sensors import Sensors raw = dict(s.raw) key = next(k for k in raw if k.endswith('::proprio')) p = raw[key] = s.p.copy() p[53:57], p[3:10], p[28:35] = action[3:7], action[7:14], action[15:22] result = Sensors(raw, s.kin) for side, index in [('left', 17), ('right', 42)]: tf = s.kin.pose(side+'_eef_link', result.positions) p[index:index+3] = tf[:3, 3] p[index+3:index+7] = Rotation.from_matrix(tf[:3, :3]).as_quat() return Sensors(raw, s.kin)
def solve(s, arm, xyz, quat, preserve_other=False, fixed_joints=(), other_pose=None): arms = ['left', 'right'] if preserve_other else [arm] names = ([f'torso_joint{i}' for i in range(1, 5)] + [f'{side}_arm_joint{i}' for side in arms for i in range(1, 8)]) initial = np.array([s.positions[n] for n in names]) lookup = {v[0]: v for v in s.kin.joints.values()} lo, hi = np.array([lookup[n][-1] for n in names]).T # Contact loads can push a measured joint slightly beyond its URDF limit. # Center retry windows on the closest legal command, never expand the limits. bounded_initial = np.clip(initial, lo, hi) torso_window = .4 if np.asarray(xyz)[2] < .30 else .12 lo[:4] = np.maximum(lo[:4], bounded_initial[:4]-torso_window) hi[:4] = np.minimum(hi[:4], bounded_initial[:4]+torso_window) for i, name in enumerate(names): if name in fixed_joints: lo[i] = max(lo[i], bounded_initial[i]-.002) hi[i] = min(hi[i], bounded_initial[i]+.002) targets = {side: s.kin.pose(side+'_eef_link', s.positions) for side in arms} if other_pose is not None: if not preserve_other: raise ValueError('A holding pose requires preserve_other') other_pose = np.asarray(other_pose, dtype=float) if other_pose.shape != (4, 4) or not np.isfinite(other_pose).all(): raise ValueError('Invalid holding pose') targets['right' if arm == 'left' else 'left'] = other_pose.copy() targets[arm][:3, 3] = xyz targets[arm][:3, :3] = Rotation.from_quat(quat).as_matrix()
def errors(q): positions = {**s.positions, **dict(zip(names, q))} out = [] for side in arms: pose = s.kin.pose(side+'_eef_link', positions) out.append((pose[:3, 3]-targets[side][:3, 3], Rotation.from_matrix(targets[side][:3, :3].T@pose[:3, :3]).as_rotvec())) return out
def residual(q): terms = [] for side, (dp, dr) in zip(arms, errors(q)): weight = 1 if side == arm else 2 terms.extend([weight*dp, weight*.2*dr]) terms.append(.002*(q-initial)) if not preserve_other: terms.append(.03*(q[:4]-initial[:4])) return np.concatenate(terms)
deadline = time.monotonic() + 6.0 original_residual = residual def residual(q): if time.monotonic() > deadline: raise RuntimeError('IK solve time budget exhausted') return original_residual(q)
rng = np.random.default_rng(0) best = None for i in range(6): seed = initial if i == 0 else initial+rng.normal(0, .3, size=len(initial)) r = least_squares(residual, np.clip(seed, lo+1e-6, hi-1e-6), bounds=(lo, hi), max_nfev=250) if best is None or np.linalg.norm(residual(r.x)) < np.linalg.norm(residual(best.x)): best = r if all(np.linalg.norm(dp) < .004 and np.linalg.norm(dr) < .05 for dp, dr in errors(r.x)): break err = [[float(np.linalg.norm(dp)), float(np.linalg.norm(dr))] for dp, dr in errors(best.x)] if any(dp > .008 or dr > .10 for dp, dr in err): raise RuntimeError(f'IK infeasible {arm} {np.round(xyz, 3).tolist()}: {err}') action = s.hold() action[3:7] = best.x[:4] for i, side in enumerate(arms): action[7:14] = best.x[4+7*i:11+7*i] if side == 'left' else action[7:14] action[15:22] = best.x[4+7*i:11+7*i] if side == 'right' else action[15:22] return action, err12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""Choose radio approach poses around depth-observed furniture."""import numpy as npfrom pipeline.navigation import Gridfrom pipeline.sensors import planar, wrapfrom experiments.radio_two_arm.perception import radiofrom experiments.radio_two_arm.motion import solve, predicted_joints
def direct_path_blocked(obs, delta): """Furniture across the base path, excluding the arm's final reaching space.""" length = np.linalg.norm(delta) if length < .25: return False direction = delta/length xyz = obs.cloud()[::5, ::5].reshape(-1, 3) mask = (np.isfinite(xyz).all(1) & (xyz[:, 2] > .29) & (xyz[:, 2] < .85) & (np.linalg.norm(xyz[:, :2], axis=1) > .55)) points = xyz[mask, :2] along = points@direction side = np.linalg.norm(points-along[:, None]*direction, axis=1) return np.count_nonzero((along > .25) & (along < length-.05) & (side < .22)) >= 30
def planned_approach(p, detected): target_world = p.odom.world(detected['handle']) goal = None for _ in range(85): p.grid.observe(p.obs, p.odom) detected = radio(p.obs) if detected is not None: target_world = .5*target_world+.5*p.odom.world(detected['handle']) if np.linalg.norm(detected['handle'][:2]-[.82, .15]) < .045: return detected if np.linalg.norm(detected['handle'][:2]-[.82, .15]) < .16: angle = detected['angle'] quat = [-np.sin(angle/2), np.cos(angle/2), 0, 0] try: above, _ = solve(p.obs, 'left', detected['handle']+[-.055, 0, .18], quat) solve(predicted_joints(p.obs, above), 'left', detected['handle']+[0, 0, -.02], quat) except RuntimeError: pass else: p.event('approach_reachable', xyz=detected['handle'].tolist()) return detected planned = choose_goal(p.grid, p.odom.pose, target_world, goal) if planned is None: raise RuntimeError('No obstacle-free radio approach in observed map') goal, route = planned waypoint = next((q for q in route if np.linalg.norm(q-p.odom.pose[:2]) > .10), goal[:2]) delta_world = waypoint-p.odom.pose[:2] c, s = np.cos(p.odom.pose[2]), np.sin(p.odom.pose[2]) delta = np.array([[c, s], [-s, c]])@delta_world velocity = np.clip(delta*1.5, -.3, .3) if np.linalg.norm(delta) > .04 and np.linalg.norm(velocity) < .10: velocity *= .10/max(np.linalg.norm(velocity), 1e-6) local_object = p.odom.local(target_world) heading = (p.odom.pose[2]+np.arctan2(local_object[1], local_object[0])-.18 if np.linalg.norm(goal[:2]-p.odom.pose[:2]) > .12 else goal[2]) angular = np.clip(1.5*wrap(heading-p.odom.pose[2]), -.5, .5) p.event('navigation_waypoint', estimated_goal=goal.tolist(), waypoint=waypoint.tolist()) yield from p.drive([*velocity, angular], 12) raise RuntimeError('Planned approach did not converge')
def choose_goal(grid, start, point, previous=None, reaches=(.82, .94), lateral=.15): options = [] for angle, reach in ((a, r) for a in np.arange(24)*np.pi/12 for r in reaches): heading = wrap(start[2]+angle) goal = np.r_[point[:2]-planar([0, 0, heading])[:2, :2]@np.array([reach, lateral]), heading] cost = np.linalg.norm(goal[:2]-start[:2])+.08*abs(wrap(heading-start[2])) if previous is not None: cost += .2*np.linalg.norm(goal[:2]-previous[:2]) options.append((cost, goal)) best = None for estimate, goal in sorted(options, key=lambda v: v[0]): if best is not None and estimate > best[0]+.3: break route = grid.route(start[:2], goal[:2]) if route is None: continue points = np.vstack([start[:2], route]) cost = np.linalg.norm(np.diff(points, axis=0), axis=1).sum()+.08*abs(wrap(goal[2]-start[2])) if best is None or cost < best[0]: best = (cost, goal, route) return None if best is None else best[1:]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778"""Radio geometry from RGBD only; no learned model or simulator object state."""import cv2import numpy as np
def red(rgb): a = rgb.astype(float) return (a[..., 0] > 65) & (a[..., 0] > 2.5*a[..., 1]) & (a[..., 0] > 2.5*a[..., 2])
def radio(s): cloud = s.cloud() mask = (red(s.get('zed', 'rgb')) & np.isfinite(cloud).all(2) & (cloud[..., 2] > .35) & (cloud[..., 2] < 1.05) & (cloud[..., 0] > .25) & (cloud[..., 0] < 3)) n, labels, stats, _ = cv2.connectedComponentsWithStats(mask.astype('uint8')) candidates = [i for i in range(1, n) if stats[i, 4] >= 35] if not candidates: return None valid = [] for i in candidates: center = np.median(cloud[labels == i], axis=0) points = cloud[mask & (np.linalg.norm(cloud-center, axis=2) < .32)] bounds = np.percentile(points, [3, 97], axis=0) extent = bounds[1]-bounds[0] # Reject broad surfaces / cropped wall regions, not just red pixels. if not .10 < extent[2] < .32 or np.max(extent[:2]) > .42 or bounds[1, 2] > 1.02: continue valid.append((stats[i, 4], center, points)) if not valid: return None _, center, points = max(valid, key=lambda item: item[0]) top = float(np.percentile(points[:, 2], 97)) handle = points[points[:, 2] > top-.012] if len(handle) < 15: return None h = np.median(handle, axis=0) _, vectors = np.linalg.eigh(np.cov(handle[:, :2].T)) axis = vectors[:, -1] if axis[0] < 0: axis = -axis angle = float(np.arctan2(axis[1], axis[0])) return {'center': center, 'handle': h, 'angle': angle, 'top': top, 'points': len(points), 'handle_points': len(handle)}
def button(s, camera, near): rgb = s.get(camera, 'rgb')[..., :3] mask = red(rgb) n, labels, stats, centers = cv2.connectedComponentsWithStats(mask.astype('uint8')) cloud = s.cloud(camera) results = [] for i in range(1, n): x, y, w, h, area = stats[i] if area < 25 or not .55 < w/max(h, 1) < 1.8 or area/(w*h) < .42: continue pts = cloud[labels == i] pts = pts[np.isfinite(pts).all(1)] if len(pts) < 20: continue xyz = np.median(pts, axis=0) if np.linalg.norm(xyz-near) > .32: continue if np.max(np.ptp(np.percentile(pts, [10, 90], axis=0), axis=0)) > .07: continue u, v = centers[i] theta = np.linspace(0, 2*np.pi, 36, endpoint=False) us = np.rint(u+np.cos(theta)*w*.85).astype(int) vs = np.rint(v+np.sin(theta)*h*.85).astype(int) valid = (us >= 0) & (us < rgb.shape[1]) & (vs >= 0) & (vs < rgb.shape[0]) if valid.sum() < 25: continue ring = rgb[vs[valid], us[valid]].astype(float) dark = float(np.mean(ring.max(1) < 105)) if dark < .6: continue results.append((dark, area, xyz)) return None if not results else max(results, key=lambda r: (r[0], r[1]))[2]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197"""Model-free two-arm radio state machine. Sensor-derived development policy."""import jsonimport numpy as npfrom scipy.spatial.transform import Rotationfrom pipeline.sensors import Sensors, Odometryfrom experiments.radio_two_arm.navigation import Grid, direct_path_blocked, planned_approachfrom scripts.kinematics import Kinematicsfrom experiments.radio_two_arm.perception import radio, buttonfrom experiments.radio_two_arm.motion import solve
class RadioPolicy: def __init__(self, events): self.events = events self.reset()
def reset(self): self.kin = Kinematics() self.odom = Odometry() self.grid = Grid() self.steps = 0 self.phase = 'start' self.grippers = [1, 1] self.generator = None self.snapshot_requested = True
def event(self, name, **values): self.events.write(json.dumps(dict(event=name, step=self.steps, phase=self.phase, **values))+'\n')
def hold(self): a = self.obs.hold() a[[14, 22]] = self.grippers return a
def wait(self, steps): a = self.hold() for _ in range(steps): yield a.copy()
def drive(self, velocity, steps): a = self.hold() a[:3] = velocity for _ in range(steps): yield a.copy() yield from self.wait(4)
def solve_motion(self, arm, xyz, quat, preserve=False, fixed_joints=()): return solve(self.obs, arm, xyz, quat, preserve, fixed_joints)
def move(self, arm, xyz, quat, steps=25, preserve=False, fixed_joints=(), retry=True): xyz = np.asarray(xyz) start = self.hold() target, err = self.solve_motion(arm, xyz, quat, preserve, fixed_joints) target[[14, 22]] = self.grippers self.event('motion_target', arm=arm, xyz=xyz.tolist(), quat=list(quat), preserve_other=preserve, ik_errors=err) for i in range(steps): a = start+(target-start)*((i+1)/steps) a[[14, 22]] = self.grippers yield a for _ in range(4): yield target.copy() actual = self.obs.eef(arm) error = float(np.linalg.norm(actual[:3]-xyz)) self.event('motion_result', arm=arm, position_error=error) self.snapshot_requested = True if error > .028: names = ([f'torso_joint{i}' for i in range(1, 5)] + [f'left_arm_joint{i}' for i in range(1, 8)] + [f'right_arm_joint{i}' for i in range(1, 8)]) commanded = np.r_[target[3:7], target[7:14], target[15:22]] stalled = [name for name, desired in zip(names, commanded) if abs(desired-self.obs.positions[name]) > .04] if retry and stalled: self.event('motion_retry', fixed_joints=stalled, error_m=error) yield from self.move(arm, xyz, quat, steps, preserve, stalled, False) return raise RuntimeError(f'{arm} execution blocked: {error:.3f}m')
def run(self): self.phase = 'scan' detected = None for _ in range(32): detected = radio(self.obs) if detected is not None: break yield from self.drive([0, 0, .65], 15) if detected is None: raise RuntimeError('Radio not found in RGBD scan') self.phase = 'approach' approach_history = [] for _ in range(45): detected = radio(self.obs) if detected is None: raise RuntimeError('Lost radio during approach') bearing = float(np.arctan2(detected['handle'][1], detected['handle'][0])) if abs(bearing-.18) > .3: approach_history.clear() yield from self.drive([0, 0, np.clip(bearing-.18, -.6, .6)], 12) continue delta = detected['handle'][:2]-[.82, .15] if direct_path_blocked(self.obs, delta): self.event('direct_path_blocked', recovery='depth_grid_detour') detected = yield from planned_approach(self, detected) break approach_history.append(detected['handle'][:2].copy()) if np.linalg.norm(delta) < .03: break if (np.linalg.norm(delta) < .045 and len(approach_history) >= 4 and np.linalg.norm(approach_history[-1]-approach_history[-4]) < .003): self.event('approach_near_target_stall', residual_m=float(np.linalg.norm(delta))) break # Small view-relative moves; never navigate from simulator positions. velocity = np.clip(delta*1.4, -.4, .4) yield from self.drive([*velocity, 0], 12) else: raise RuntimeError('Approach did not converge') handle = detected['handle'].copy() theta = detected['angle'] quat = [-np.sin(theta/2), np.cos(theta/2), 0, 0] self.event('handle_estimate', xyz=handle.tolist(), angle=theta) self.phase = 'grasp' yield from self.move('left', handle+[-.055, 0, .18], quat, 35) yield from self.move('left', handle+[0, 0, -.02], quat) self.grippers[0] = -1 yield from self.wait(18) self.phase = 'verify_grasp' yield from self.move('left', self.obs.eef('left')[:3]+[0, 0, .115], quat) raised = radio(self.obs) if raised is None or raised['top']-handle[2] < .065: raise RuntimeError('Radio did not rise with left hand') self.event('grasp_verified', observed_rise=float(raised['top']-handle[2])) self.phase = 'expose_button' yield from self.move('left', [.70, .15, .86], [-.7071, .7071, 0, 0], 35) self.grippers[1] = -1 yield from self.move('right', [.52, -.10, .80], [-.183, .683, .183, .683], 35, preserve=True) near = self.obs.eef('left')[:3]+[-.075, -.03, -.11] target = button(self.obs, 'zed', near) if target is None: target = button(self.obs, 'right_realsense', near) if target is None: self.phase = 'inspect_other_face' self.event('button_not_visible', recovery='rotate_held_radio_half_turn') yield from self.move('left', [.70, .15, .86], [0, 1, 0, 0], 35, preserve=True) yield from self.move('left', [.60, .05, .86], [.7071, .7071, 0, 0], 35, preserve=True) near = self.obs.eef('left')[:3]+[.025, 0, -.11] target = button(self.obs, 'zed', near) if target is None: target = button(self.obs, 'right_realsense', near) if target is None: raise RuntimeError('Button not visible after inspecting both radio faces') self.event('button_estimate', camera='head_or_right_wrist', xyz=target.tolist()) quat = [-.183, .683, .183, .683] self.phase = 'align_press' try: solve(self.obs, 'right', target+[-.065, -.055, .006], quat, True) except RuntimeError as exc: # Move the held object into a reachable workspace, based on the # observed button rather than an instance-specific object pose. self.phase = 'recenter_radio' center = np.array([.55, .0, .80]) delta = center-target self.event('press_reach_recovery', reason=str(exc), shift=delta.tolist()) left = self.obs.eef('left').copy() yield from self.move('left', left[:3]+delta, left[3:], 40, preserve=True) target = button(self.obs, 'zed', center) if target is None: target = button(self.obs, 'right_realsense', center) if target is None: raise RuntimeError('Button not visible after recentering held radio') self.event('button_estimate', camera='head_or_right_wrist', xyz=target.tolist()) self.phase = 'align_press' yield from self.move('right', target+[-.065, -.055, .006], quat, preserve=True) target = button(self.obs, 'right_realsense', target) if target is None: raise RuntimeError('Button could not be reacquired in right wrist') self.event('button_estimate', camera='right_realsense', xyz=target.tolist()) self.phase = 'press' for offset in [-.013, -.007, 0, .005]: yield from self.move('right', target+[offset, -.005, .001], quat, 25, preserve=True) yield from self.wait(12) raise RuntimeError('Press sequence exhausted without episode termination')
def predict(self, raw): self.obs = Sensors(raw, self.kin) self.odom.update(self.obs.p) self.steps += 1 if self.generator is None: self.generator = self.run() try: return np.asarray(next(self.generator), dtype=np.float32) except (RuntimeError, StopIteration) as exc: if self.phase != 'failure_hold': self.event('failure', reason=str(exc)) self.phase = 'failure_hold' self.generator = iter(()) return self.hold()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""Small depth-derived occupancy grid and A* for local room navigation."""import heapqimport numpy as npfrom scipy.ndimage import binary_dilationfrom pipeline.sensors import planar,wrap
def object_approach(grid,start,point,yaw,attempt=0): """Choose a reachable viewpoint around a detected object using the observed map.""" angles=(0.,np.pi/4,-np.pi/4,np.pi/2,-np.pi/2,3*np.pi/4,-3*np.pi/4,np.pi) # A perception retry needs a different view even when the old route was free. offset=min(max(int(attempt),0),len(angles)-1) angles=angles[offset:]+angles[:offset] for reach in (.72,.62,.82): for angle in angles: heading=wrap(yaw+angle) goal=np.r_[np.asarray(point)[:2]-planar([0,0,heading])[:2,:2]@np.array([reach,-.25]),heading] if grid.route(np.asarray(start)[:2],goal[:2]) is not None: return goal return None
class Grid: def __init__(self,resolution=.08,size=180): self.resolution=resolution self.size=size self.occupied=np.zeros((size,size),bool)
def cell(self,xy): return np.round(np.asarray(xy)/self.resolution+self.size/2).astype(int)
def xy(self,cell): return (np.asarray(cell)-self.size/2)*self.resolution
def observe(self,obs,odom): xyz=obs.cloud()[::5,::5].reshape(-1,3) valid=np.isfinite(xyz).all(1)&(xyz[:,2]>.29)&(xyz[:,2]<.85) valid &= np.linalg.norm(xyz[:,:2],axis=1)>.55 for arm in ('left','right'): valid &= np.linalg.norm(xyz-obs.eef(arm)[:3],axis=1)>.35 cells=self.cell(odom.world(xyz[valid])[:,:2]) cells=cells[(cells>=0).all(1)&(cells<self.size).all(1)] self.occupied[cells[:,0],cells[:,1]]=True
def route(self,start,goal): start,goal=tuple(self.cell(start)),tuple(self.cell(goal)) blocked=binary_dilation(self.occupied,iterations=3) # Allow leaving the current footprint, which may overlap noisy depth. x,y=start blocked[max(0,x-3):x+4,max(0,y-3):y+4]=False if not all(0<=v<self.size for v in (*start,*goal)) or blocked[goal]: return None costs={start:0.};parent={} queue=[(0.,start)] dirs=[(i,j) for i in (-1,0,1) for j in (-1,0,1) if i or j] while queue: _,node=heapq.heappop(queue) if node==goal:break for dx,dy in dirs: nxt=(node[0]+dx,node[1]+dy) if not all(0<=v<self.size for v in nxt) or blocked[nxt]:continue if dx and dy and (blocked[node[0]+dx,node[1]] or blocked[node[0],node[1]+dy]):continue cost=costs[node]+np.hypot(dx,dy) if cost<costs.get(nxt,float('inf')): costs[nxt]=cost;parent[nxt]=node heapq.heappush(queue,(cost+np.linalg.norm(np.subtract(nxt,goal)),nxt)) if goal not in costs:return None path=[goal] while path[-1]!=start:path.append(parent[path[-1]]) path=path[::-1] # Retain enough waypoints to follow around inflated furniture corners. return [self.xy(c) for c in path[5::5]]+[self.xy(goal)]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""Permitted observations, calibrated depth projection, and local odometry."""import jsonfrom pathlib import Pathimport cv2import numpy as npfrom scipy.spatial.transform import Rotationfrom scripts.kinematics import Kinematics, positions_from_proprio
def wrap(angle): return (angle + np.pi) % (2 * np.pi) - np.pi
def planar(pose): x, y, yaw = pose c, s = np.cos(yaw), np.sin(yaw) return np.array([[c, -s, 0, x], [s, c, 0, y], [0, 0, 1, 0], [0, 0, 0, 1.]])
class Sensors: def __init__(self, raw, kin=None): # Deliberately discard every non-sensor field before policy execution. self.raw = {k: np.asarray(v) for k, v in raw.items() if k.split('::')[-1] in ('rgb', 'depth_linear', 'proprio')} self.p = next(v for k, v in self.raw.items() if k.endswith('::proprio')).astype(float) if self.p.shape != (61,) or not np.isfinite(self.p).all(): raise ValueError('Expected finite R1Pro proprioception (61)') self.kin = kin or Kinematics() if not self.kin.eef_offsets: self.kin.calibrate(self.p) self.positions = positions_from_proprio(self.p) self._clouds = {}
@classmethod def load(cls, folder, kin=None): folder = Path(folder) meta = json.loads((folder / 'observation.json').read_text())['observations'] raw = {} for key, value in meta.items(): if key.endswith('::rgb'): raw[key] = cv2.cvtColor(cv2.imread(str(folder / value)), cv2.COLOR_BGR2RGB) elif key.endswith('::depth_linear'): raw[key] = np.load(folder / value) elif key.endswith('::proprio'): raw[key] = value return cls(raw, kin)
def get(self, camera, modality): return next(v for k, v in self.raw.items() if f':{camera}_link:' in k and k.endswith('::' + modality))
def camera(self, camera): local = np.eye(4) if camera == 'zed': local[:3, :3] = Rotation.from_quat([-1, 0, 0, 0]).as_matrix() local[:3, 3] = [.06, 0, .01] else: local[:3, :3] = Rotation.from_quat([.7071, -.7071, 0, 0]).as_matrix() return self.kin.pose(camera + '_link', self.positions) @ local
def cloud(self, camera='zed'): if camera not in self._clouds: depth = self.get(camera, 'depth_linear').squeeze() h, w = depth.shape fx = w * (306 / 720 if camera == 'zed' else 388.6639 / 480) v, u = np.indices((h, w)) xyz = np.stack(((u-w/2)*depth/fx, -(v-h/2)*depth/fx, -depth), -1) tf = self.camera(camera) self._clouds[camera] = xyz @ tf[:3, :3].T + tf[:3, 3] return self._clouds[camera]
def eef(self, arm='right'): start = 42 if arm == 'right' else 17 return self.p[start:start+7]
def hold(self): a = np.zeros(23, dtype=np.float32) a[3:7], a[7:14], a[15:22] = self.p[53:57], self.p[3:10], self.p[28:35] a[14] = np.clip(2*np.mean(self.p[24:26])/.05-1, -1, 1) a[22] = np.clip(2*np.mean(self.p[49:51])/.05-1, -1, 1) return a
class Odometry: """Integrate body-frame base velocity from the permitted proprioception.""" def __init__(self): self.pose = np.zeros(3)
def update(self, proprio, dt=1/30): vx, vy, omega = proprio[:3] yaw = self.pose[2] + omega*dt/2 self.pose[:2] += dt * np.array([np.cos(yaw)*vx-np.sin(yaw)*vy, np.sin(yaw)*vx+np.cos(yaw)*vy]) self.pose[2] = wrap(self.pose[2] + omega*dt)
def world(self, xyz): tf = planar(self.pose) return np.asarray(xyz) @ tf[:3, :3].T + tf[:3, 3]
def local(self, xyz): tf = planar(self.pose) return (np.asarray(xyz)-tf[:3, 3]) @ tf[:3, :3]12345678910111213141516171819#!/usr/bin/env bash#SBATCH --job-name=task00-recovery#SBATCH --partition=all#SBATCH --nodes=1#SBATCH --ntasks=1#SBATCH --gres=gpu:rtx4080s:1#SBATCH --cpus-per-task=12#SBATCH --mem=28G#SBATCH --time=04:00:00set -euo pipefail: "${RECOVERY_ROOT:?Set the staged recovery package path}": "${B1K_REPO:?Set the installed simulator source path}": "${B1K_PYTHON:?Set the installed Python environment}": "${RECOVERY_CASES:?Set the cases JSONL path}": "${RECOVERY_RUNS:?Set the output root}"source "$RECOVERY_ROOT/env_eai.sh"export OMNIGIBSON_APPDATA_PATH="$RECOVERY_ROOT/cache/${SLURM_JOB_ID}_${SLURM_ARRAY_TASK_ID:-0}"srun "$B1K_PYTHON" -m tools.driver --cases "$RECOVERY_CASES" --runs "$RECOVERY_RUNS" \ --shard "${SLURM_ARRAY_TASK_ID:-0}" --shards "${RECOVERY_SHARDS:-1}" --resolution 0 --export12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""URDF-only forward/inverse kinematics; never accesses the simulator."""import osimport xml.etree.ElementTree as ETimport numpy as npfrom scipy.optimize import least_squaresfrom scipy.spatial.transform import Rotation
URDF = os.environ.get('B1K_ROBOT_URDF', '/home/eai/code/b1k/datasets/omnigibson-robot-assets/models/r1pro/urdf/r1pro_with_meta_links.urdf')
class Kinematics: def __init__(self, path=URDF): self.joints = {} self.eef_offsets = {} for joint in ET.parse(path).getroot().findall('joint'): origin = joint.find('origin') xyz = np.fromstring(origin.get('xyz', '0 0 0'), sep=' ') if origin is not None else np.zeros(3) rpy = np.fromstring(origin.get('rpy', '0 0 0'), sep=' ') if origin is not None else np.zeros(3) transform = np.eye(4) transform[:3, :3] = Rotation.from_euler('xyz', rpy).as_matrix() transform[:3, 3] = xyz axis = joint.find('axis') axis = np.fromstring(axis.get('xyz'), sep=' ') if axis is not None else np.array([1., 0, 0]) limit = joint.find('limit') bounds = (float(limit.get('lower', '-3.14')), float(limit.get('upper', '3.14'))) if limit is not None else (-3.14, 3.14) self.joints[joint.find('child').get('link')] = (joint.get('name'), joint.find('parent').get('link'), joint.get('type'), transform, axis, bounds)
def pose(self, link, positions): if link.endswith('_eef_link'): arm = link.removesuffix('_eef_link') if arm not in self.eef_offsets: raise ValueError('Calibrate end-effector frame from proprioception first') return self.pose(f'{arm}_gripper_link', positions) @ self.eef_offsets[arm] if link not in self.joints: if link == 'base_link': return np.eye(4) raise KeyError(link) name, parent, kind, origin, axis, bounds = self.joints[link] motion = np.eye(4) q = positions.get(name, 0.) if kind in ('revolute', 'continuous'): motion[:3, :3] = Rotation.from_rotvec(axis * q).as_matrix() elif kind == 'prismatic': motion[:3, 3] = axis * q return self.pose(parent, positions) @ origin @ motion
def calibrate(self, proprio): positions = positions_from_proprio(proprio) for arm, start in [('left', 17), ('right', 42)]: observed = np.eye(4) observed[:3, 3] = proprio[start:start+3] observed[:3, :3] = Rotation.from_quat(proprio[start+3:start+7]).as_matrix() self.eef_offsets[arm] = np.linalg.inv(self.pose(f'{arm}_gripper_link', positions)) @ observed
def solve(self, arm, target_xyz, positions, target_quat=None, wide=False): names = [f'{arm}_arm_joint{i}' for i in range(1, 8)] initial = np.array([positions[n] for n in names]) by_name = {data[0]: data for data in self.joints.values()} lo, hi = np.array([by_name[n][-1] for n in names]).T target_rotation = Rotation.from_quat(target_quat) if target_quat is not None else None def residual(q): pose = self.pose(f'{arm}_eef_link', {**positions, **dict(zip(names, q))}) terms = [pose[:3, 3] - target_xyz] if target_rotation is not None: terms.append(.15 * (target_rotation.inv() * Rotation.from_matrix(pose[:3, :3])).as_rotvec()) terms.append(.003 * (q - initial)) return np.concatenate(terms) seeds = [initial] rng = np.random.default_rng(0) seeds.extend(initial + rng.normal(0, .35, size=7) for _ in range(5)) if wide: seeds.extend(rng.uniform(lo, hi) for _ in range(32)) results = [least_squares(residual, np.clip(seed, lo + 1e-6, hi - 1e-6), bounds=(lo, hi), max_nfev=300) for seed in seeds] result = min(results, key=lambda r: np.linalg.norm(residual(r.x))) final = self.pose(f'{arm}_eef_link', {**positions, **dict(zip(names, result.x))}) error = np.linalg.norm(final[:3, 3] - target_xyz) if not result.success or error > .015: raise ValueError(f'IK did not reach target: position error {error:.4f}m') return result.x, error
def positions_from_proprio(p): return {**{f'torso_joint{i+1}': q for i, q in enumerate(p[53:57])}, **{f'left_arm_joint{i+1}': q for i, q in enumerate(p[3:10])}, **{f'right_arm_joint{i+1}': q for i, q in enumerate(p[28:35])}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990"""Recover legacy fixed grasp identity from recorded rigid co-motion.
This is an inferred constraint, never reported as an exactly serialized one.No constraints are created here. The caller may create them only at reset."""import numpy as npfrom scipy.spatial.transform import Rotationfrom scripts.kinematics import Kinematics
def matrix(pose): p, q = pose a = np.eye(4) a[:3, :3] = Rotation.from_quat(np.asarray(q)).as_matrix() a[:3, 3] = np.asarray(p) return a
def infer_grasps(env, source, frame): robot = env.robots[0] names = list(robot.dof_names_ordered) kin = Kinematics() to_np = lambda x: x.detach().cpu().numpy() body = matrix(tuple(to_np(x) for x in robot.get_position_orientation())) base_link = matrix(tuple(to_np(x) for x in robot.links["base_link"].get_position_orientation())) base_offset = np.linalg.inv(body) @ base_link hand_offsets = {} for arm in robot.arm_names: gripper = matrix(tuple(to_np(x) for x in robot.links[f"{arm}_gripper_link"].get_position_orientation())) eef = matrix(tuple(to_np(x) for x in robot.eef_links[arm].get_position_orientation())) hand_offsets[arm] = np.linalg.inv(gripper) @ eef frames = sorted(set([max(0, frame - 30), frame, min(source.n_actions, frame + 30)])) samples = [] current_fk_error = {} for i in frames: snap, _ = source.materialize(i, {o.name: o.n_joints for o in env.scene.objects}) reg = snap[0]["registry"]["object_registry"] rs = reg[robot.name] q = np.asarray(rs["joint_pos"]) joints = dict(zip(names, q)) root = matrix((rs["root_link"]["pos"], rs["root_link"]["ori"])) bq = q[to_np(robot.base_idx).astype(int)] virtual = np.eye(4) virtual[:3, 3] = bq[:3] virtual[:3, :3] = Rotation.from_euler("XYZ", bq[3:6]).as_matrix() eefs = {arm: root @ virtual @ base_offset @ kin.pose(f"{arm}_gripper_link", joints) @ hand_offsets[arm] for arm in robot.arm_names} if i == frame: current_fk_error = {arm: float(np.linalg.norm(eefs[arm][:3, 3] - to_np(robot.get_eef_position(arm)))) for arm in robot.arm_names} objects = {n: matrix((v["root_link"]["pos"], v["root_link"]["ori"])) for n, v in reg.items() if n in {getattr(v, "wrapped_obj", v).name for v in env.task.object_scope.values() if getattr(getattr(v, "wrapped_obj", v), "category", None) == "radio"}} samples.append((i, eefs, objects, q, rs.get("controllers", {}))) if max(current_fk_error.values()) > .005: raise ValueError(f"Recorded FK mapping does not match live robot: {current_fk_error}") current = next(s for s in samples if s[0] == frame) inferred, ambiguous = [], [] for arm in robot.arm_names: width = float(current[3][to_np(robot.gripper_control_idx[arm]).astype(int)].mean()) control = current[4].get("gripper_" + arm, {}) target = control.get("goal", {}).get("target", [width]) requested_width = float(np.asarray(target).mean()) if requested_width > .025: continue candidates = [] for name, obj in current[2].items(): distance = np.linalg.norm(current[1][arm][:3, 3] - obj[:3, 3]) if distance > (.45 if "can_" not in name[:4] else .16): continue relative = [np.linalg.inv(s[1][arm]) @ s[2][name] for s in samples] translation_range = max(np.linalg.norm(x[:3, 3] - relative[0][:3, 3]) for x in relative) rotation_range = max(Rotation.from_matrix(relative[0][:3, :3].T @ x[:3, :3]).magnitude() for x in relative) movement = max(np.linalg.norm(s[2][name][:3, 3] - samples[0][2][name][:3, 3]) for s in samples) evidence = dict(arm=arm, object=name, distance_m=float(distance), grip_width_m=width, requested_grip_width_m=requested_width, relative_translation_range_m=float(translation_range), relative_rotation_range_rad=float(rotation_range), object_motion_m=float(movement), source_frames=frames, provenance="inferred_temporal_rigid_grasp") if translation_range < .012 and rotation_range < .12 and movement > .015: candidates.append(evidence) else: ambiguous.append(evidence) if len(candidates) > 1: raise ValueError(f"Ambiguous held object for {arm}: {candidates}") if candidates: # Co-motion establishes one object; other nearby objects do not # make the hand's identity ambiguous unless they also co-move. ambiguous = [e for e in ambiguous if e["arm"] != arm] inferred.extend(candidates) return inferred, {"fk_error_m": current_fk_error, "inferred": inferred, "ambiguous": ambiguous}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110"""Synchronous pre-action observations and T+1 full states; teacher sidecar separate."""import jsonfrom pathlib import Pathimport h5pyimport numpy as npfrom .sim import plain, array
class EpisodeWriter: def __init__(self, directory, provenance): self.directory = Path(directory) self.directory.mkdir(parents=True, exist_ok=False) self.f = h5py.File(self.directory / "trajectory.hdf5", "w") self.f.attrs.update(schema="task00-recovery-v1", action_frequency=30, action_semantics="R1Pro absolute joint targets, normalized base velocity, smooth gripper", language="Turn on the radio receiver.") self.f.attrs["provenance"] = json.dumps(plain(provenance)) self.f.attrs["depth_semantics"] = "nonfinite_or_nonpositive_depth_is_zero; consult_depth_valid_mask" self.f.create_group("observations") self.f.create_group("teacher") self.f.create_dataset("actions", shape=(0, 23), maxshape=(None, 23), dtype="f4", chunks=(64, 23)) self.f.create_dataset("states", shape=(0,), maxshape=(None,), dtype=h5py.vlen_dtype(np.dtype("float32"))) self.f.create_dataset("teacher/context_json", shape=(0,), maxshape=(None,), dtype=h5py.string_dtype()) self.f.create_dataset("teacher/supervision_mask", shape=(0,), maxshape=(None,), dtype="bool") self.f.create_dataset("terminated", shape=(0,), maxshape=(None,), dtype="bool") self.f.create_dataset("truncated", shape=(0,), maxshape=(None,), dtype="bool") self.events = (self.directory / "events.jsonl").open("w") self.n = 0 self.rejected_intervals = []
@staticmethod def append(dataset, value): n = len(dataset) dataset.resize(n + 1, axis=0) dataset[n] = value
def state(self, value): self.append(self.f["states"], array(value).astype(np.float32))
def step(self, obs, action, teacher, terminated, truncated, next_state): expected = set(self.f["observations"]) sensor_obs = {k: v for k, v in obs.items() if k.split("::")[-1] in {"rgb", "depth_linear", "proprio", "proprio_full", "cam_rel_poses"}} for key in list(sensor_obs): if key.endswith("::depth_linear"): depth = array(sensor_obs[key]) valid = np.isfinite(depth) & (depth > 0) sensor_obs[key] = np.where(valid, depth, 0) sensor_obs[key.rsplit("::", 1)[0] + "::depth_valid"] = valid if not sensor_obs or not any(k.endswith("::rgb") for k in sensor_obs): raise ValueError("Training record requires camera images") if self.n and set(sensor_obs) != expected: raise ValueError("Sensor key set changed within episode") for key, value in sensor_obs.items(): a = array(value) if key.endswith("::rgb"): a = a[..., :3].astype(np.uint8) elif key.endswith("::depth_valid"): a = a.astype(bool) else: a = a.astype(np.float32) if not self.n: self.f["observations"].create_dataset(key, shape=(0,) + a.shape, maxshape=(None,) + a.shape, dtype=a.dtype, chunks=(1,) + a.shape, compression="lzf") self.append(self.f["observations"][key], a) self.append(self.f["actions"], np.asarray(plain(action), dtype=np.float32)) self.append(self.f["teacher/context_json"], json.dumps(plain(teacher))) self.append(self.f["teacher/supervision_mask"], False) self.append(self.f["terminated"], bool(terminated)) self.append(self.f["truncated"], bool(truncated)) self.state(next_state) self.n += 1 if self.n % 30 == 0: self.f.flush()
def event(self, event_name, **data): self.events.write(json.dumps({"step": self.n, "event": event_name, **plain(data)}) + "\n") self.events.flush()
def verify_primitive(self, start, operation): if not 0 <= start <= self.n: raise ValueError("Invalid primitive interval") self.f["teacher/supervision_mask"][start:self.n] = True for begin, end in self.rejected_intervals: lo, hi = max(start, begin), min(self.n, end) if lo < hi: self.f["teacher/supervision_mask"][lo:hi] = False self.event("primitive_verified", operation=operation, start=start, end=self.n)
def reject_actions(self, start, reason): if not 0 <= start <= self.n: raise ValueError("Invalid rejected action interval") self.rejected_intervals.append((start, self.n)) self.f["teacher/supervision_mask"][start:self.n] = False self.event("actions_rejected", start=start, end=self.n, reason=reason)
def close(self, outcome): if self.n and not outcome.get("success"): self.f["truncated"][-1] = True errors = [] if len(self.f["states"]) != self.n + 1: errors.append("state_action_length_mismatch") if not all(len(v) == self.n for v in self.f["observations"].values()): errors.append("observation_action_length_mismatch") if errors: outcome.update(training_eligible=False, schema_errors=errors) self.f.attrs["outcome"] = json.dumps(plain(outcome)) self.f.close() self.events.close() (self.directory / "outcome.json").write_text(json.dumps(plain(outcome), indent=2) + "\n")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118"""Restore a recorded Task00 state and run physical recovery on the simulator."""import argparseimport hashlibimport jsonimport timeimport signalimport tracebackfrom pathlib import Path
from .source import SourceEpisodefrom .sim import build_env, restore, hold_action, task_state, plain, array
def main(): p = argparse.ArgumentParser(description=__doc__) p.add_argument("--source", type=Path, required=True) p.add_argument("--meta", type=Path, required=True) p.add_argument("--frame", type=int, required=True) p.add_argument("--output", type=Path, required=True) p.add_argument("--max-steps", type=int, default=3000) p.add_argument("--max-seconds", type=int, default=2400) p.add_argument("--resolution", type=int, default=256, help="0 for full native export resolution") p.add_argument("--probe-only", action="store_true") p.add_argument("--hold-steps", type=int, default=10) a = p.parse_args() if a.output.exists(): raise FileExistsError(a.output) def interrupted(signum, frame): raise InterruptedError(f"interrupted_signal_{signum}") signal.signal(signal.SIGTERM, interrupted) signal.signal(signal.SIGINT, interrupted) started = time.monotonic() writer = None package = Path(__file__).resolve().parents[1] code_files = {} for group in ('task00_recovery', 'experiments', 'pipeline', 'scripts'): for f in sorted((package/group).rglob('*.py')): code_files[str(f.relative_to(package))] = hashlib.sha256(f.read_bytes()).hexdigest() code_sha = hashlib.sha256(json.dumps(code_files, sort_keys=True).encode()).hexdigest() outcome = dict(success=False, training_eligible=False, status="infrastructure_failure", steps=0, code_sha256=code_sha, code_files=code_files, resolution=a.resolution) try: import numpy as np import torch import omnigibson as og source = SourceEpisode(a.source, a.meta) if source.config['task'].get('activity_name') != 'turning_on_radio': raise ValueError('Source is not turning_on_radio') env = build_env(source, a.resolution) signal.signal(signal.SIGTERM, interrupted) signal.signal(signal.SIGINT, interrupted) audit = restore(env, source, a.frame) before = task_state(env) print('RESTORE_STATE', json.dumps(before), flush=True) outcome.update(source=source.summary(), source_frame=a.frame, restore=audit, initial_task=before) for _ in range(a.hold_steps): env.step(hold_action(env.robots[0])) after = task_state(env) held_before = before['held'] position_drift = np.linalg.norm(np.asarray(before['radio_pose'][0]) - after['radio_pose'][0]) outcome['hold_audit'] = dict(before=before, after=after, radio_position_drift_m=float(position_drift)) if held_before != after['held'] or position_drift > .08: outcome['status'] = 'restore_failure' raise RuntimeError('restore_hold_check_failed') if audit.get('grasp_evidence', {}).get('ambiguous'): outcome['status'] = 'restore_failure' raise RuntimeError('ambiguous_source_grasp') audit = restore(env, source, a.frame) if a.probe_only: outcome.update(status='restore_verified', final_task=task_state(env)) import cv2 a.output.mkdir(parents=True, exist_ok=True) obs, _ = env.get_obs() for key, value in obs.items(): if key.endswith('::rgb'): cv2.imwrite(str(a.output/(key.replace(':', '_')+'.jpg')), cv2.cvtColor(array(value)[..., :3], cv2.COLOR_RGB2BGR)) elif before['success']: outcome.update(status='already_complete', already_complete_at_start=True, final_task=before) else: from .recording import EpisodeWriter from .teacher import RecoveryTeacher writer = EpisodeWriter(a.output, dict(source=source.summary(), frame=a.frame, restore=audit, source_sha256=hashlib.sha256(a.source.read_bytes()).hexdigest(), code_sha256=code_sha, code_files=code_files)) teacher = RecoveryTeacher(env, writer, max_steps=a.max_steps, max_seconds=a.max_seconds) outcome['status'] = 'teacher_failure' outcome.update(teacher.run()) outcome.update(steps=teacher.steps, final_task=task_state(env)) import cv2 images = [cv2.resize(v[..., :3], (256, 256)) for k,v in teacher.raw.items() if k.endswith('::rgb')] if images: cv2.imwrite(str(a.output/'final.jpg'), cv2.cvtColor(np.concatenate(images, axis=1), cv2.COLOR_RGB2BGR)) except Exception as exc: outcome.update(error=str(exc), traceback=traceback.format_exc()) if isinstance(exc, InterruptedError): outcome['status'] = 'infrastructure_failure' if 'teacher' in locals(): outcome.update(steps=teacher.steps, final_task=task_state(env)) print(outcome['traceback'], flush=True) finally: outcome['wall_seconds'] = round(time.monotonic() - started, 3) if writer: outcome["steps"] = writer.n writer.close(outcome) else: a.output.mkdir(parents=True, exist_ok=True) (a.output/'outcome.json').write_text(json.dumps(plain(outcome), indent=2)+'\n') print('OUTCOME', json.dumps(plain(outcome)), flush=True) try: import omnigibson as og og.shutdown() except Exception: pass return 0 if outcome['status'] not in ('infrastructure_failure', 'restore_failure') else 2
if __name__ == '__main__': raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202"""OmniGibson boundary. Privileged state stays on the teacher / audit side."""from __future__ import annotationsimport copyimport jsonimport osfrom pathlib import Pathimport numpy as np
def plain(value): if hasattr(value, "detach"): return value.detach().cpu().numpy().tolist() if isinstance(value, np.ndarray): return value.tolist() if isinstance(value, dict): return {str(k): plain(v) for k, v in value.items()} if isinstance(value, (tuple, list)): return [plain(v) for v in value] if isinstance(value, np.generic): return value.item() return value
def array(value): return value.detach().cpu().numpy() if hasattr(value, "detach") else np.asarray(value)
def build_env(source, resolution=256): os.environ.setdefault("OMNI_KIT_ACCEPT_EULA", "YES") import omnigibson as og from omnigibson.macros import gm import yaml gm.USE_GPU_DYNAMICS = False gm.ENABLE_TRANSITION_RULES = False gm.ENABLE_FLATCACHE = True config = copy.deepcopy(source.config) config.pop("wrapper", None) # The original config reconstructs background objects omitted from scene_file. config["env"].update(action_frequency=30, rendering_frequency=30, physics_frequency=120, flatten_obs_space=True, automatic_reset=False) config["task"].update(online_object_sampling=False, use_presampled_robot_pose=False, include_obs=False) config["task"].setdefault("termination_config", {})["max_steps"] = 12000 old_robot = config["robots"][0] robot = yaml.safe_load((Path(os.environ["B1K_REPO"]) / "OmniGibson/omnigibson/eval/r1pro.yaml").read_text()) robot.pop("eval", None) for key in ("name", "position", "orientation", "scale"): if key in old_robot: robot[key] = old_robot[key] robot["obs_modalities"] = ["proprio", "rgb", "depth_linear"] robot["sensor_config"]["VisionSensor"]["sensor_kwargs"].update( image_height=resolution or 480, image_width=resolution or 480) config["robots"] = [robot] print("RECOVERY building environment", flush=True) env = og.Environment(configs=config) for name, sensor in env.robots[0].sensors.items(): if "zed_link" in name: sensor.horizontal_aperture = 40.0 if resolution == 0: sensor.image_height = 720 sensor.image_width = 720 if resolution == 0: # Campaign patch: resizing a sensor after env creation invalidates physics # views; refresh them exactly as the official RGBDFullResWrapper does. og.sim.update_handles() env.load_observation_space() env._recovery_config = config env._recovery_initial = copy.deepcopy(og.sim.dump_state(serialized=False)) return env
def grasp_names(robot): return {arm: (robot._ag_obj_in_hand[arm].name if robot._ag_obj_in_hand[arm] is not None else None) for arm in robot.arm_names}
def hold_action(robot): """Absolute joint positions; keep each restored occupied hand closed.""" import torch q = robot.get_joint_positions() a = torch.zeros(robot.action_dim, dtype=torch.float32) # Controller order is checked at the boundary, not assumed silently. expected = ["base", "trunk", "arm_left", "gripper_left", "arm_right", "gripper_right"] order = [n for n in robot.controller_order if n != "camera"] if order != expected or robot.action_dim != 23: raise ValueError(f"Unsupported controller order/dimension: {order}/{robot.action_dim}") a[3:7] = q[robot.trunk_control_idx] for arm, start, grip in (("left", 7, 14), ("right", 15, 22)): a[start:start + 7] = q[robot.arm_control_idx[arm]] a[grip] = -1 if grasp_names(robot)[arm] else torch.clamp( 2 * q[robot.gripper_control_idx[arm]].mean() / .05 - 1, -1, 1) return a
def restore(env, source, frame, infer_missing_grasps=True): """Restore only at the episode boundary. No pose setting during execution.""" import torch import omnigibson as og from .vendor.fork_state import backfill_untemplated_entities, translate_fork_snapshot snapshot, audit = source.materialize(frame, {o.name: o.n_joints for o in env.scene.objects}) audit["backfilled_entities"] = backfill_untemplated_entities(snapshot, env._recovery_initial) if audit["unresolved_tails"]: raise ValueError(f"Unresolved source fields: {audit['unresolved_tails']}") snapshot = translate_fork_snapshot(snapshot) # Load all physical poses first. Legacy fixed-grasp frames must be built only # after BOTH the hand and object have reached their recorded poses. pending = [] robot = env.robots[0] explicit_grasp_state = False for name, entity in snapshot[0]["registry"]["object_registry"].items(): if "controller_groups" in entity: explicit_grasp_state = "ag_obj_constraint_params" in entity audit["source_controller_state"] = plain(entity["controller_groups"]) entity["controller_groups"] = {} # teacher starts from measured hold for arm, params in entity.get("ag_obj_constraint_params", {}).items(): if params: pending.append((name, arm, params)) entity["ag_obj_constraint_params"] = {} og.sim.load_state(snapshot, serialized=False) audit["grasp_restore"] = [] audit["grasp_state_serialized"] = explicit_grasp_state if not pending and not explicit_grasp_state and infer_missing_grasps: from .grasp_evidence import infer_grasps inferred, evidence = infer_grasps(env, source, frame) audit["grasp_evidence"] = evidence for item in inferred: obj = env.scene.object_registry("name", item["object"]) if obj.n_joints: raise ValueError("Inferred grasp requires an object with no articulated degrees of freedom") # Fixed-link assemblies (e.g. bin body + handle) are one rigid body. root_index = list(obj.links.values()).index(obj.root_link) pending.append((robot.name, item["arm"], {"ag_obj_uuid": obj.uuid, "ag_link_idx": root_index})) for robot_name, arm, params in pending: if robot_name != robot.name or "ag_obj_uuid" not in params: raise ValueError(f"Unsupported legacy grasp descriptor: {robot_name}/{arm}/{params}") obj = env.scene.object_registry("uuid", int(params["ag_obj_uuid"])) if obj is None: raise ValueError("Recorded grasp target missing in live scene") link_name = list(obj.links)[int(params["ag_link_idx"])] link = obj.links[link_name] joint_type = robot._get_assisted_grasp_joint_type(obj, link_name) if joint_type != "FixedJoint": raise ValueError("Legacy spherical grasp pivot is not recoverable exactly") # A fixed joint is independent of choice of anchor. Keep recorded pose AND velocities. robot._establish_grasp(target_obj=obj, target_link_name=link_name, arm=arm, contact_pos_world=link.get_position_orientation()[0], joint_type=joint_type) audit["grasp_restore"].append({"arm": arm, "object": obj.name, "joint_type": joint_type}) for obj in env.scene.objects: if obj.n_joints and not obj.kinematic_only: obj.set_joint_positions(obj.get_joint_positions(), drive=True) obj.set_joint_velocities(torch.zeros_like(obj.get_joint_velocities()), drive=True) robot.apply_action(hold_action(robot)) for _ in range(4): og.sim.render() audit.update(frame=frame, held=grasp_names(robot), physics_steps_before_audit=0, controller_handoff="measured_position_hold") return audit
def radio_object(env): objects = [getattr(v, "wrapped_obj", v) for v in env.task.object_scope.values()] radios = [o for o in objects if getattr(o, "category", None) == "radio"] if len(radios) != 1: raise ValueError(f"Expected one radio, found {[o.name for o in radios]}") return radios[0]
def task_state(env): from omnigibson.object_states import ToggledOn from scipy.spatial.transform import Rotation robot = env.robots[0] obj = radio_object(env) actual_success, goal_status = env.task.compiled_task.check_goal(env.task._evaluate_predicate) toggle = obj.states[ToggledOn] pos, quat = obj.get_position_orientation() rotation = Rotation.from_quat(array(quat)) marker = array(toggle.visual_marker.get_position_orientation()[0]) local_marker = rotation.inv().apply(marker-array(pos)) points = array(obj.root_link.collision_boundary_points_local) scale = array(obj.scale) points = points * scale lo, hi = points.min(0), points.max(0) distances = np.r_[abs(local_marker-lo), abs(local_marker-hi)] face = int(np.argmin(distances)) normal = np.eye(3)[face % 3] * (-1 if face < 3 else 1) handle = np.median(points[points[:, 2] > hi[2]-.015], axis=0) return {"success": bool(actual_success), "goal_status": plain(goal_status), "held": grasp_names(robot), "radio_name": obj.name, "radio_pose": plain((pos, quat)), "radio_joints": obj.n_joints, "radio_links": list(obj.links), "radio_on": bool(toggle.get_value()), "button_normal_world": rotation.apply(normal).tolist(), "handle_world": (rotation.apply(handle)+array(pos)).tolist(), "handle_axis_world": rotation.apply([0, 1, 0]).tolist(), "radio_finger_contact": obj in (ToggledOn._finger_contact_objs or set()), "toggle_pose": plain(toggle.link.get_position_orientation()), "toggle_marker_pose": plain(toggle.visual_marker.get_position_orientation()), "toggle_scale": plain(toggle.scale), "toggle_contact_steps": toggle.robot_can_toggle_steps, "eef_world": {a: plain(robot.eef_links[a].get_position_orientation()) for a in robot.arm_names}, "object_positions": {obj.name: plain(pos)}, "robot_pose": plain(robot.get_position_orientation())}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273"""Strict source contracts shared by indexing, restoration, and provenance."""from __future__ import annotations
import copyimport jsonfrom pathlib import Pathimport h5pyimport numpy as npfrom .vendor.fork_serialization import ForkStateLayout, peel_json
class SourceEpisode: def __init__(self, path, meta=None): self.path = Path(path) self.meta_path = Path(meta) if meta else None self.metadata = json.loads(self.meta_path.read_text()) if meta else {} with h5py.File(self.path, "r") as f: root = f["data"] self.config = peel_json(self.metadata.get("config", root.attrs.get("config"))) self.scene_file = peel_json(self.metadata.get("scene_file", root.attrs.get("scene_file"))) if not isinstance(self.config, dict) or not isinstance(self.scene_file, dict): raise ValueError("A recorded config and scene_file are required") d = root["demo_0"] self.n_actions = len(d["action"]) self.n_states = len(d["state"]) if self.n_states != self.n_actions + 1: raise ValueError("Expected pre-action states plus one terminal state") if d["action"].shape[1:] != (23,): raise ValueError("This pipeline requires the R1Pro 23-dimensional action contract") self.success = bool(d.attrs.get("success", self.metadata.get("success", False))) self.width = d["state"].shape[1] self.state_sizes = np.asarray(d["state_size"], dtype=np.int64) if len(self.state_sizes) != self.n_states or np.any(self.state_sizes <= 0) or np.any(self.state_sizes > self.width): raise ValueError("Invalid state_size")
def layout(self, joint_counts=None): return ForkStateLayout(self.scene_file, joint_counts=joint_counts)
def materialize(self, frame, joint_counts=None): """Merge every filtered state through frame; skipped entities retain history.
Copying only a mid-episode row would leave sleeping objects at initial poses. Initial recorded scene fields are authoritative, not the previous attempt. """ if not 0 <= frame < self.n_states: raise IndexError(frame) layout = self.layout(joint_counts) scene = copy.deepcopy(self.scene_file["state"]) result = {0: scene} grasp_history = {} with h5py.File(self.path, "r") as f: states = f["data/demo_0/state"] # Read in blocks to avoid millions of small HDF5 calls. for begin in range(0, frame + 1, 256): rows = states[begin:min(frame + 1, begin + 256)] for offset, row in enumerate(rows): i = begin + offset decoded = layout.decode_row(row[:self.state_sizes[i]])[0] scene["pos"], scene["ori"] = decoded["pos"], decoded["ori"] for registry, entities in decoded["registry"].items(): scene["registry"].setdefault(registry, {}).update(entities) for entity in entities.values(): for arm, params in entity.get("ag_obj_constraint_params", {}).items(): if params and "ag_obj_uuid" in params: grasp_history[str(int(params["ag_obj_uuid"]))] = {"arm": arm, "frame": i} return result, {"prefix_rows": frame + 1, "unresolved_tails": layout.unresolved_tails, "derived_decodes": layout.derived_decodes, "last_grasp_by_uuid": grasp_history}
def summary(self): return {"path": str(self.path), "meta": str(self.meta_path) if self.meta_path else None, "n_actions": self.n_actions, "n_states": self.n_states, "state_width": self.width, "state_sizes": np.unique(self.state_sizes).tolist(), "source_success": self.success, "versions": self.scene_file.get("versions")}12345678910111213141516171819202122232425262728293031323334353637383940414243"""Human dataset observation contract, including the 256-dimensional state."""import numpy as npfrom scipy.spatial.transform import Rotationfrom .sim import array, plainfrom .grasp_evidence import matrix
# Original LeRobot conversion removes grasp_left / grasp_right from the 258-D# recording. Grasp identity / BDDL remain exclusively in the teacher sidecar.PROPRIO_KEYS = ["joint_qpos", "joint_qpos_sin", "joint_qpos_cos", "joint_qvel", "joint_qeffort", "robot_pos", "robot_ori_cos", "robot_ori_sin", "robot_2d_ori", "robot_2d_ori_cos", "robot_2d_ori_sin", "robot_lin_vel", "robot_ang_vel"]for _arm in ("left", "right"): PROPRIO_KEYS += [f"arm_{_arm}_qpos", f"arm_{_arm}_qpos_sin", f"arm_{_arm}_qpos_cos", f"arm_{_arm}_qvel", f"eef_{_arm}_pos", f"eef_{_arm}_quat", f"gripper_{_arm}_qpos", f"gripper_{_arm}_qvel"]PROPRIO_KEYS += ["trunk_qpos", "trunk_qvel", "base_qpos", "base_qpos_sin", "base_qpos_cos", "base_qvel"]
def extra_observations(robot): values = robot._get_proprioception_dict() parts = [array(values[k]).reshape(-1) for k in PROPRIO_KEYS] state = np.concatenate(parts).astype(np.float32) if state.shape != (256,) or not np.isfinite(state).all(): raise ValueError(f"Invalid human-format state: {state.shape}") result = {robot.name + "::proprio_full": state} body_inv = np.linalg.inv(matrix(plain(robot.get_position_orientation()))) poses = [] for role in ("left_realsense", "right_realsense", "zed"): sensor = next(v for k, v in robot.sensors.items() if role + "_link" in k) pose = body_inv @ matrix(plain(sensor.get_position_orientation())) poses.append(np.r_[pose[:3, 3], Rotation.from_matrix(pose[:3, :3]).as_quat()]) result[robot.name + "::cam_rel_poses"] = np.concatenate(poses).astype(np.float32) return result
def schema(robot): values = robot._get_proprioception_dict() widths = [array(values[k]).size for k in PROPRIO_KEYS] offsets = np.cumsum([0] + widths).tolist() return {"state_fields": {k: [offsets[i], offsets[i + 1]] for i, k in enumerate(PROPRIO_KEYS)}, "joint_names": list(robot.dof_names_ordered), "base_qvel_frame": "robot_body", "camera_order": ["left_wrist", "right_wrist", "head"], "camera_quaternion": "xyzw", "note": "Full state follows human-format ordering; 61-D policy input is also retained." " Image resizing is explicit; production should use original camera resolutions."}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480"""State-aware, privileged code teacher; all task progress uses physical actions.
The restored task state is used to choose an entry phase and locate the radio'scontrol. It is never included in the student observation. No state/pose settersor synthetic assisted grasps are used after restoration."""import timeimport numpy as npfrom scipy.spatial.transform import Rotation
from experiments.radio_two_arm.policy import RadioPolicyfrom experiments.radio_two_arm.motion import solvefrom experiments.radio_two_arm.navigation import choose_goalfrom pipeline.sensors import Sensors, wrapfrom .sim import array, plain, hold_action, task_state, radio_objectfrom .student import extra_observations
class GoalReached(Exception): pass
def entry_phase(context): if context['success']: return 'complete' held = [arm for arm, name in context['held'].items() if name == context['radio_name']] if held: return 'press_' + held[0] + '_held' return 'recover_floor' if context['radio_pose'][0][2] < .30 else 'recover_supported'
class NavigationObservation: """Keep depth-grid angular sampling independent of recording resolution.
The grid samples every fifth pixel. Feeding 720px instead of the validated 256px view otherwise changes obstacle evidence density by nearly eightfold. Only this planning view is resampled; recorded RGB/depth stay native. """ def __init__(self, observation): self.observation = observation
def __getattr__(self, name): return getattr(self.observation, name)
def cloud(self, camera='zed'): points = self.observation.cloud(camera) h, w = points.shape[:2] if (h, w) == (256, 256): return points rows = np.minimum((np.arange(256)*h/256).astype(int), h-1) cols = np.minimum((np.arange(256)*w/256).astype(int), w-1) return points[rows[:, None], cols]
class RecoveryTeacher(RadioPolicy): def __init__(self, env, writer, max_steps=3000, max_seconds=2400): self.env, self.writer = env, writer self.max_steps = max_steps self.deadline = time.monotonic() + max_seconds super().__init__(writer.events) self.refresh() self.grippers = array(hold_action(env.robots[0]))[[14, 22]].tolist() import omnigibson as og self.writer.state(og.sim.dump_state(serialized=True)) self.primitive_start = 0 self.press_anchor = None self.last_action = None self.releasing_arm = None self.primary_holder = None self.press_open_hands = set()
def event(self, event_name, **values): self.writer.event(event_name, phase=self.phase, **values) if event_name in ('strategy', 'strategy_failed', 'press_candidate', 'grasp_verified'): print('TEACHER', self.steps, event_name, values, flush=True)
def refresh(self): raw, _ = self.env.get_obs() self.raw = {k: array(v) for k, v in raw.items()} self.obs = Sensors(self.raw, self.kin) self.raw.update(extra_observations(self.env.robots[0])) self.context = task_state(self.env)
def local(self, world): pos, quat = self.context['robot_pose'] return Rotation.from_quat(quat).inv().apply(np.asarray(world) - pos)
def tick(self, action): import torch import omnigibson as og if self.steps >= self.max_steps or time.monotonic() >= self.deadline: raise TimeoutError('recovery_budget_exhausted') action = np.asarray(action, dtype=np.float32) if action.shape != (23,) or not np.isfinite(action).all(): raise ValueError('invalid_action') # Preserve every occupied hand unless a deliberate release is implemented. for arm, grip in [('left', 14), ('right', 22)]: if self.context['held'][arm] and arm != self.releasing_arm: action[grip] = -1 before = {k: v.copy() for k, v in self.raw.items()} context = self.context self.env.step(torch.as_tensor(action)) self.last_action = action.copy() self.refresh() self.steps += 1 self.odom.update(self.obs.p) self.writer.step(before, action, dict(phase=self.phase, **context), self.context['success'], False, og.sim.dump_state(serialized=True)) if self.steps % 30 == 0: print('STEP', self.steps, self.phase, self.context['toggle_contact_steps'], self.context['radio_finger_contact'], flush=True) import cv2 images = [cv2.resize(v[..., :3], (256, 256)) for k,v in self.raw.items() if k.endswith('::rgb')] if images: cv2.imwrite(str(self.writer.directory/'latest.jpg'), cv2.cvtColor(np.concatenate(images, axis=1), cv2.COLOR_RGB2BGR)) tilt = np.arccos(np.clip(Rotation.from_quat(self.context['robot_pose'][1]).as_matrix()[2, 2], -1, 1)) if tilt > .40: self.writer.reject_actions(self.primitive_start, 'robot_base_unstable') raise ValueError('robot_base_unstable') if self.context['success']: self.writer.verify_primitive(self.primitive_start, 'activate_radio') raise GoalReached() if (self.phase in ('press_left', 'press_right') and all(obj == self.context['radio_name'] for obj in self.context['held'].values())): raise RuntimeError('press_free_hand_grasped_radio')
def execute(self, generator): self.primitive_start = self.steps for action in generator: self.tick(action)
def holding_target(self, arm): if self.press_anchor is None or self.phase != 'press_' + arm: return None holding, position, quaternion = self.press_anchor if (holding == arm or self.context['held'][holding] != self.context['radio_name']): raise RuntimeError('press_holding_hand_changed') target = np.eye(4) target[:3, 3] = self.local(position) target[:3, :3] = (Rotation.from_quat(self.context['robot_pose'][1]).inv() * Rotation.from_quat(quaternion)).as_matrix() return target
def solve_motion(self, arm, xyz, quat, preserve=False, fixed_joints=()): return solve(self.obs, arm, xyz, quat, preserve, fixed_joints, other_pose=self.holding_target(arm))
def wait(self, steps): # Continue the position command during contact dwell. Replacing it with # the loaded hand's measured joints would accumulate tracking deflection. if (self.press_anchor is not None and self.phase.startswith('press_') and self.last_action is not None): action = self.last_action.copy() action[:3] = 0 action[[14, 22]] = self.grippers for _ in range(steps): yield action.copy() else: yield from super().wait(steps)
def move(self, arm, xyz, quat, steps=25, preserve=False, fixed_joints=(), retry=True): yield from super().move(arm, xyz, quat, steps, preserve, fixed_joints, retry) target = self.holding_target(arm) if target is not None: holding = 'right' if arm == 'left' else 'left' actual = self.obs.eef(holding) position_error = float(np.linalg.norm(actual[:3]-target[:3, 3])) rotation_error = float((Rotation.from_matrix(target[:3, :3]).inv() * Rotation.from_quat(actual[3:])).magnitude()) self.event('holding_pose_result', arm=holding, position_error=position_error, rotation_error=rotation_error) if position_error > .08 or rotation_error > .35: raise RuntimeError('press_holding_pose_displaced')
def navigate(self): """Replan a depth-observed route to the current radio/button location.""" self.phase = 'recovery_approach' previous = None history = [] floor = self.context['radio_pose'][0][2] < .30 reaches = (.58, .68) if floor else (.82, .94) for _ in range(65): local = self.local(self.context['toggle_marker_pose'][0]) if np.linalg.norm(local[:2] - [.65, 0]) < .20: return self.grid.observe(NavigationObservation(self.obs), self.odom) position, quaternion = self.context['robot_pose'] yaw = Rotation.from_quat(quaternion).as_euler('xyz')[2] history.append((np.asarray(position[:2]), yaw)) if len(history) >= 7: before, heading = history[-7] if (np.linalg.norm(history[-1][0]-before) < .015 and abs(wrap(yaw-heading)) < .025): raise RuntimeError('navigation_physically_stalled') world = self.odom.world(local) choice = choose_goal(self.grid, self.odom.pose, world, previous, reaches=reaches, lateral=0 if floor else .15) if choice is None: raise RuntimeError('no_observed_traversable_route') previous, route = choice if (np.linalg.norm(previous[:2] - self.odom.pose[:2]) < .06 and abs(wrap(previous[2]-self.odom.pose[2])) < .10): return waypoint = next((q for q in route if np.linalg.norm(q-self.odom.pose[:2]) > .10), previous[:2]) c, s = np.cos(self.odom.pose[2]), np.sin(self.odom.pose[2]) delta = np.array([[c, s], [-s, c]]) @ (waypoint-self.odom.pose[:2]) velocity = np.clip(delta*1.3, -.22, .22) angular = np.clip(wrap(previous[2]-self.odom.pose[2]), -.4, .4) self.event('navigation_waypoint', goal=previous.tolist(), target_local=local.tolist(), velocity=[*velocity, angular]) yield from self.drive([*velocity, angular], 10) raise RuntimeError('recovery_navigation_budget_exhausted')
def press(self, arm): """Try bounded physical contact poses around the actual toggle marker.""" self.phase = 'press_' + arm self.press_anchor = None preserve = any(self.context['held'].values()) or self.context['radio_pose'][0][2] >= .30 if not any(self.context['held'].values()) and self.context['button_normal_world'][2] < -.5: raise RuntimeError('button_faces_support_surface_requires_regrasp') grip = 0 if arm == 'left' else 1 self.grippers[grip] = 1 if arm in self.press_open_hands else -1 yield from self.wait(8) holding = 'right' if arm == 'left' else 'left' if self.context['held'][holding] == self.context['radio_name']: position, quaternion = self.context['eef_world'][holding] self.press_anchor = (holding, np.array(position), np.array(quaternion)) self.event('press_holding_anchor', arm=holding, position=position, quaternion=quaternion) # Candidate wrist orientations include the proven Task00 pose and mirrored # counterpart, current pose and top-down approaches for fallen radios. quats = [self.obs.eef(arm)[3:].tolist(), [-.183, .683, .183, .683], [.183, .683, -.183, .683], [0, 1, 0, 0], [-.7071, .7071, 0, 0]] candidates = [] target = self.local(self.context['toggle_marker_pose'][0]) robot_R = Rotation.from_quat(self.context['robot_pose'][1]) normal = robot_R.inv().apply(self.context['button_normal_world']) eef_world_p, eef_world_q = self.env.robots[0].eef_links[arm].get_position_orientation() eef_world_R = Rotation.from_quat(array(eef_world_q)) fingers = [] for finger in self.env.robots[0].finger_links[arm]: vertices = array(finger.collision_boundary_points_world) fingers.append(eef_world_R.inv().apply(vertices-array(eef_world_p))) for quat in quats: rotation = Rotation.from_quat(quat) for finger in fingers: vertices = rotation.apply(finger) distances = vertices @ normal # Leading surface toward the radio, expressed relative to the EEF. tip = vertices[distances < distances.min()+.003].mean(0) point = target-tip+normal*.002 try: action, err = self.solve_motion(arm, point, quat, preserve) except RuntimeError: continue cost = np.linalg.norm(action[3:22] - self.obs.hold()[3:22]) candidates.append((cost, quat, tip)) if not candidates: raise RuntimeError('no_feasible_press_pose') for _, quat, tip in sorted(candidates, key=lambda c: c[0])[:8]: candidate_start = self.steps target = self.local(self.context['toggle_marker_pose'][0]) normal = Rotation.from_quat(self.context['robot_pose'][1]).inv().apply(self.context['button_normal_world']) self.event('press_candidate', arm=arm, target=target.tolist(), quat=quat, tip=tip.tolist()) try: yield from self.move(arm, target-tip+normal*.07, quat, 20, preserve=preserve) for distance in (.025, .012, .004, -.003, -.009): target = self.local(self.context['toggle_marker_pose'][0]) yield from self.move(arm, target-tip+normal*distance, quat, 12, preserve=preserve) yield from self.wait(8) except RuntimeError as exc: self.event('press_pose_failed', error=str(exc)) if str(exc) == 'press_free_hand_grasped_radio': raise self.writer.reject_actions(candidate_start, 'press_candidate_did_not_activate') raise RuntimeError('press_contact_candidates_exhausted')
def release_secondary_grasp(self, primary): """Physically free an accidentally attached pressing hand before replanning.""" secondary = 'right' if primary == 'left' else 'left' self.phase = 'release_secondary_' + secondary self.press_anchor = None self.releasing_arm = secondary self.grippers[0 if primary == 'left' else 1] = -1 self.grippers[0 if secondary == 'left' else 1] = 1 try: yield from self.wait(20) if self.context['held'][secondary] is not None: raise RuntimeError('secondary_grasp_release_failed') if self.context['held'][primary] != self.context['radio_name']: raise RuntimeError('primary_grasp_lost_during_release') # Open fingers cannot establish another assisted grasp while pressing. # Press geometry is recomputed from their actual open collision mesh. self.press_open_hands.add(secondary) self.event('secondary_grasp_released', primary=primary, secondary=secondary) eef = self.obs.eef(secondary).copy() retreat = np.array([0, .12 if secondary == 'left' else -.12, .04]) yield from self.move(secondary, eef[:3]+retreat, eef[3:], 25, preserve=True) finally: self.releasing_arm = None
def grounded_grasp(self): """Acquire the handle in its measured orientation, including a tipped radio.""" self.phase = 'recover_handle' floor = self.context['radio_pose'][0][2] < .30 if np.linalg.norm(self.local(self.context['handle_world'])[:2]) > (.80 if floor else 1.05): yield from self.navigate() self.phase = 'recover_handle' for arm in ('left', 'right'): handle = self.local(self.context['handle_world']) axis = Rotation.from_quat(self.context['robot_pose'][1]).inv().apply(self.context['handle_axis_world']) theta = np.arctan2(axis[1], axis[0]) quat = [-np.sin(theta/2), np.cos(theta/2), 0, 0] index = 0 if arm == 'left' else 1 for delta in ([0, 0, -.01], [0, 0, .01], [-.015, 0, 0]): candidate_start = self.steps if any(self.context['held'].values()): return self.grippers[index] = 1 try: yield from self.move(arm, handle+[0, 0, .14], quat, 30, preserve=not floor) yield from self.wait(8) handle = self.local(self.context['handle_world']) yield from self.move(arm, handle+delta, quat, 25, preserve=not floor) self.grippers[index] = -1 yield from self.wait(20) if self.context['held'][arm] != self.context['radio_name']: self.event('grasp_not_established', arm=arm) self.writer.reject_actions(candidate_start, 'grasp_not_established') continue start_height = self.context['radio_pose'][0][2] yield from self.move(arm, self.obs.eef(arm)[:3]+[0,0,.14], quat, 30, preserve=True) if self.context['radio_pose'][0][2] < start_height+.06: raise RuntimeError('grasp_lift_not_verified') self.writer.verify_primitive(self.primitive_start, 'acquire_radio') self.event('grasp_verified', arm=arm) return except RuntimeError as exc: self.writer.reject_actions(candidate_start, str(exc)) self.event('grasp_candidate_failed', arm=arm, error=str(exc)) raise RuntimeError('handle_grasp_candidates_exhausted')
def reorient(self, holding_arm, variant=0): """Present the button to the free hand while maintaining the real grasp.""" self.phase = 'reorient_' + holding_arm robot_R = Rotation.from_quat(self.context['robot_pose'][1]) radio_R = robot_R.inv() * Rotation.from_quat(self.context['radio_pose'][1]) radio_pos = self.local(self.context['radio_pose'][0]) eef = self.obs.eef(holding_arm).copy() relative_R = radio_R.inv() * Rotation.from_quat(eef[3:]) relative_p = radio_R.inv().apply(eef[:3]-radio_pos) button_offset = radio_R.inv().apply(self.local(self.context['toggle_marker_pose'][0])-radio_pos) side_yaw = -np.pi/2 if holding_arm == 'left' else np.pi/2 orientations = [Rotation.from_euler('z', np.pi), Rotation.from_euler('z', side_yaw), Rotation.from_euler('z', side_yaw)*Rotation.from_euler('y', -np.pi/2), Rotation.identity(), Rotation.from_euler('z', -side_yaw), Rotation.from_euler('y', -np.pi/2)] orientations = orientations[variant % len(orientations):] + orientations[:variant % len(orientations)] for desired_R in orientations: for center in ([.60, 0, .78], [.65, .08 if holding_arm=='left' else -.08, .68]): target_obj = np.asarray(center)-desired_R.apply(button_offset) target_eef = target_obj+desired_R.apply(relative_p) try: yield from self.move(holding_arm, target_eef, (desired_R*relative_R).as_quat(), 45, preserve=True) yield from self.wait(8) return except RuntimeError as exc: self.event('reorient_candidate_failed', error=str(exc)) raise RuntimeError('radio_reorientation_infeasible')
def clear_free_hand(self, holding_arm): """Move the unused hand out of the radio's presentation workspace.""" arm = 'right' if holding_arm == 'left' else 'left' if self.context['held'][arm] is not None: raise RuntimeError('clear_hand_is_occupied') self.phase = 'clear_' + arm self.press_anchor = None side = 1 if arm == 'left' else -1 eef = self.obs.eef(arm).copy() # Withdraw laterally before bringing the held radio to the midline. # Every move solves for both hands and preserves the actual holding pose. candidates = [eef[:3] + [0, side*.16, .08], np.array([.45, side*.32, .85]), np.array([.50, side*.35, .95])] for target in candidates: try: yield from self.move(arm, target, eef[3:], 30, preserve=True) if self.context['held'][holding_arm] != self.context['radio_name']: raise RuntimeError('holding_grasp_lost_while_clearing') self.event('free_hand_cleared', arm=arm, holding=holding_arm) return except RuntimeError as exc: self.event('clear_hand_candidate_failed', arm=arm, error=str(exc)) raise RuntimeError('free_hand_clearance_infeasible')
def recenter(self, holding_arm): self.phase = 'recenter_' + holding_arm button = self.local(self.context['toggle_marker_pose'][0]) eef = self.obs.eef(holding_arm).copy() for center in ([.62, 0, .78], [.55, 0, .86], [.65, 0, .65]): try: yield from self.move(holding_arm, eef[:3] + np.asarray(center) - button, eef[3:], 40, preserve=True) return except RuntimeError as exc: self.event('recenter_failed', error=str(exc)) raise RuntimeError('held_radio_recenter_infeasible')
def run(self): """Restart at the measured current phase, never at an assumed initial state.""" failures = [] orientation_attempt = 0 try: for cycle in range(6): self.refresh() phase = entry_phase(self.context) self.event('strategy', entry=phase, cycle=cycle) holding = next((arm for arm, name in self.context['held'].items() if name == self.context['radio_name']), None) holders = [arm for arm, name in self.context['held'].items() if name == self.context['radio_name']] if len(holders) == 2: primary = self.primary_holder or holding try: self.execute(self.release_secondary_grasp(primary)) except RuntimeError as exc: self.writer.reject_actions(self.primitive_start, str(exc)) failures.append(dict(strategy='release_secondary_grasp', error=str(exc), step=self.steps)) self.event('strategy_failed', name='release_secondary_grasp', error=str(exc)) # Re-evaluate the measured grasp even if the retreat was blocked. holding = next((arm for arm, name in self.context['held'].items() if name == self.context['radio_name']), None) if sum(name == self.context['radio_name'] for name in self.context['held'].values()) == 2: continue self.primary_holder = holding if holding: arm = 'right' if holding == 'left' else 'left' variant = orientation_attempt orientation_attempt += 1 strategies = [('free_hand_clear', lambda: self.clear_free_hand(holding)), ('held_reorient', lambda: self.reorient(holding, variant)), ('held_press', lambda: self.press(arm)), ('held_recenter', lambda: self.recenter(holding)), ('held_press_recentered', lambda: self.press(arm))] if cycle == 0: # A restored held state may already expose the button. # Do not first force it through a canonical orientation. strategies.insert(0, ('held_press_current', lambda: self.press(arm))) else: strategies = [('grounded_grasp', self.grounded_grasp), ('supported_press', lambda: self.press('right')), ('supported_press_left', lambda: self.press('left')), ('navigate', self.navigate), ('supported_press_near', lambda: self.press('right')), ('original_grasp_and_press', lambda: RadioPolicy.run(self))] if phase == 'recover_floor': strategies = [('floor_approach', self.navigate), ('floor_press', lambda: self.press('left')), ('floor_press_right', lambda: self.press('right')), ('floor_grasp', self.grounded_grasp)] for name, make in strategies: self.event('strategy', name=name) began = self.steps try: self.execute(make()) except RuntimeError as exc: self.writer.reject_actions(began, str(exc)) failures.append(dict(strategy=name, error=str(exc), step=self.steps)) self.event('strategy_failed', name=name, error=str(exc)) current_held = next((arm for arm, obj in self.context['held'].items() if obj == self.context['radio_name']), None) if (current_held != holding or sum(obj == self.context['radio_name'] for obj in self.context['held'].values()) == 2): self.grippers = array(hold_action(self.env.robots[0]))[[14, 22]].tolist() break return dict(success=False, status='teacher_failure', error='recovery_strategies_exhausted', attempts=failures) except GoalReached: return dict(success=True, status='completed', attempts=failures)1"""Pinned compatibility code; see PROVENANCE.md."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524{ "provenance": { "generator": "tools/generate_fork_category_states.py", "fork_omnigibson_commit": "55a7944da", "bddl_version": "3.7.0", "assets_root": "/home/user/dataset/embodiedClaw_v392_data_root/behavior-1k-assets/objects", "n_scene_files_validated": 702, "n_pairs_observed": 121, "gated_abilities_excluded": "requirement-gated (gm.USE_GPU_DYNAMICS off in eval)" }, "models": { "armchair/axcwcm": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "background/gkemae": { "non_kin_stub": {}, "gated": [] }, "bar/byvbuc": { "non_kin_stub": {}, "gated": [] }, "bar/egwapq": { "non_kin_stub": {}, "gated": [] }, "bathtub/rufepf": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "bed/klcjcy": { "non_kin_stub": {}, "gated": [] }, "bed/siuxgz": { "non_kin_stub": {}, "gated": [] }, "bed/tjfzsb": { "non_kin_stub": {}, "gated": [] }, "bookcase/bsvnni": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "bookcase/eckdny": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "bookcase/kdnyfh": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "bookcase/kmuacd": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "bookcase/opryhp": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "bookcase/otwukr": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "bottom_cabinet/jhymlr": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "bottom_cabinet/nddvba": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "bottom_cabinet/qacthv": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "bottom_cabinet/rhdbzv": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "bottom_cabinet_no_top/ncgmqr": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "bowl/adciys": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "breakfast_table/xftrki": { "non_kin_stub": {}, "gated": [] }, "burner/mdanhg": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 } }, "gated": [] }, "bush/cwsigt": { "non_kin_stub": { "ModifiedParticles": { "n_systems": 0 }, "Saturated": { "n_systems": 0, "default_visual_particle_limit": 0, "default_physical_particle_limit": 0 }, "ParticleRemover": { "current_step": 0 } }, "gated": [] }, "bush/frqici": { "non_kin_stub": { "ModifiedParticles": { "n_systems": 0 }, "Saturated": { "n_systems": 0, "default_visual_particle_limit": 0, "default_physical_particle_limit": 0 }, "ParticleRemover": { "current_step": 0 } }, "gated": [] }, "bush/kjakgd": { "non_kin_stub": { "ModifiedParticles": { "n_systems": 0 }, "Saturated": { "n_systems": 0, "default_visual_particle_limit": 0, "default_physical_particle_limit": 0 }, "ParticleRemover": { "current_step": 0 } }, "gated": [] }, "bush/knspbi": { "non_kin_stub": { "ModifiedParticles": { "n_systems": 0 }, "Saturated": { "n_systems": 0, "default_visual_particle_limit": 0, "default_physical_particle_limit": 0 }, "ParticleRemover": { "current_step": 0 } }, "gated": [] }, "bush/kyghri": { "non_kin_stub": { "ModifiedParticles": { "n_systems": 0 }, "Saturated": { "n_systems": 0, "default_visual_particle_limit": 0, "default_physical_particle_limit": 0 }, "ParticleRemover": { "current_step": 0 } }, "gated": [] }, "bush/lfyqkj": { "non_kin_stub": { "ModifiedParticles": { "n_systems": 0 }, "Saturated": { "n_systems": 0, "default_visual_particle_limit": 0, "default_physical_particle_limit": 0 }, "ParticleRemover": { "current_step": 0 } }, "gated": [] }, "bush/oedeqi": { "non_kin_stub": { "ModifiedParticles": { "n_systems": 0 }, "Saturated": { "n_systems": 0, "default_visual_particle_limit": 0, "default_physical_particle_limit": 0 }, "ParticleRemover": { "current_step": 0 } }, "gated": [] }, "bush/pjhpwk": { "non_kin_stub": { "ModifiedParticles": { "n_systems": 0 }, "Saturated": { "n_systems": 0, "default_visual_particle_limit": 0, "default_physical_particle_limit": 0 }, "ParticleRemover": { "current_step": 0 } }, "gated": [] }, "bush/yhjhta": { "non_kin_stub": { "ModifiedParticles": { "n_systems": 0 }, "Saturated": { "n_systems": 0, "default_visual_particle_limit": 0, "default_physical_particle_limit": 0 }, "ParticleRemover": { "current_step": 0 } }, "gated": [] }, "can_of_soda/itolcg": { "non_kin_stub": {}, "gated": [] }, "can_of_soda/lugwcz": { "non_kin_stub": {}, "gated": [] }, "car/ssxsje": { "non_kin_stub": { "Temperature": { "temperature": 0 }, "AttachedTo": { "attached_obj_uuid": -1 } }, "gated": [] }, "car/xxsgpq": { "non_kin_stub": { "Temperature": { "temperature": 0 }, "AttachedTo": { "attached_obj_uuid": -1 } }, "gated": [] }, "ceilings/alydei": { "non_kin_stub": {}, "gated": [] }, "ceilings/aoekre": { "non_kin_stub": {}, "gated": [] }, "ceilings/feolie": { "non_kin_stub": {}, "gated": [] }, "ceilings/gznlyj": { "non_kin_stub": {}, "gated": [] }, "ceilings/isizwh": { "non_kin_stub": {}, "gated": [] }, "ceilings/kbxtoc": { "non_kin_stub": {}, "gated": [] }, "ceilings/laeuzw": { "non_kin_stub": {}, "gated": [] }, "ceilings/mbrukp": { "non_kin_stub": {}, "gated": [] }, "ceilings/qhcqdn": { "non_kin_stub": {}, "gated": [] }, "ceilings/sbkyof": { "non_kin_stub": {}, "gated": [] }, "ceilings/srlfnq": { "non_kin_stub": {}, "gated": [] }, "ceilings/vkfllw": { "non_kin_stub": {}, "gated": [] }, "charcoal_grill/crdaeu": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 }, "Temperature": { "temperature": 0 } }, "gated": [] }, "coffee_table/koagbh": { "non_kin_stub": {}, "gated": [] }, "coffee_table/osroux": { "non_kin_stub": {}, "gated": [] }, "countertop/tpuwys": { "non_kin_stub": {}, "gated": [] }, "decorative_sign/hgonwj": { "non_kin_stub": {}, "gated": [] }, "decorative_sign/rypeha": { "non_kin_stub": {}, "gated": [] }, "decorative_sign/xzsmxq": { "non_kin_stub": {}, "gated": [] }, "desk/aduafr": { "non_kin_stub": {}, "gated": [] }, "desk/iotfzl": { "non_kin_stub": {}, "gated": [] }, "desk/uqcmzf": { "non_kin_stub": {}, "gated": [] }, "dishwasher/ynrhuk": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 }, "Temperature": { "temperature": 0 } }, "gated": [] }, "door/bexenl": { "non_kin_stub": {}, "gated": [] }, "door/dlncrt": { "non_kin_stub": {}, "gated": [] }, "door/pevmgl": { "non_kin_stub": {}, "gated": [] }, "door/pxhbim": { "non_kin_stub": {}, "gated": [] }, "door/vudhlc": { "non_kin_stub": {}, "gated": [] }, "downlight/fisfbn": { "non_kin_stub": {}, "gated": [] }, "downlight/pawfmw": { "non_kin_stub": {}, "gated": [] }, "downlight/pxrmnt": { "non_kin_stub": {}, "gated": [] }, "downlight/vlplia": { "non_kin_stub": {}, "gated": [] }, "driveway/umalys": { "non_kin_stub": {}, "gated": [] }, "drop_in_sink/hecjnt": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 }, "Temperature": { "temperature": 0 } }, "gated": [ "particleSink", "particleSource" ] }, "drop_in_sink/lkklqs": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 }, "Temperature": { "temperature": 0 } }, "gated": [ "particleSink", "particleSource" ] }, "electric_switch/strbnw": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 } }, "gated": [] }, "fixed_window/etjpqr": { "non_kin_stub": {}, "gated": [] }, "fixed_window/kvdqep": { "non_kin_stub": {}, "gated": [] }, "fixed_window/lhzwtz": { "non_kin_stub": {}, "gated": [] }, "floor_lamp/mqfdjk": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 } }, "gated": [] }, "floor_lamp/ogolip": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 } }, "gated": [] }, "floors/dcxicr": { "non_kin_stub": {}, "gated": [] }, "floors/ghetev": { "non_kin_stub": {}, "gated": [] }, "floors/irvmpb": { "non_kin_stub": {}, "gated": [] }, "floors/iwsyoz": { "non_kin_stub": {}, "gated": [] }, "floors/nbxnpk": { "non_kin_stub": {}, "gated": [] }, "floors/nlswvt": { "non_kin_stub": {}, "gated": [] }, "floors/ogynye": { "non_kin_stub": {}, "gated": [] }, "floors/qadhjb": { "non_kin_stub": {}, "gated": [] }, "floors/rfqizg": { "non_kin_stub": {}, "gated": [] }, "floors/sdejoi": { "non_kin_stub": {}, "gated": [] }, "floors/slmyas": { "non_kin_stub": {}, "gated": [] }, "floors/tfuahz": { "non_kin_stub": {}, "gated": [] }, "floors/ulujpr": { "non_kin_stub": {}, "gated": [] }, "floors/xkkysf": { "non_kin_stub": {}, "gated": [] }, "floors/xorxro": { "non_kin_stub": {}, "gated": [] }, "floors/zqjkvm": { "non_kin_stub": {}, "gated": [] }, "floors/zrhxwn": { "non_kin_stub": {}, "gated": [] }, "folderal/ydrlth": { "non_kin_stub": {}, "gated": [] }, "fridge/petcxr": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "furniture_sink/ojjqku": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 }, "Temperature": { "temperature": 0 } }, "gated": [ "particleSink", "particleSource" ] }, "garage_door/prdjyt": { "non_kin_stub": {}, "gated": [] }, "garden_chair/cottya": { "non_kin_stub": {}, "gated": [] }, "garden_chair/lraplz": { "non_kin_stub": {}, "gated": [] }, "garden_light/qyfrwj": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 } }, "gated": [] }, "hall_tree/daxzaw": { "non_kin_stub": {}, "gated": [] }, "hall_tree/upkvgr": { "non_kin_stub": {}, "gated": [] }, "hook/akwlam": { "non_kin_stub": {}, "gated": [] }, "lawn/aztwla": { "non_kin_stub": {}, "gated": [] }, "lawn/srfikq": { "non_kin_stub": {}, "gated": [] }, "lawn/tiqndr": { "non_kin_stub": {}, "gated": [] }, "lawn/zjtrpt": { "non_kin_stub": {}, "gated": [] }, "map/fdtxut": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "map/hsbtqi": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "microwave/hjjxmi": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 }, "Temperature": { "temperature": 0 } }, "gated": [] }, "mirror/edxfnt": { "non_kin_stub": {}, "gated": [] }, "mirror/ovdinr": { "non_kin_stub": {}, "gated": [] }, "motion_sensor/aecflf": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 } }, "gated": [] }, "mousetrap/mwfwsv": { "non_kin_stub": {}, "gated": [] }, "nightstand/aykehx": { "non_kin_stub": {}, "gated": [] }, "nightstand/roxnbe": { "non_kin_stub": {}, "gated": [] }, "nightstand/uzxrlg": { "non_kin_stub": {}, "gated": [] }, "ottoman/qsnawv": { "non_kin_stub": {}, "gated": [] }, "oven/ffitak": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 }, "Temperature": { "temperature": 0 } }, "gated": [] }, "painting/eexydp": { "non_kin_stub": {}, "gated": [] }, "painting/jfkvxh": { "non_kin_stub": {}, "gated": [] }, "painting/ljabhq": { "non_kin_stub": {}, "gated": [] }, "paver/eskaca": { "non_kin_stub": {}, "gated": [] }, "paver/lmdfdn": { "non_kin_stub": {}, "gated": [] }, "paver/sekqqq": { "non_kin_stub": {}, "gated": [] }, "picture/abtgvz": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/aicjaq": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/aqahkx": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/bzmdxc": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/ekagyj": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/ggajdz": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/hffaxw": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/hyjqxp": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/jnecmu": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/jovfqj": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/nxjgqw": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/nxqoed": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/nzctlq": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/qlkknu": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/qlsyco": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/rypaxo": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/svpzro": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/trqgni": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/ttwhjj": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/tveyoh": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/vezfau": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/xnuynn": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/yrkfct": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "picture/yzbpie": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "pizza/vyfhkm": { "non_kin_stub": { "Temperature": { "temperature": 0 }, "MaxTemperature": { "max_temperature": 0 } }, "gated": [] }, "plate/itoeew": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "playground/xdlcdi": { "non_kin_stub": {}, "gated": [] }, "radio/wxnicr": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 } }, "gated": [] }, "rail_fence/owbrvb": { "non_kin_stub": {}, "gated": [] }, "railing/pqzbbb": { "non_kin_stub": {}, "gated": [] }, "range_hood/xvdfpp": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 } }, "gated": [] }, "roof/pgwmer": { "non_kin_stub": {}, "gated": [] }, "room_divider/bydmct": { "non_kin_stub": {}, "gated": [] }, "room_light/eqbjaz": { "non_kin_stub": {}, "gated": [] }, "room_light/kiuayi": { "non_kin_stub": {}, "gated": [] }, "serving_cart/vvtcby": { "non_kin_stub": {}, "gated": [] }, "shelf/sapyzl": { "non_kin_stub": {}, "gated": [] }, "shelf/vanltx": { "non_kin_stub": {}, "gated": [] }, "shower/giialz": { "non_kin_stub": {}, "gated": [ "particleSink" ] }, "showerhead/afoeoa": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 } }, "gated": [] }, "showerhead/svuhzb": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 } }, "gated": [] }, "sofa/frlxgz": { "non_kin_stub": { "ModifiedParticles": { "n_systems": 0 }, "Saturated": { "n_systems": 0, "default_visual_particle_limit": 0, "default_physical_particle_limit": 0 }, "ParticleRemover": { "current_step": 0 } }, "gated": [] }, "sofa/ukfaaz": { "non_kin_stub": { "ModifiedParticles": { "n_systems": 0 }, "Saturated": { "n_systems": 0, "default_visual_particle_limit": 0, "default_physical_particle_limit": 0 }, "ParticleRemover": { "current_step": 0 } }, "gated": [] }, "stairs/tikozn": { "non_kin_stub": {}, "gated": [] }, "standing_mirror/wwkuuf": { "non_kin_stub": {}, "gated": [] }, "straight_chair/hgunnf": { "non_kin_stub": {}, "gated": [] }, "straight_chair/uofiqj": { "non_kin_stub": {}, "gated": [] }, "straight_chair/zdhnyg": { "non_kin_stub": {}, "gated": [] }, "swing_set/yzhrgz": { "non_kin_stub": {}, "gated": [] }, "swivel_chair/iiihwn": { "non_kin_stub": {}, "gated": [] }, "table_lamp/erfbgw": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 } }, "gated": [] }, "table_lamp/lshxmu": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 } }, "gated": [] }, "table_lamp/wbcgev": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 } }, "gated": [] }, "taboret/cgwxtq": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "toilet/udiezm": { "non_kin_stub": {}, "gated": [] }, "top_cabinet/tynnnw": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "towel_rack/qedffr": { "non_kin_stub": {}, "gated": [] }, "track_light/ltnnrc": { "non_kin_stub": {}, "gated": [] }, "trash_can/wkxtxh": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "tree/dyymaq": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "tree/flkzbo": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "tree/gmzozb": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "tree/rrhqpw": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "tree/wtyipq": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] }, "wall_mounted_light/etqbld": { "non_kin_stub": {}, "gated": [] }, "wall_mounted_light/mbhxbg": { "non_kin_stub": {}, "gated": [] }, "wall_mounted_tv/dxyfxf": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 } }, "gated": [] }, "wall_mounted_tv/sodbbr": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 } }, "gated": [] }, "wall_nail/wlnail": { "non_kin_stub": { "AttachedTo": { "attached_obj_uuid": -1 } }, "gated": [] }, "wall_socket/nujxel": { "non_kin_stub": {}, "gated": [] }, "wall_socket/plssag": { "non_kin_stub": {}, "gated": [] }, "walls/abtbfo": { "non_kin_stub": {}, "gated": [] }, "walls/bjekee": { "non_kin_stub": {}, "gated": [] }, "walls/boflea": { "non_kin_stub": {}, "gated": [] }, "walls/buhmrc": { "non_kin_stub": {}, "gated": [] }, "walls/chmqjn": { "non_kin_stub": {}, "gated": [] }, "walls/cvdpaq": { "non_kin_stub": {}, "gated": [] }, "walls/cxsmhr": { "non_kin_stub": {}, "gated": [] }, "walls/dewyls": { "non_kin_stub": {}, "gated": [] }, "walls/dlfarz": { "non_kin_stub": {}, "gated": [] }, "walls/eguptx": { "non_kin_stub": {}, "gated": [] }, "walls/epketb": { "non_kin_stub": {}, "gated": [] }, "walls/fwsbwf": { "non_kin_stub": {}, "gated": [] }, "walls/gishpf": { "non_kin_stub": {}, "gated": [] }, "walls/hcbqvq": { "non_kin_stub": {}, "gated": [] }, "walls/hddwcd": { "non_kin_stub": {}, "gated": [] }, "walls/jemunw": { "non_kin_stub": {}, "gated": [] }, "walls/jglkyp": { "non_kin_stub": {}, "gated": [] }, "walls/jnbgxj": { "non_kin_stub": {}, "gated": [] }, "walls/jpdrrk": { "non_kin_stub": {}, "gated": [] }, "walls/jzwmhx": { "non_kin_stub": {}, "gated": [] }, "walls/lblwvg": { "non_kin_stub": {}, "gated": [] }, "walls/ldoefg": { "non_kin_stub": {}, "gated": [] }, "walls/lempwq": { "non_kin_stub": {}, "gated": [] }, "walls/lovfhw": { "non_kin_stub": {}, "gated": [] }, "walls/mgumxz": { "non_kin_stub": {}, "gated": [] }, "walls/mgvxov": { "non_kin_stub": {}, "gated": [] }, "walls/miltge": { "non_kin_stub": {}, "gated": [] }, "walls/mkgplc": { "non_kin_stub": {}, "gated": [] }, "walls/mwlvfb": { "non_kin_stub": {}, "gated": [] }, "walls/oglchp": { "non_kin_stub": {}, "gated": [] }, "walls/oiagxk": { "non_kin_stub": {}, "gated": [] }, "walls/oqrbxo": { "non_kin_stub": {}, "gated": [] }, "walls/owxeej": { "non_kin_stub": {}, "gated": [] }, "walls/paarsl": { "non_kin_stub": {}, "gated": [] }, "walls/pmygxs": { "non_kin_stub": {}, "gated": [] }, "walls/qeofms": { "non_kin_stub": {}, "gated": [] }, "walls/rrabdp": { "non_kin_stub": {}, "gated": [] }, "walls/rscyjh": { "non_kin_stub": {}, "gated": [] }, "walls/slooel": { "non_kin_stub": {}, "gated": [] }, "walls/uiloru": { "non_kin_stub": {}, "gated": [] }, "walls/umqqmh": { "non_kin_stub": {}, "gated": [] }, "walls/upttgq": { "non_kin_stub": {}, "gated": [] }, "walls/vastci": { "non_kin_stub": {}, "gated": [] }, "walls/vxveul": { "non_kin_stub": {}, "gated": [] }, "walls/weybsr": { "non_kin_stub": {}, "gated": [] }, "walls/wjblrc": { "non_kin_stub": {}, "gated": [] }, "walls/xsubff": { "non_kin_stub": {}, "gated": [] }, "walls/xyrbgy": { "non_kin_stub": {}, "gated": [] }, "walls/ylpkth": { "non_kin_stub": {}, "gated": [] }, "walls/ynhwyn": { "non_kin_stub": {}, "gated": [] }, "walls/zdhaff": { "non_kin_stub": {}, "gated": [] }, "walls/zlekao": { "non_kin_stub": {}, "gated": [] }, "washer/ziomqg": { "non_kin_stub": { "ToggledOn": { "value": 0, "hand_in_marker_steps": 0 }, "Temperature": { "temperature": 0 } }, "gated": [] }, "wood_fireplace/gpnsij": { "non_kin_stub": { "Temperature": { "temperature": 0 } }, "gated": [] } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522"""Sim-free decoder for fork-era (og51 / 2025-challenge) flat per-step states.
Fork-recorded episode HDF5s store ``data/demo_0/state`` rows produced by thefork's ``og.sim.serialize``. v3.9's ``deserialize`` cannot parse them (therobot's controller block layout and AG block drifted, desyncing every objectafter the robot), and the previous workaround was to boot the og51 stack justto materialize a structured snapshot.This module reconstructs the STRUCTURED fork state dict (the fork's``og.sim.dump_state(serialized=False)`` shape) from a flat row with nosimulator at all, so the existing translate/load path(``embodiedClaw_compat.fork_state``) can seed v3.9 directly from the old HDF5.
Layout, traced from the fork sources (registry_utils/scene_base/entity_prim/stateful_object/controllable_object/manipulation_robot) and verified by strictfull-row walks that consume every float of every row:
sim row := scene_pos(3) scene_ori(4) <master registry> master reg := n=2, uuid("system_registry"), <sys reg>, uuid("object_registry"), <obj reg> registry := n_entries, { entity_uuid, <entity blob> } * n_entries entity := is_asleep(1) root_link(13 dynamic | 7 kinematic) [joint_pos(N) joint_vel(N)] (articulated) [controllers...] (robots) <non_kin states> (dispatch table below) [AG block] (robots; absent on recordings predating AG serialization) controller := goal_is_valid(1) goal(goal_dim) [past_samples(5*obs_dim) current_idx(1) fully_filled(1)] (vel_filter) AG block := sentinel(-987654.0) { has(1) obj_uuid(1) link_idx(1) contact_pos(3) } * n_arms
Flat entity order is entity -> controllers -> non_kin -> AG (BaseRobot's MROplaces ControllableObject.serialize inside StatefulObject's super() call).
Per-entity layouts come from the episode's ``scene_file`` (task-relevantobject templates incl. the robot's controller order/args). Objects with notemplate (background objects that were awake early in the episode) are sizedby scanning to the next known uuid anchor: root pose/velocities are kept, andjoints too when the caller supplies joint counts (e.g. from the live v3.9scene); an unnamed non-kin tail is dropped and reported via``unresolved_tails``. Decoding is strict everywhere else — any anchor or countmismatch raises ``ForkDecodeError`` instead of guessing.
AG params are emitted in serialized form (``ag_obj_uuid``/``ag_link_idx``/``contact_pos``); resolve them against a live scene with``embodiedClaw_compat.fork_state.resolve_serialized_ag`` before loading."""
from __future__ import annotations
import jsonfrom hashlib import md5from typing import Any, Dict, List, Mapping, Optional, Tuple
__all__ = [ "ForkDecodeError", "ForkStateLayout", "get_uuid", "is_fork_scene_file", "load_model_states", "load_scene_file", "peel_json",]
_MODEL_STATES_CACHE: Optional[Dict[str, Any]] = None
def load_model_states() -> Dict[str, Any]: """Load the packaged per-(category/model) fork non-kin templates.
Generated by ``tools/generate_fork_category_states.py`` with the fork's own object_states machinery (bddl 3.7 abilities, asset meta links) and validated against every observed scene_file template. Lets the decoder recover joints AND named non-kin states for objects that have no scene_file template. Returns ``{}`` when the data file is absent. """ global _MODEL_STATES_CACHE if _MODEL_STATES_CACHE is None: import os
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "fork_category_states.json") if os.path.exists(path): with open(path, "r", encoding="utf-8") as f: _MODEL_STATES_CACHE = json.load(f).get("models", {}) else: _MODEL_STATES_CACHE = {} return _MODEL_STATES_CACHE
AG_SENTINEL = -987654.0_AG_ARM_BLOCK = 6 # has(1) obj_uuid(1) link_idx(1) contact_pos(3)_GRIPPER_FILTER_WIDTH = 5 # fork MultiFingerGripperController MovingAverageFilter
class ForkDecodeError(RuntimeError): """A flat row does not match the computed fork layout (fail closed)."""
# Controller dof counts per robot class, used only when the recording's# init_info controller args predate dof_idx being recorded. Class facts (fork# robot definitions: base = 3 holonomic virtual dofs (x, y, rz), 4 torso# joints, 7 per arm, 2 per parallel-jaw gripper); any mismatch fails the# strict full-row walk rather than decoding garbage._FALLBACK_DOF_COUNTS = { "R1Pro": {"base": 3, "trunk": 4, "arm_left": 7, "arm_right": 7, "gripper_left": 2, "gripper_right": 2},}
def get_uuid(name: str, n_digits: int = 8) -> int: """float32(int(md5(name),16) % 1e8) — matches the fork's python_utils.get_uuid.""" import numpy as np
return int(np.float32(int(md5(name.encode()).hexdigest(), 16) % (10**n_digits)).item())
def peel_json(value: Any, max_layers: int = 6) -> Any: """Undo repeated json.dumps layers (recorders double-encode scene_file).""" for _ in range(max_layers): if not isinstance(value, str): break try: value = json.loads(value) except (TypeError, ValueError): break return value
def load_scene_file(hdf5_path: str, meta_path: Optional[str] = None) -> Dict[str, Any]: """Read the episode's scene_file dict from the meta json sidecar (newer fork recordings) or the HDF5 ``data`` attrs (older recordings).""" if meta_path is not None: with open(meta_path, "r", encoding="utf-8") as f: meta = json.load(f) if "scene_file" in meta: scene_file = peel_json(meta["scene_file"]) if isinstance(scene_file, Mapping): return dict(scene_file) import h5py
with h5py.File(hdf5_path, "r") as f: if "scene_file" in f["data"].attrs: scene_file = peel_json(f["data"].attrs["scene_file"]) if isinstance(scene_file, Mapping): return dict(scene_file) raise ForkDecodeError(f"no scene_file found for {hdf5_path} (meta json or hdf5 data attrs)")
def is_fork_scene_file(scene_file: Mapping[str, Any]) -> bool: """True when the recording stack predates official v3.9 (fork og51 stamps "3.8.0", the original 2025-challenge stack "1.2.0-alpha").""" version = str(((scene_file.get("versions") or {}).get("omnigibson") or {}).get("version") or "") parts = version.split(".") try: major, minor = int(parts[0]), int(parts[1].split("-")[0]) except (IndexError, ValueError): raise ForkDecodeError(f"unparseable omnigibson version stamp in scene_file: {version!r}") return (major, minor) < (3, 9)
# --------------------------------------------------------------------------# non-kin state decoders: name -> fn(row, i, template_entry) -> (value, next_i)# Sizes verified against the fork's object_states sources. The particle states# are self-describing (leading n_systems count); nonzero system references# cannot be resolved sim-free and fail closed.# --------------------------------------------------------------------------def _dec_toggled_on(row, i, tmpl): return {"value": bool(round(float(row[i]))), "hand_in_marker_steps": int(round(float(row[i + 1])))}, i + 2
def _dec_attached_to(row, i, tmpl): return {"attached_obj_uuid": int(round(float(row[i])))}, i + 1
def _dec_particle_modifier(row, i, tmpl): return {"current_step": int(round(float(row[i])))}, i + 1
def _dec_modified_particles(row, i, tmpl): n_systems = int(round(float(row[i]))) if n_systems: raise ForkDecodeError(f"ModifiedParticles with {n_systems} active systems is not decodable sim-free") return {"n_systems": 0}, i + 1
def _dec_saturated(row, i, tmpl): n_systems = int(round(float(row[i]))) if n_systems: raise ForkDecodeError(f"Saturated with {n_systems} whitelisted systems is not decodable sim-free") return { "n_systems": 0, "default_visual_particle_limit": int(round(float(row[i + 1]))), "default_physical_particle_limit": int(round(float(row[i + 2]))), }, i + 3
def _dec_tensorized_scalar(row, i, tmpl): keys = list(tmpl.keys()) if len(keys) != 1: raise ForkDecodeError(f"tensorized state template has {len(keys)} keys, expected 1: {keys}") return {keys[0]: float(row[i])}, i + 1
def _dec_slicer_active(row, i, tmpl): value_key = next(iter(tmpl.keys())) return { value_key: bool(round(float(row[i]))), "previously_touching": bool(round(float(row[i + 1]))), "delay_counter": int(round(float(row[i + 2]))), }, i + 3
_NON_KIN_DECODERS = { "ToggledOn": _dec_toggled_on, "AttachedTo": _dec_attached_to, "ParticleRemover": _dec_particle_modifier, "ParticleApplier": _dec_particle_modifier, "ParticleSource": _dec_particle_modifier, "ParticleSink": _dec_particle_modifier, "ModifiedParticles": _dec_modified_particles, "Saturated": _dec_saturated, "Temperature": _dec_tensorized_scalar, "MaxTemperature": _dec_tensorized_scalar, "SlicerActive": _dec_slicer_active,}
def _controller_specs(scene_file: Mapping[str, Any], robot_name: str) -> List[Tuple[str, int, int]]: """Per-controller (name, goal_dim, vel_filter_len) in serialization order.
Order and vel_filter presence come from the robot's scene_file state template; goal dims from the recorded init_info controller args (JointController-family goal is {"target": (len(dof_idx),)}, MultiFingerGripperController binary/smooth is 1).""" template = scene_file["state"]["registry"]["object_registry"][robot_name] init_info = (scene_file.get("objects_info") or {}).get("init_info") or scene_file.get("init_info") or {} robot_info = init_info.get(robot_name) or {} args = (robot_info.get("args") or {}).get("controller_config") or {} fallback = _FALLBACK_DOF_COUNTS.get(str(robot_info.get("class_name")), {}) specs: List[Tuple[str, int, int]] = [] for cname, cstate in template["controllers"].items(): cargs = args.get(cname) if not isinstance(cargs, Mapping): raise ForkDecodeError(f"no recorded init_info controller args for {robot_name}.{cname}") cls, mode = cargs.get("name"), cargs.get("mode") n_dofs = len(cargs["dof_idx"]) if cargs.get("dof_idx") else fallback.get(cname, 0) if not n_dofs: raise ForkDecodeError( f"cannot size {robot_name}.{cname}: no recorded dof_idx and no fallback " f"for robot class {robot_info.get('class_name')!r}" ) if cls in ("JointController", "HolonomicBaseJointController"): goal_dim = n_dofs elif cls == "MultiFingerGripperController": goal_dim = n_dofs if mode == "independent" else 1 else: raise ForkDecodeError(f"no goal-dim rule for controller class {cls!r} ({robot_name}.{cname})") vel_filter_len = (_GRIPPER_FILTER_WIDTH * n_dofs + 2) if "vel_filter" in cstate else 0 specs.append((cname, goal_dim, vel_filter_len)) return specs
class ForkStateLayout: """Precomputed per-entity decode plans for one episode's scene."""
def __init__( self, scene_file: Mapping[str, Any], joint_counts: Optional[Mapping[str, int]] = None, model_states: Optional[Mapping[str, Any]] = None, ): self._templates = scene_file["state"]["registry"]["object_registry"] self._scene_pos_ori_size = 7 inst_to_name = ((scene_file.get("metadata") or {}).get("inst_to_name") or {}) init_info = (scene_file.get("objects_info") or {}).get("init_info") or scene_file.get("init_info") or {} if model_states is None: model_states = load_model_states() # per-name derived non-kin stubs for objects without a scene_file # template, keyed off the recorded (category, model) self._derived_stubs: Dict[str, Mapping[str, Any]] = {} for name, info in init_info.items(): if name in self._templates or info.get("class_name") != "DatasetObject": continue arg = info.get("args") or {} entry = model_states.get(f"{arg.get('category')}/{arg.get('model')}") if isinstance(entry, Mapping) and not entry.get("unsupported") and "non_kin_stub" in entry: self._derived_stubs[name] = entry["non_kin_stub"] names = dict.fromkeys( list(self._templates) + [str(v) for v in inst_to_name.values() if v] + list(init_info) ) self._uuid_to_name = {get_uuid(name): name for name in names} self._registry_uuids = { get_uuid("system_registry"): "system_registry", get_uuid("object_registry"): "object_registry", } self._joint_counts = {str(k): int(v) for k, v in (joint_counts or {}).items()} self._controller_specs = { name: _controller_specs(scene_file, name) for name, tmpl in self._templates.items() if "controllers" in tmpl } self._arm_names = { name: tuple(tmpl["ag_obj_constraint_params"].keys()) for name, tmpl in self._templates.items() if "ag_obj_constraint_params" in tmpl } # background objects whose non-kin tail could not be decoded: name -> floats dropped self.unresolved_tails: Dict[str, int] = {} # untemplated objects fully decoded via a derived model template: name -> state names self.derived_decodes: Dict[str, Tuple[str, ...]] = {}
# -- row walking ------------------------------------------------------- def decode_row(self, row: Any) -> Dict[int, Dict[str, Any]]: """Decode one flat per-step row into ``{0: scene_state}`` (fork ``dump_state(serialized=False)`` vocabulary). Raises ForkDecodeError on any layout mismatch; guarantees the whole row was consumed.""" import torch as th
row = th.as_tensor(row).to(th.float32).flatten() n = row.numel() scene_state: Dict[str, Any] = {"pos": row[0:3].clone(), "ori": row[3:7].clone()} i = self._scene_pos_ori_size n_regs = self._count(row, i, "registry count") if n_regs != 2: raise ForkDecodeError(f"expected 2 sub-registries, found {n_regs}") i += 1 registry: Dict[str, Any] = {} for _ in range(n_regs): reg_name = self._registry_uuids.get(self._count(row, i, "registry uuid")) if reg_name is None: raise ForkDecodeError(f"unknown registry uuid at index {i}: {float(row[i])}") i += 1 count = self._count(row, i, f"{reg_name} entry count") i += 1 if reg_name == "system_registry": if count: raise ForkDecodeError(f"{count} active particle systems are not decodable sim-free") registry[reg_name] = {} continue entities: Dict[str, Any] = {} for _ in range(count): name = self._uuid_to_name.get(self._count(row, i, "object uuid")) if name is None: raise ForkDecodeError(f"unknown object uuid at index {i}: {float(row[i])}") i += 1 entities[name], i = self._decode_entity(row, i, name) registry[reg_name] = entities if i != n: raise ForkDecodeError(f"row not fully consumed: {i} of {n} floats") scene_state["registry"] = registry return {0: scene_state}
def try_decode_row(self, row: Any) -> Optional[Dict[int, Dict[str, Any]]]: try: return self.decode_row(row) except ForkDecodeError: return None
@staticmethod def _count(row, i, what: str) -> int: if i >= row.numel(): raise ForkDecodeError(f"row ended while reading {what} at index {i}") value = float(row[i]) if value != round(value) or value < 0: raise ForkDecodeError(f"non-integer {what} at index {i}: {value}") return int(value)
def _decode_entity(self, row, i: int, name: str) -> Tuple[Dict[str, Any], int]: template = self._templates.get(name) if template is None: return self._decode_untemplated(row, i, name) entity: Dict[str, Any] = {"is_asleep": bool(self._count(row, i, f"{name} is_asleep"))} i += 1 root: Dict[str, Any] = {"pos": row[i : i + 3].clone(), "ori": row[i + 3 : i + 7].clone()} i += 7 if "lin_vel" in template["root_link"]: root["lin_vel"], root["ang_vel"] = row[i : i + 3].clone(), row[i + 3 : i + 6].clone() i += 6 entity["root_link"] = root n_joints = len(template.get("joint_pos") or []) if n_joints: entity["joint_pos"] = row[i : i + n_joints].clone() entity["joint_vel"] = row[i + n_joints : i + 2 * n_joints].clone() i += 2 * n_joints if name in self._controller_specs: entity["controllers"], i = self._decode_controllers(row, i, name) non_kin: Dict[str, Any] = {} for state_name, state_template in (template.get("non_kin") or {}).items(): decoder = _NON_KIN_DECODERS.get(state_name) if decoder is None: raise ForkDecodeError(f"no decode rule for non-kin state {state_name!r} on {name}") non_kin[state_name], i = decoder(row, i, state_template) entity["non_kin"] = non_kin if name in self._arm_names: ag, i = self._decode_ag(row, i, self._arm_names[name]) if ag is not None: entity["ag_obj_constraint_params"] = ag return entity, i
def _decode_controllers(self, row, i: int, name: str) -> Tuple[Dict[str, Any], int]: controllers: Dict[str, Any] = {} for cname, goal_dim, vel_filter_len in self._controller_specs[name]: goal_is_valid = bool(self._count(row, i, f"{name}.{cname} goal_is_valid")) i += 1 goal = {"target": row[i : i + goal_dim].clone()} if goal_is_valid else None i += goal_dim state: Dict[str, Any] = {"goal_is_valid": goal_is_valid, "goal": goal} if vel_filter_len: obs_dim = (vel_filter_len - 2) // _GRIPPER_FILTER_WIDTH state["vel_filter"] = { "past_samples": row[i : i + vel_filter_len - 2].clone().reshape(_GRIPPER_FILTER_WIDTH, obs_dim), "current_idx": self._count(row, i + vel_filter_len - 2, f"{name}.{cname} filter idx"), "fully_filled": bool(self._count(row, i + vel_filter_len - 1, f"{name}.{cname} filter fill")), } i += vel_filter_len controllers[cname] = state return controllers, i
def _decode_ag(self, row, i: int, arm_names: Tuple[str, ...]) -> Tuple[Optional[Dict[str, Any]], int]: # Recordings made before the fork's AG-serialization change carry no # block at all (mirrors the fork deserializer's sentinel check). if i >= row.numel() or float(row[i]) != AG_SENTINEL: return None, i i += 1 ag: Dict[str, Any] = {} for arm in arm_names: block = row[i : i + _AG_ARM_BLOCK] i += _AG_ARM_BLOCK if float(block[0]) > 0.5: ag[arm] = { "ag_obj_uuid": int(round(float(block[1]))), "ag_link_idx": int(round(float(block[2]))), "contact_pos": block[3:6].clone(), } else: ag[arm] = {} return ag, i
def _decode_untemplated(self, row, i: int, name: str) -> Tuple[Dict[str, Any], int]: """Anchor-sized decode for objects absent from the scene_file template.
With a derived model template (packaged per-(category, model) table) the block is fully determined: the state sizes fix the joint count by arithmetic and every float decodes to a named field. Otherwise keep root state (and joints when the caller supplied a count) and drop the unnamed non-kin tail.""" entity: Dict[str, Any] = {"is_asleep": bool(self._count(row, i, f"{name} is_asleep"))} i += 1 end = self._next_anchor(row, i) block = end - i stub = self._derived_stubs.get(name) if stub is not None and block >= 13: derived = self._try_derived_decode(row, i, end, name, stub) if derived is not None: entity.update(derived) self.derived_decodes[name] = tuple(stub) return entity, end if block < 7: raise ForkDecodeError(f"untemplated object {name} block too small: {block} floats") root: Dict[str, Any] = {"pos": row[i : i + 3].clone(), "ori": row[i + 3 : i + 7].clone()} consumed = 7 if block >= 13: root["lin_vel"], root["ang_vel"] = row[i + 7 : i + 10].clone(), row[i + 10 : i + 13].clone() consumed = 13 entity["root_link"] = root n_joints = self._joint_counts.get(name, 0) if n_joints and consumed + 2 * n_joints <= block: entity["joint_pos"] = row[i + consumed : i + consumed + n_joints].clone() entity["joint_vel"] = row[i + consumed + n_joints : i + consumed + 2 * n_joints].clone() consumed += 2 * n_joints entity["non_kin"] = {} if block - consumed: self.unresolved_tails[name] = max(self.unresolved_tails.get(name, 0), block - consumed) return entity, end
def _try_derived_decode( self, row, i: int, end: int, name: str, stub: Mapping[str, Any] ) -> Optional[Dict[str, Any]]: """Strict decode of an untemplated dynamic block via a derived model template. The joint count follows from block arithmetic (every stub's length equals its fixed serialized size); any inconsistency — odd remainder, live joint-count disagreement, mis-sized state stream, or leftover floats — returns None so the caller falls back to the conservative skip path.""" remainder = (end - i) - 13 - sum(len(s) for s in stub.values()) if remainder < 0 or remainder % 2: return None n_joints = remainder // 2 known = self._joint_counts.get(name) if known is not None and known != n_joints: return None out: Dict[str, Any] = { "root_link": { "pos": row[i : i + 3].clone(), "ori": row[i + 3 : i + 7].clone(), "lin_vel": row[i + 7 : i + 10].clone(), "ang_vel": row[i + 10 : i + 13].clone(), } } j = i + 13 if n_joints: out["joint_pos"] = row[j : j + n_joints].clone() out["joint_vel"] = row[j + n_joints : j + 2 * n_joints].clone() j += 2 * n_joints non_kin: Dict[str, Any] = {} try: for state_name, state_stub in stub.items(): non_kin[state_name], j = _NON_KIN_DECODERS[state_name](row, j, state_stub) except (ForkDecodeError, KeyError): return None if j != end: return None out["non_kin"] = non_kin return out
def _next_anchor(self, row, i: int) -> int: n = row.numel() while i < n: value = float(row[i]) if value == round(value) and int(value) in self._uuid_to_name: return i i += 1 return n123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232"""Load fork-era (og51) complete-state snapshots into official OmniGibson v3.9.
The fork's FLAT per-step HDF5 states cannot be parsed by v3.9 — per-objectserialized layouts drifted, so ``og.sim.deserialize`` desyncs mid-vector.The pipeline's materialized complete-state snapshots (CompleteStateStore) arestructured name-keyed dicts instead, and v3.9 CAN load those once translated.
Two passes:
1. ``translate_fork_snapshot`` (pre-load): structural translation only — scene index keys ``"0"`` -> ``0``; numeric lists -> torch tensors; empty ``non_kin`` ``[]`` -> ``{}``; robot ``controllers`` ``{goal, goal_is_valid[, vel_filter]}`` -> ``controller_groups`` ``{goals, goal_set}`` (v3.9 ControllerView layout; goal key vocabulary, e.g. ``target``, is unchanged). Assisted-grasp params stay in the fork's legacy shape (``contact_pos``): v3.9's ``Robot._load_state`` legacy branch converts them at load time and ``embodiedClaw_compat.robots``' ``reestablish_assisted_grasps`` re-welds precisely afterwards.
2. ``conform_snapshot_to_live`` (post-load): project the snapshot onto the live sim's state vocabulary so it stays v3.9-serializable (parity vectors). og51's stateful-state sets differ from v3.9's (e.g. Temperature on objects v3.9 does not track), and legacy AG frame values are not representable in v3.9's serialized AG block. Per entity: keep target values for states the live object has, backfill live values for the rest; adopt the live AG params; backfill entities/registries the snapshot lacks."""
from __future__ import annotations
import copyfrom typing import Any, Dict, Mapping
__all__ = [ "translate_fork_snapshot", "conform_snapshot_to_live", "resolve_serialized_ag", "backfill_untemplated_entities",]
def backfill_untemplated_entities( snapshot: Mapping[str, Any], authoritative_initial: Mapping[Any, Any]) -> list: """Complete a sim-free-decoded snapshot (in place) so v3.9 can load it and so a load always reconstructs the same canonical world.
Two gaps are filled from the frozen config-built authoritative initial state (the same fallback the fork materializer used):
* Entities the snapshot lacks entirely (never recorded and absent from the scene_file initial state — batch-converted snapshots) are merged wholesale. Without them ``Scene._load_state`` skips those objects, which is benign on a cold seed but lets an in-place RE-seed inherit residue from the previous attempt (e.g. a background object the robot bumped), breaking duplicate-reseed identity. * Entities present but missing load-required fields — the decoder keeps only root pose/velocities for objects without a scene_file template, so a recorded articulated background object may lack ``joint_pos``/``joint_vel`` (which v3.9's ``EntityPrim._load_state`` reads unconditionally for articulated prims), and a kinematic-decoded root may lack velocities a dynamic prim's load expects.
Recorded values, controllers, non-kin, and AG params are never touched. Returns the sorted entity names that were merged or completed. """ initial_by_scene = {int(key): value for key, value in authoritative_initial.items()} touched = set() for scene_key, scene_state in snapshot.items(): initial_scene = initial_by_scene.get(int(scene_key)) if initial_scene is None: continue initial_registry = initial_scene.get("registry", {}).get("object_registry", {}) registry = scene_state.get("registry", {}).get("object_registry", {}) for name, initial_entity in initial_registry.items(): if name not in registry: registry[name] = copy.deepcopy(initial_entity) touched.add(name) for name, entity in registry.items(): initial_entity = initial_registry.get(name) if not isinstance(initial_entity, Mapping): continue if "joint_pos" in initial_entity and "joint_pos" not in entity: entity["joint_pos"] = copy.deepcopy(initial_entity["joint_pos"]) entity["joint_vel"] = copy.deepcopy(initial_entity["joint_vel"]) touched.add(name) root, initial_root = entity.get("root_link"), initial_entity.get("root_link") if isinstance(root, dict) and isinstance(initial_root, Mapping): for key, value in initial_root.items(): if key not in root: root[key] = copy.deepcopy(value) touched.add(name) return sorted(touched)
def resolve_serialized_ag(snapshot: Mapping[str, Any], scene: Any) -> None: """Resolve sim-free-decoded AG refs into the fork's legacy param dict.
``embodiedClaw_compat.fork_serialization`` cannot resolve prim paths without a scene, so it emits ``{ag_obj_uuid, ag_link_idx, contact_pos}`` per grasping arm. Rewrite those (in place) into the legacy shape that v3.9's ``Robot._load_state`` legacy branch consumes, exactly like the fork's ``ManipulationRobot.deserialize`` did: object by registry uuid, link by index into the object's links dict (same USD => same order; the common case is single-link objects where the index is 0), eef joint path from the robot. No-op for snapshots that already carry legacy params. """ import torch as th
for scene_state in snapshot.values(): registry = scene_state.get("registry", {}).get("object_registry", {}) for robot_name, entity in registry.items(): ag = entity.get("ag_obj_constraint_params") if not isinstance(ag, dict): continue for arm, params in ag.items(): if not (isinstance(params, Mapping) and "ag_obj_uuid" in params): continue obj = scene.object_registry("uuid", int(params["ag_obj_uuid"])) if obj is None: raise ValueError( f"assisted-grasp target uuid {params['ag_obj_uuid']} for " f"{robot_name}.{arm} is not in the live scene" ) links = list(obj.links.values()) link_idx = int(params["ag_link_idx"]) if link_idx >= len(links): raise ValueError( f"assisted-grasp link index {link_idx} out of range for {obj.name}" ) robot = scene.object_registry("name", robot_name) ag[arm] = { "ag_obj_prim_path": obj.prim_path, "ag_link_prim_path": links[link_idx].prim_path, "ag_joint_prim_path": f"{robot.eef_links[arm].prim_path}/ag_constraint", "contact_pos": th.as_tensor(params["contact_pos"], dtype=th.float32), }
def _to_torch(value: Any) -> Any: import torch as th
if isinstance(value, Mapping): return {key: _to_torch(item) for key, item in value.items()} if isinstance(value, list): try: return th.tensor(value, dtype=th.float32) except (TypeError, ValueError): return [_to_torch(item) for item in value] return value
def _translate_controllers(entity: Dict[str, Any]) -> None: controllers = entity.pop("controllers", None) if controllers is None: return groups: Dict[str, Any] = {} for name, state in controllers.items(): if not isinstance(state, Mapping): raise ValueError(f"fork controller state for {name!r} is not a mapping") groups[name] = { "goal_set": bool(state["goal_is_valid"]), "goals": dict(state["goal"]), } # vel_filter has no v3.9 equivalent (and the seeder reloads controllers # for the primitive session right after the state load). entity["controller_groups"] = groups
def translate_fork_snapshot(snapshot: Mapping[str, Any]) -> Dict[str, Any]: """Return a v3.9-loadable deep copy of a fork complete-state snapshot.""" result: Dict[str, Any] = {} for scene_key, scene_state in snapshot.items(): scene_state = copy.deepcopy(scene_state) registry = scene_state.get("registry", {}).get("object_registry", {}) for entity in registry.values(): if isinstance(entity.get("non_kin"), list) and not entity["non_kin"]: entity["non_kin"] = {} if "controllers" in entity: _translate_controllers(entity) result[int(scene_key)] = _to_torch(scene_state) return result
_MISSING = object()
def _project(target: Any, live: Any) -> Any: """Recursive structural projection: live vocabulary and shapes win.
- Mappings: iterate LIVE keys (fork-only keys drop — e.g. Temperature on objects v3.9 does not track, legacy AG fields); recurse per key. - Tensors: keep the target value when its shape matches; broadcast a single-element target onto the live shape (fork scalar gripper width vs v3.9 per-finger targets); otherwise adopt the live value. - Scalars/other: keep the target value when present, else live. """ import torch as th
if isinstance(live, Mapping): if not isinstance(target, Mapping): return copy.deepcopy(live) return { key: _project(target.get(key, _MISSING), live_value) for key, live_value in live.items() } if isinstance(live, th.Tensor): if isinstance(target, th.Tensor): if tuple(target.shape) == tuple(live.shape): return target if target.numel() == 1 and live.numel() >= 1: return th.full_like(live, float(target.reshape(-1)[0])) return live.clone() return live if target is _MISSING else target
def conform_snapshot_to_live( snapshot: Dict[str, Any], live_state: Mapping[Any, Any]) -> None: """Project @snapshot (in place) onto @live_state's state vocabulary.
@live_state is ``og.sim.dump_state(serialized=False)`` taken right after loading @snapshot: the world then carries every fork value v3.9 supports, so entries backfilled from live contribute zero delta to load-fidelity diagnostics. This makes the snapshot v3.9-serializable: og51's stateful state sets, AG param encoding, and goal shapes all drifted, and v3.9's serialize indexes strictly by the live objects' own vocabulary. """ for scene_key, live_scene in live_state.items(): snapshot[scene_key] = _project(snapshot.get(scene_key, _MISSING), live_scene) for scene_key in [key for key in snapshot if key not in live_state]: del snapshot[scene_key]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158{ "source_case": "episode_00003620_f002073", "source_runtime": "941dd1db02dad2b7934febd1b39b345b4494e0cb7bcd907b3d916181373ee839", "anchor_step": 65, "observed_step": 89, "calibration_proprio": [ 8.621547021903098e-05, -0.0002548636111896485, -0.00037544590304605663, -1.228742003440857, 0.037409503012895584, -0.10264366120100021, -0.8023198843002319, 0.011105997487902641, 0.8760256171226501, -0.5098469853401184, -0.007156834937632084, -0.008140124380588531, 0.02320193499326706, -0.03454063832759857, 0.8379126787185669, 0.21579907834529877, -0.08544155955314636, 0.8994569778442383, 0.1511586308479309, 0.6930659413337708, 0.10622632503509521, 0.9382355213165283, -0.21350570023059845, 0.25068995356559753, 0.0003656216140370816, 0.03696770966053009, 0.0028726235032081604, 0.0017150810454040766, -1.1217868328094482, -0.054427389055490494, 0.07597112655639648, -1.1059705018997192, -0.0008988446206785738, 0.8837236762046814, 0.20336216688156128, 0.00180852843914181, -0.01974860206246376, -0.0003673858300317079, -0.017804155126214027, -0.05926808342337608, 0.0009321836405433714, 0.015762167051434517, 0.9236979484558105, -0.22100281715393066, 0.7352176904678345, -0.06972181051969528, 0.930612325668335, 0.06277886778116226, 0.3537774085998535, 0.04999997466802597, 0.049999698996543884, 2.1436269889818504e-05, 2.371082518948242e-05, 1.0232930183410645, -1.439692735671997, -1.0230684280395508, 1.2429999515006784e-05, -0.0008858870714902878, 0.0002661350881680846, 0.003300442360341549, 0.0010310605866834521 ], "observed_proprio": [ -0.0009117194567807019, 5.717936437577009e-05, 0.0003912262327503413, -1.2802883386611938, 0.2044498175382614, -1.1732306480407715, -1.5001282691955566, 0.024430807679891586, 0.7742031812667847, -1.0592609643936157, -0.034914880990982056, -0.030753595754504204, -0.12512661516666412, -0.03616377338767052, -0.05378986895084381, -0.020931661128997803, 0.07243973016738892, 0.5342252254486084, 0.00884544849395752, 0.884623110294342, 0.7179591059684753, 0.6386969685554504, -0.20422889292240143, 0.18679256737232208, 0.00032414510496892035, 0.03718554973602295, -0.10684840381145477, -0.036140479147434235, -0.9149863123893738, 0.1743805855512619, 0.26595398783683777, -0.8236302137374878, -0.20426373183727264, 0.5730473399162292, -0.27302485704421997, 0.03440157696604729, 0.005959740839898586, -0.025288276374340057, 0.0016273200744763017, 0.02603336051106453, -0.007222221232950687, 0.04082530364394188, 0.7443113327026367, -0.031164705753326416, 0.7375836968421936, -0.06994928419589996, 0.930590808391571, 0.06270568817853928, 0.35380205512046814, 4.94706682729884e-07, 4.100954953401015e-08, 1.1562297004275024e-05, -0.001196451485157013, 0.7990342974662781, -1.375714659690857, -1.0136350393295288, 0.10436542332172394, -0.008765585720539093, -0.0007596348877996206, -0.004070611204952002, -0.0027220402844250202 ], "holding_target": [ [ 0.07061526012669758, 0.9974837400331779, 0.0062986829308048775, 0.5601520820291249 ], [ 0.8053107688560318, -0.053282220709951165, -0.5904536988797032, 0.006250802137737488 ], [ -0.5886323560608488, 0.046767438732947864, -0.8070469354830697, 0.9127131423992428 ], [ 0.0, 0.0, 0.0, 1.0 ] ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566{ "source": "v8 episode_00009930_f004300 frame0", "proprio": [ 0.0004853983409702778, 0.00029681785963475704, 0.0006303827976807952, -0.6368667483329773, -0.09203382581472397, -0.35182985663414, 0.0017121128039434552, 0.46996113657951355, -0.002493982668966055, -0.8182016015052795, 0.0004246461612638086, 0.0026403646916151047, -0.004034055396914482, -0.0025361706502735615, -2.9669608920812607e-06, -0.0005292248097248375, -0.0012191126588732004, 0.5414104461669922, 0.026944875717163086, 0.7438309788703918, 0.057091955095529556, 0.8625752329826355, -0.43816453218460083, 0.24640680849552155, 0.049875322729349136, 0.04987121373414993, -8.038755913730711e-05, -0.0003416695981286466, -0.5309996604919434, -0.06173987314105034, -0.32459694147109985, -1.0425454378128052, 0.6642840504646301, 0.4094456136226654, 0.5584911108016968, 0.0087641142308712, -0.002928845351561904, -0.00872182846069336, 0.015559806488454342, 0.2932525873184204, 0.012712670490145683, 0.015666358172893524, 0.7121121883392334, -0.3449810743331909, 0.8822637796401978, -0.16034474968910217, 0.8994651436805725, -0.05880854278802872, 0.4022357761859894, 0.03910424932837486, 5.7688666856847703e-05, -0.0014373725280165672, -0.002859571948647499, 0.6909226775169373, -0.8359125852584839, -0.27305179834365845, -5.219121248956071e-06, 0.002998537151142955, 0.006828080862760544, -0.0007685121381655335, -0.0036888381000608206 ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104import jsonfrom pathlib import Pathimport h5pyimport numpy as npimport pytest
from task00_recovery.teacher import entry_phasefrom task00_recovery.recording import EpisodeWriterfrom tools.build_cases import buildfrom tools.driver import needs_export, run_casefrom tools.download_sources import fetch
def test_teacher_never_sets_physical_state_or_goal(): import ast import inspect import task00_recovery.teacher as teacher forbidden = {'set_value', 'set_position_orientation', 'set_joint_positions', 'load_state', '_establish_grasp'} tree = ast.parse(inspect.getsource(teacher)) assert not [n.func.attr for n in ast.walk(tree) if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) and n.func.attr in forbidden]
def test_sealed_input_reuse_checks_hash_and_refuses_extension(tmp_path): import hashlib (tmp_path/'index.csv').write_bytes(b'known-input') (tmp_path/'SHA256SUMS').write_text(hashlib.sha256(b'known-input').hexdigest()+' index.csv\n') assert fetch(tmp_path, 'index.csv') == tmp_path/'index.csv' with pytest.raises(ValueError, match='sealed'): fetch(tmp_path, 'extra.hdf5') (tmp_path/'index.csv').write_bytes(b'corrupted-input') with pytest.raises(ValueError, match='checksum mismatch'): fetch(tmp_path, 'index.csv')
@pytest.mark.parametrize('held,z,success,expected', [ ({'left': None, 'right': None}, .7, False, 'recover_supported'), ({'left': None, 'right': None}, .1, False, 'recover_floor'), ({'left': 'radio', 'right': None}, .8, False, 'press_left_held'), ({'left': None, 'right': 'radio'}, .8, False, 'press_right_held'), ({'left': None, 'right': None}, .8, True, 'complete'),])def test_stage_dispatch(held, z, success, expected): assert entry_phase(dict(held=held, radio_name='radio', radio_pose=[[0, 0, z], [0, 0, 0, 1]], success=success)) == expected
def test_record_alignment_and_masks(tmp_path): writer = EpisodeWriter(tmp_path/'run', {'frame': 10}) writer.state(np.zeros(4)) obs = {'robot::rgb': np.zeros((2, 2, 3), dtype=np.uint8), 'robot::proprio': np.ones(61)} for i in range(3): writer.step(obs, np.full(23, i), {'phase': 'press'}, False, False, np.full(4, i+1)) writer.reject_actions(1, 'blocked') writer.verify_primitive(0, 'press') writer.close({'success': False}) with h5py.File(tmp_path/'run/trajectory.hdf5') as f: assert len(f['states']) == len(f['actions']) + 1 assert f['teacher/supervision_mask'][:].tolist() == [True, False, False] assert f['truncated'][:].tolist() == [False, False, True] assert f['actions'][2, 0] == 2
def test_case_dedup_and_terminal(tmp_path): (tmp_path/'index.csv').write_text('episode_id,task_id,instance_id,outcome\n00005010,0,501,failure\n00005020,0,502,failure\n') for eid in ('00005010', '00005020'): h = tmp_path/f'trajectories/task-0000/episode_{eid}.hdf5' h.parent.mkdir(parents=True, exist_ok=True) with h5py.File(h, 'w') as f: f.create_dataset('data/demo_0/action', data=np.zeros((4, 23))) f.create_dataset('data/demo_0/state', data=np.zeros((5, 10))) m = tmp_path/f'meta/task-0000/episodes/episode_{eid}.json' m.parent.mkdir(parents=True, exist_ok=True) m.write_text('{}') seed = tmp_path/'judgement/task-0000/seeds/episode_00005010.json' seed.parent.mkdir(parents=True) seed.write_text(json.dumps({'chunks': [{'seed': 2}, {'seed': 2}]})) rows = build(tmp_path) assert len(rows) == 2 assert [(c['frame'], c['start_type']) for c in rows] == [(2, 'judgement_seed'), (4, 'terminal_state')] seed.write_text(json.dumps({'chunks': [{'seed': 5}]})) with pytest.raises(ValueError, match='outside'): build(tmp_path)
def test_export_failure_is_resumable_without_simulation(tmp_path, monkeypatch): case = dict(case_id='test', path='/unused', meta='/unused', frame=2) folder = tmp_path/'test' attempt = folder/'attempt_001' attempt.mkdir(parents=True) (attempt/'outcome.json').write_text(json.dumps(dict(status='completed', success=True, steps=30))) calls = [] def fake_run(cmd, **kwargs): calls.append(cmd) assert 'export_lerobot.py' in cmd[1] return type('Result', (), {'returncode': 1})() monkeypatch.setattr('tools.driver.subprocess.run', fake_run) for _ in range(2): assert run_case(case, tmp_path, 100, 0, True, 30) == 'export_failed_retryable' assert not (folder/'complete.json').exists() assert len(calls) == 2 assert needs_export({'steps': 30}, {'passed': False}) assert not needs_export({'steps': 30}, {'passed': True})123456789101112131415161718192021222324252627282930"""Recorded terminal state: clear the free hand without moving the grasp."""import jsonfrom pathlib import Pathfrom types import SimpleNamespace
import numpy as npimport pytest
from experiments.radio_two_arm.motion import solve, predicted_jointsfrom pipeline.sensors import Sensorsfrom task00_recovery.teacher import RecoveryTeacher
def test_recorded_right_grasp_allows_left_clearance_with_fixed_holder(): fixture = json.loads((Path(__file__).parent/'fixtures/right_terminal_993.json').read_text()) obs = Sensors({'robot_r1::proprio': np.array(fixture['proprio'])}) free = obs.eef('left') target = free[:3] + [0, .16, .08] action, errors = solve(obs, 'left', target, free[3:], True) planned = predicted_joints(obs, action) assert np.linalg.norm(planned.eef('left')[:3]-target) < .008 assert np.linalg.norm(planned.eef('right')[:3]-obs.eef('right')[:3]) < .008 assert all(dr < .10 for _, dr in errors)
def test_clearance_does_not_treat_an_occupied_hand_as_free(): teacher = RecoveryTeacher.__new__(RecoveryTeacher) teacher.context = dict(held={'left': 'radio', 'right': 'radio'}, radio_name='radio') with pytest.raises(RuntimeError, match='clear_hand_is_occupied'): list(teacher.clear_free_hand('right'))123456789101112131415161718192021222324252627282930313233343536373839404142"""Regression from the actual left-held pilot: preserve its pre-press pose."""import jsonfrom pathlib import Path
import numpy as npfrom scipy.spatial.transform import Rotation
from experiments.radio_two_arm.motion import solve, predicted_jointsfrom pipeline.sensors import Sensorsfrom scripts.kinematics import Kinematicsfrom task00_recovery.teacher import RecoveryTeacher
def test_recorded_holding_deflection_is_not_rebased(): fixture = json.loads((Path(__file__).parent/'fixtures/holding_anchor.json').read_text()) kin = Kinematics() kin.calibrate(np.array(fixture['calibration_proprio'])) obs = Sensors({'robot_r1::proprio': np.array(fixture['observed_proprio'])}, kin) anchor = np.array(fixture['holding_target']) assert np.linalg.norm(obs.eef('left')[:3]-anchor[:3, 3]) > .035 free = obs.eef('right') action, _ = solve(obs, 'right', free[:3], free[3:], True, other_pose=anchor) expected = predicted_joints(obs, action) assert np.linalg.norm(expected.eef('left')[:3]-anchor[:3, 3]) < .008 assert (Rotation.from_matrix(anchor[:3, :3]).inv() * Rotation.from_quat(expected.eef('left')[3:])).magnitude() < .10 assert np.linalg.norm(expected.eef('right')[:3]-free[:3]) < .008
def test_contact_dwell_keeps_commanded_joint_targets(): teacher = RecoveryTeacher.__new__(RecoveryTeacher) teacher.phase = 'press_right' teacher.press_anchor = ('left', np.zeros(3), np.array([0, 0, 0, 1])) teacher.last_action = np.linspace(-.5, .5, 23, dtype=np.float32) teacher.grippers = [-1, -1] commands = list(teacher.wait(8)) for action in commands: np.testing.assert_array_equal(action[3:14], teacher.last_action[3:14]) np.testing.assert_array_equal(action[15:22], teacher.last_action[15:22]) np.testing.assert_array_equal(action[:3], 0) np.testing.assert_array_equal(action[[14, 22]], -1) assert not np.shares_memory(commands[0], commands[1])12345678910111213141516171819202122import numpy as npfrom task00_recovery.teacher import NavigationObservation
def test_navigation_sampling_preserves_native_recording_and_angular_density(): class Observation: def __init__(self, n): y, x = np.indices((n, n), dtype=np.float32) self.points = np.stack((x/n, y/n, np.ones_like(x)), -1) def cloud(self, camera='zed'): return self.points def eef(self, arm): return arm low, native = Observation(256), Observation(720) before = native.points.copy() expected = NavigationObservation(low).cloud()[::5, ::5] actual = NavigationObservation(native).cloud()[::5, ::5] assert actual.shape == expected.shape == (52, 52, 3) np.testing.assert_allclose(actual, expected, atol=1/720) np.testing.assert_array_equal(native.points, before) assert NavigationObservation(native).eef('left') == 'left' assert NavigationObservation(low).cloud() is low.points123456789101112131415161718192021222324from tools.centre_pilot import foreign_policy_starting, gpu_available
def test_policy_initialization_is_busy_before_cuda_allocation(tmp_path, monkeypatch): folder = tmp_path/'100' folder.mkdir() command = folder/'cmdline' command.write_bytes(b'python\0/run/scripts/serve_pi05.py\0--root\0/run/eval\0') assert foreign_policy_starting(tmp_path) monkeypatch.setattr('tools.centre_pilot.foreign_policy_starting', lambda: True) monkeypatch.setattr('tools.centre_pilot.subprocess.check_output', lambda *a, **k: (_ for _ in ()).throw(AssertionError('GPU query should not be needed'))) assert not gpu_available() assert not gpu_available(reserved=True)
def test_diagnostic_command_text_does_not_count_as_a_policy_service(tmp_path): folder = tmp_path/'100' folder.mkdir() command = folder/'cmdline' command.write_bytes(b'python\0-c\0print("serve_pi05.py")\0') assert not foreign_policy_starting(tmp_path) command.write_bytes(b'') # A just-exited process must not retain ownership. assert not foreign_policy_starting(tmp_path)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970"""Regressions for the actual terminal-state pilot failure."""import jsonfrom pathlib import Pathfrom types import SimpleNamespace
import numpy as npimport pytest
from experiments.radio_two_arm.motion import predicted_joints, solvefrom pipeline.sensors import Sensorsfrom scripts.kinematics import Kinematicsfrom task00_recovery.teacher import RecoveryTeacher
@pytest.mark.parametrize('side', [-1, 1])def test_stalled_joint_outside_urdf_limit_has_legal_retry(side): fixture = json.loads((Path(__file__).parent/'fixtures/holding_anchor.json').read_text()) kin = Kinematics() kin.calibrate(np.array(fixture['calibration_proprio'])) obs = Sensors({'robot_r1::proprio': np.array(fixture['calibration_proprio'])}, kin) limit = next(j[-1] for j in kin.joints.values() if j[0] == 'left_arm_joint6') action = obs.hold() # The recorded failure overshot the lower limit by 0.003318 radians. action[12] = limit[0 if side < 0 else 1] + side*.003318 overshot = predicted_joints(obs, action) eef = overshot.eef('left') command, errors = solve(overshot, 'left', eef[:3], eef[3:], fixed_joints=['left_arm_joint6']) assert limit[0] <= command[12] <= limit[1] assert errors[0][0] < .008 and errors[0][1] < .10
def test_secondary_release_opens_only_secondary_and_replans_from_measured_grasp(): teacher = RecoveryTeacher.__new__(RecoveryTeacher) teacher.context = dict(held={'left': 'radio', 'right': 'radio'}, radio_name='radio') teacher.grippers = [-1, -1] teacher.press_open_hands = set() teacher.last_action = None teacher.obs = SimpleNamespace(hold=lambda: np.zeros(23), eef=lambda arm: np.array([.6, -.1, .8, 0, 0, 0, 1.])) teacher.event = lambda *args, **kwargs: None movements = [] def move(arm, xyz, quat, steps, preserve): movements.append((arm, xyz, preserve)) yield np.zeros(23) teacher.move = move generator = teacher.release_secondary_grasp('left') for _ in range(20): action = next(generator) assert action[14] == -1 and action[22] == 1 assert teacher.releasing_arm == 'right' # Model the measured result of the open-gripper commands, never a state setter. teacher.context['held']['right'] = None list(generator) assert teacher.releasing_arm is None assert teacher.press_open_hands == {'right'} assert movements[0][0] == 'right' and movements[0][2] is True
def test_secondary_release_does_not_infer_release_from_elapsed_time(): teacher = RecoveryTeacher.__new__(RecoveryTeacher) teacher.context = dict(held={'left': 'radio', 'right': 'radio'}, radio_name='radio') teacher.grippers = [-1, -1] teacher.press_open_hands = set() teacher.last_action = None teacher.obs = SimpleNamespace(hold=lambda: np.zeros(23)) with pytest.raises(RuntimeError, match='secondary_grasp_release_failed'): list(teacher.release_secondary_grasp('left')) assert teacher.releasing_arm is None assert teacher.press_open_hands == set()1234567891011121314151617181920212223"""Integration checks against the tiny, explicitly selected source sample."""from pathlib import Pathimport pytestfrom task00_recovery.source import SourceEpisode
INPUTS = Path(__file__).resolve().parents[1]/'inputs'
@pytest.mark.parametrize('episode,frame,held', [('00003990', 4000, True), ('00005200', 4299, False)])def test_actual_grasp_state_takes_precedence_over_annotation(episode, frame, held): source = INPUTS/f'trajectories/task-0000/episode_{episode}.hdf5' meta = INPUTS/f'meta/task-0000/episodes/episode_{episode}.json' if not source.exists(): pytest.skip('Selected HF test source has not been downloaded') s = SourceEpisode(source, meta) snapshot, audit = s.materialize(frame) robot = snapshot[0]['registry']['object_registry']['robot_r1'] assert bool(robot['ag_obj_constraint_params']['right']) == held assert audit['prefix_rows'] == frame+1 assert audit['unresolved_tails'] == {} assert s.n_states == s.n_actions+1 with pytest.raises(IndexError): s.materialize(s.n_states)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253"""Build Task00 recovery cases from locally downloaded source episodes only."""import argparseimport csvimport jsonfrom pathlib import Pathimport h5py
def build(root): root = Path(root) cases = [] for row in csv.DictReader((root/'index.csv').open()): if int(row['task_id']) != 0 or row['outcome'] != 'failure': continue eid = row['episode_id'] source = root/f'trajectories/task-0000/episode_{eid}.hdf5' meta = root/f'meta/task-0000/episodes/episode_{eid}.json' if not source.exists() or not meta.exists(): continue with h5py.File(source) as f: n = len(f['data/demo_0/action']) if len(f['data/demo_0/state']) != n + 1: raise ValueError(f'{eid}: states must be T+1') path = root/f'judgement/task-0000/seeds/episode_{eid}.json' chunks = json.loads(path.read_text()).get('chunks', []) if path.exists() else [] seeds = {} for chunk in chunks: if chunk.get('seed') is not None: frame = int(chunk['seed']) if not 0 <= frame <= n: raise ValueError(f'{eid}: seed {frame} outside [0,{n}]') seeds.setdefault(frame, []).append(chunk) if not seeds: seeds[n] = [] for rank, (frame, annotations) in enumerate(sorted(seeds.items())): cases.append(dict(case_id=f'episode_{eid}_f{frame:06d}', episode_id=eid, instance_id=int(row['instance_id']), frame=frame, seed_rank=rank, start_type='judgement_seed' if annotations else 'terminal_state', path=str(source.resolve()), meta=str(meta.resolve()), diagnostic_only=301 <= int(row['instance_id']) <= 340, annotations=annotations)) return sorted(cases, key=lambda c: (c['seed_rank'], c['episode_id']))
if __name__ == '__main__': p = argparse.ArgumentParser(description=__doc__) p.add_argument('--inputs', type=Path, required=True) p.add_argument('--output', type=Path, required=True) a = p.parse_args() rows = build(a.inputs) a.output.parent.mkdir(parents=True, exist_ok=True) a.output.write_text(''.join(json.dumps(c)+'\n' for c in rows)) print(json.dumps(dict(cases=len(rows), episodes=len({c['episode_id'] for c in rows}))))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129"""Bounded, resumable centre pilot. Never starts the full campaign."""import argparseimport fcntlimport jsonimport osfrom pathlib import Pathimport shutilimport subprocessimport timefrom tools.driver import run_case, atomic_json
def foreign_policy_starting(proc=Path('/proc')): """Centre's evaluator spawns this service immediately after its GPU gate.
Its process exists before JAX allocates GPU memory. Checking only nvidia-smi would allow two supervisors to pass during model initialization. """ for folder in proc.iterdir(): if not folder.name.isdigit(): continue try: argv = (folder/'cmdline').read_bytes().decode(errors='replace').split('\0') except (FileNotFoundError, PermissionError, ProcessLookupError): continue if len(argv) > 1 and Path(argv[1]).name == 'serve_pi05.py': return True return False
def gpu_available(reserved=False): if foreign_policy_starting(): return False free = subprocess.check_output(['nvidia-smi', '--query-gpu=memory.free', '--format=csv,noheader,nounits'], text=True) rows = [int(x) for x in free.splitlines()] return len(rows) == 1 and rows[0] >= (16000 if reserved else 20000)
def reserve_gpu(): """Hold this bounded job's GPU across CPU exports between fresh simulators.
Centre's other workers recognize >=20000MiB free as idle. A 5GiB allocation makes ownership visible during inter-case gaps, with a >=16000MiB free gate for the measured <15000MiB simulator. Acquire after the existing job exits. The CUDA allocation is released automatically on supervisor exit. """ while True: while not gpu_available(): time.sleep(5) time.sleep(10) if not gpu_available(): continue import torch allocation = torch.empty(5*1024**3, dtype=torch.uint8, device='cuda:0') torch.cuda.synchronize() time.sleep(10) if gpu_available(reserved=True): print(json.dumps(dict(event='pilot_gpu_reserved', pid=os.getpid(), reservation_mib=5120)), flush=True) return allocation # Another worker won the acquisition race; leave its work alone. del allocation torch.cuda.empty_cache()
def case_passed(row): return ((row['outcome'].get('status') == 'already_complete' and row.get('expected') == 'already_complete') or (row['success'] and row['dataset_passed']))
def main(): p = argparse.ArgumentParser(description=__doc__) p.add_argument('--cases', type=Path, required=True) p.add_argument('--runs', type=Path, required=True) a = p.parse_args() cases = [json.loads(x) for x in a.cases.read_text().splitlines() if x.strip()] if len(cases) > 12: p.error('This pilot is bounded to twelve cases') a.runs.mkdir(parents=True, exist_ok=True) lock = (a.runs/'pilot.lock').open('a') fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) status = a.runs/'pilot_status.json' records = [] reservation = None for case in cases: while not (a.runs/case['case_id']/'complete.json').exists(): usage = shutil.disk_usage(a.runs) if usage.free < 100*1024**3 or usage.used/usage.total > .90: raise RuntimeError('pilot_storage_gate') atomic_json(status, dict(state='waiting_gpu', case=case['case_id'], completed=len(records), pid=os.getpid())) if reservation is None: reservation = reserve_gpu() while not gpu_available(reserved=True): time.sleep(30) time.sleep(10) if not gpu_available(reserved=True): continue atomic_json(status, dict(state='running', case=case['case_id'], completed=len(records), pid=os.getpid())) result = run_case(case, a.runs, 3000, 0, True, 3600) print(json.dumps(dict(case=case['case_id'], result=result)), flush=True) if result == 'complete': break if result in ('infrastructure_exhausted', 'export_failed_retryable', 'export_failed_verification', 'owned_by_other_worker'): atomic_json(status, dict(state='needs_repair', case=case['case_id'], result=result, completed=len(records))) return 2 row = json.loads((a.runs/case['case_id']/'complete.json').read_text()) records.append(row) if not case_passed(row): atomic_json(status, dict(state='needs_repair', case=case['case_id'], completed=len(records), planned=len(cases), records=records)) return 2 recovered = sum(bool(r['success']) for r in records) already = sum(r['outcome'].get('status') == 'already_complete' for r in records) expected_ok = all(case_passed(r) for r in records) atomic_json(status, dict(state='pilot_passed' if expected_ok else 'needs_repair', cases=len(records), recovered=recovered, already_complete=already, records=records)) return 0 if expected_ok else 2
if __name__ == '__main__': raise SystemExit(main())12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394"""Download explicit Task00 source episodes, never the full dataset or videos."""import argparseimport csvimport hashlibimport jsonimport shutilimport urllib.errorimport urllib.requestfrom pathlib import Path
REPO = "fastwalker1118/B1k_Rollouts"REVISION = "99d84272f5ac24ec364017ea4f60b75d0da88fba"
def fetch(root, relative, revision=REVISION, budget_gb=2.0, optional=False): root = Path(root) target = root / relative seal = root / 'SHA256SUMS' if target.exists(): if seal.exists(): expected = dict(line.split(' ', 1)[::-1] for line in seal.read_text().splitlines()) if relative not in expected or hashlib.sha256(target.read_bytes()).hexdigest() != expected[relative]: raise ValueError(f'Existing sealed input checksum mismatch: {relative}') return target if seal.exists(): if optional: return None raise ValueError('Input subset is sealed; select a new --root to download additional episodes') root.mkdir(parents=True, exist_ok=True) used = sum(p.stat().st_size for p in root.rglob("*") if p.is_file()) if shutil.disk_usage(root).free < 100 * 1024**3: raise RuntimeError("Keep at least 100 GiB free; download refused") url = f"https://huggingface.co/datasets/{REPO}/resolve/{revision}/{relative}" try: response = urllib.request.urlopen(url, timeout=90) except urllib.error.HTTPError as e: if optional and e.code == 404: return None raise target.parent.mkdir(parents=True, exist_ok=True) partial = target.with_suffix(target.suffix + ".partial") total = 0 digest = hashlib.sha256() try: with response, partial.open("wb") as out: while block := response.read(1024 * 1024): total += len(block) if used + total > budget_gb * 1e9: raise RuntimeError("Explicit download budget exceeded") if shutil.disk_usage(root).free < 100 * 1024**3: raise RuntimeError("Free disk reserve reached") digest.update(block) out.write(block) partial.replace(target) finally: partial.unlink(missing_ok=True) with (root / "downloads.jsonl").open("a") as log: log.write(json.dumps(dict(path=relative, bytes=total, sha256=digest.hexdigest(), repo=REPO, revision=revision)) + "\n") print(f"downloaded {relative} ({total / 1e6:.2f} MB)", flush=True) return target
def main(): p = argparse.ArgumentParser(description=__doc__) p.add_argument("--root", type=Path, required=True) p.add_argument("--episodes", nargs="*", default=[]) p.add_argument("--inspect-seeds", type=int, default=0, help="Fetch only this many non-public failure seed JSON files") p.add_argument("--budget-gb", type=float, default=2) a = p.parse_args() index = fetch(a.root, "index.csv", budget_gb=a.budget_gb) rows = [r for r in csv.DictReader(index.open()) if int(r["task_id"]) == 0] lookup = {r["episode_id"]: r for r in rows} failures = [r for r in rows if r["outcome"] == "failure" and int(r["instance_id"]) > 340] if a.inspect_seeds: stride = max(1, len(failures) // a.inspect_seeds) for r in failures[::stride][:a.inspect_seeds]: f = fetch(a.root, f"judgement/task-0000/seeds/episode_{r['episode_id']}.json", budget_gb=a.budget_gb, optional=True) if f: print(r["episode_id"], json.dumps(json.loads(f.read_text()).get("chunks")), flush=True) for eid in a.episodes: if eid not in lookup: raise ValueError(f"Not a task00 episode: {eid}") for category, suffix in [("meta/task-0000/episodes", "json"), ("judgement/task-0000/seeds", "json"), ("trajectories/task-0000", "hdf5")]: fetch(a.root, f"{category}/episode_{eid}.{suffix}", budget_gb=a.budget_gb, optional=category.startswith("judgement"))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116"""One sequential simulator worker per allocation; restart failed exports safely."""import argparseimport fcntlimport jsonimport osimport signalfrom pathlib import Pathimport shutilimport subprocessimport sys
ROOT = Path(__file__).resolve().parents[1]
def atomic_json(path, value): path = Path(path) tmp = path.with_suffix('.tmp') tmp.write_text(json.dumps(value, indent=2)+'\n') tmp.replace(path)
def needs_export(outcome, verification): return outcome.get('steps', 0) > 0 and not verification.get('passed', False)
def run_case(case, runs, max_steps, resolution, export, timeout): folder = runs/case['case_id'] folder.mkdir(parents=True, exist_ok=True) with (folder/'worker.lock').open('w') as lock: try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: return 'owned_by_other_worker' complete = folder/'complete.json' if complete.exists(): return 'complete' atomic_json(folder/'case.json', case) attempts = sorted(folder.glob('attempt_[0-9][0-9][0-9]')) attempt = attempts[-1] if attempts else None outcome = json.loads((attempt/'outcome.json').read_text()) if attempt and (attempt/'outcome.json').exists() else {} if not outcome or outcome.get('status') == 'infrastructure_failure': if len(attempts) >= 2: atomic_json(folder/'infrastructure_exhausted.json', outcome or {'error':'two incomplete attempts'}) return 'infrastructure_exhausted' attempt = folder/f'attempt_{len(attempts)+1:03d}' entry = os.getenv('RECOVERY_SIM_ENTRY') launcher = [sys.executable, entry, 'task00_recovery.run'] if entry else [sys.executable, '-m', 'task00_recovery.run'] command = launcher + ['--source', case['path'], '--meta', case['meta'], '--frame', str(case['frame']), '--output', str(attempt), '--max-steps', str(max_steps), '--resolution', str(resolution)] atomic_json(folder/'launch.json', dict(command=command, slurm_job=os.getenv('SLURM_JOB_ID'))) with (folder/f'{attempt.name}.log').open('w') as log: process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) try: process.wait(timeout=timeout) except subprocess.TimeoutExpired: os.killpg(process.pid, signal.SIGTERM) try: process.wait(timeout=30) except subprocess.TimeoutExpired: os.killpg(process.pid, signal.SIGKILL) process.wait() atomic_json(folder/'last_infrastructure_error.json', {'error':'simulator_timeout'}) return 'simulator_timeout' if not (attempt/'outcome.json').exists(): return 'missing_outcome' outcome = json.loads((attempt/'outcome.json').read_text()) if outcome.get('status') == 'infrastructure_failure': return 'infrastructure_failure' verification = {} if (attempt/'dataset_verification.json').exists(): verification = json.loads((attempt/'dataset_verification.json').read_text()) if export and needs_export(outcome, verification): with (attempt/'export.log').open('a') as log: command = [sys.executable, str(ROOT/'tools/export_lerobot.py'), str(attempt), '--official-info', str(ROOT/'config/official_info.json'), '--case', json.dumps(case)] result = subprocess.run(command, stdout=log, stderr=subprocess.STDOUT) if result.returncode != 0: return 'export_failed_retryable' verification = json.loads((attempt/'dataset_verification.json').read_text()) if not verification.get('passed'): return 'export_failed_verification' if not export and outcome.get('steps', 0) > 0: # Simulation-only finish stays exportable on a later --export run. atomic_json(folder/'simulation_complete.json', outcome) return 'simulation_complete' atomic_json(complete, dict(**case, outcome=outcome, verification=verification, attempt=str(attempt), success=bool(outcome.get('success')), dataset_passed=verification.get('passed', False))) return 'complete'
def main(): p = argparse.ArgumentParser(description=__doc__) p.add_argument('--cases', type=Path, required=True) p.add_argument('--runs', type=Path, required=True) p.add_argument('--shard', type=int, default=0) p.add_argument('--shards', type=int, default=1) p.add_argument('--max-steps', type=int, default=3000) p.add_argument('--resolution', type=int, default=256) p.add_argument('--timeout', type=int, default=3600) p.add_argument('--export', action='store_true') a = p.parse_args() if not 0 <= a.shard < a.shards: p.error('Require 0 <= shard < shards') if a.export and a.resolution != 0: p.error('Native LeRobot export requires --resolution 0') a.runs.mkdir(parents=True, exist_ok=True) cases = [json.loads(s) for s in a.cases.read_text().splitlines() if s.strip()] for case in cases[a.shard::a.shards]: if shutil.disk_usage(a.runs).free < 100*1024**3: raise RuntimeError('100 GiB free-disk reserve reached') print(case['case_id'], run_case(case, a.runs, a.max_steps, a.resolution, a.export, a.timeout), flush=True)
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304#!/usr/bin/env python3"""Export one teacher run (trajectory.hdf5) to the Task-00 aligned LeRobot v3 layout.
Schema is taken from the same official_info.json the Task-00 production recorderused (30 Hz, 61-D state, 23-D action, 3 x 7-D robot2cam_pose, 3 RGB + 3 depth video;wrist 480x480, head 720x720). RGB encoding is identical to Task 00. Depth uses theofficial human-demo settings (HEVC gray12le, CRF 0, GOP 8, no B-frames) instead of theTask-00 default (CRF 30, GOP 2, B-frames 4) that its report flagged as lossy.
Episode semantics follow Task 00: a successful episode ends at the first step whoseBDDL goal is satisfied (reward 1, terminated True on that frame only); the teacher'spost-success settling tail is not exported. A failed run keeps every recorded step andmarks truncated True on its last frame.
Also writes a 768x336 composite video.mp4 (head | left wrist | right wrist) of everyexported frame, preview.jpg, and dataset_verification.json."""import argparseimport hashlibimport jsonimport shutilimport subprocessimport timefrom pathlib import Path
import cv2import h5pyimport imageio_ffmpegimport numpy as np
TASK_NAME = "turning_on_radio"TASK_PROMPT = "Turn on the radio receiver that is on the table in the living room."ROLES = {"left": "left_realsense_link", "right": "right_realsense_link", "head": "zed_link"}RGB_KEY = "observation.rgb.{}_camera_0"DEPTH_KEY = "observation.depth_linear.{}_camera_0"POSE_KEY = "observation.robot2cam_pose.{}_camera_0"POSE_ORDER = ["left", "right", "head"] # teacher cam_rel_poses order (student.extra_observations)RESOLUTION = {"left": 480, "right": 480, "head": 720}
def features(official_info): reference = json.loads(Path(official_info).read_text()) automatic = {"timestamp", "frame_index", "episode_index", "index", "task_index"} out = {k: v for k, v in reference["features"].items() if k not in automatic} for feature in out.values(): feature["shape"] = tuple(feature["shape"]) return out
def obs_key(obs, role, modality): matches = [k for k in obs if ROLES[role] in k and k.endswith("::" + modality)] if len(matches) != 1: raise ValueError(f"{role}/{modality}: {matches}") return matches[0]
def composite(run, n, fps, obs, keys, success, stages): dest = run / "video.mp4" tmp = run / "video.partial.mp4" cmd = [imageio_ffmpeg.get_ffmpeg_exe(), "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", "768x336", "-r", str(fps), "-i", "pipe:0", "-an", "-c:v", "libx264", "-preset", "fast", "-crf", "20", "-threads", "2", "-pix_fmt", "yuv420p", "-movflags", "+faststart", str(tmp)] proc = subprocess.Popen(cmd, stdin=subprocess.PIPE) samples, sample_at = [], set(np.linspace(0, n - 1, 6, dtype=int).tolist()) si, phase = 0, "restored_vla_failure_state" try: for start in range(0, n, 64): chunks = [obs[k][start:min(n, start + 64)] for k in keys] for j in range(len(chunks[0])): i = start + j while si < len(stages) and stages[si]["step"] <= i: phase = stages[si].get("name", phase) si += 1 frame = np.zeros((336, 768, 3), dtype=np.uint8) frame[56:312] = np.concatenate( [cv2.resize(c[j][..., :3], (256, 256), interpolation=cv2.INTER_AREA) for c in chunks], axis=1) cv2.putText(frame, f"{run.parent.name} | FINAL: {'SUCCESS' if success else 'FAILED'}", (8, 20), cv2.FONT_HERSHEY_SIMPLEX, .48, (255, 255, 255), 1) for col, label in enumerate(["HEAD", "LEFT WRIST", "RIGHT WRIST"]): cv2.putText(frame, label, (col * 256 + 8, 45), cv2.FONT_HERSHEY_SIMPLEX, .45, (255, 255, 255), 1) cv2.putText(frame, f"{i / fps:.2f}s | step {i}/{n - 1} | {phase}", (8, 329), cv2.FONT_HERSHEY_SIMPLEX, .43, (255, 255, 255), 1) proc.stdin.write(frame.tobytes()) if i in sample_at: samples.append(frame.copy()) proc.stdin.close() if proc.wait() != 0: raise RuntimeError("ffmpeg composite failed") except BaseException: proc.kill() proc.wait() raise tmp.replace(dest) cap = cv2.VideoCapture(str(dest)) decoded = 0 while cap.read()[0]: decoded += 1 cap.release() if decoded != n: raise ValueError(f"composite decoded {decoded} != {n}") cv2.imwrite(str(run / "preview.jpg"), cv2.cvtColor(np.concatenate(samples), cv2.COLOR_RGB2BGR)) return {"video": "video.mp4", "frames": n, "fps": fps, "decoded_frames": decoded, "sha256": hashlib.sha256(dest.read_bytes()).hexdigest()}
def export(run, official_info, case): from lerobot.configs.video import DepthEncoderConfig, VideoEncoderConfig from lerobot.datasets.lerobot_dataset import LeRobotDataset from lerobot.datasets.depth_utils import quantize_depth, dequantize_depth
run = Path(run) outcome = json.loads((run / "outcome.json").read_text()) success = bool(outcome.get("success")) final_root = run / "dataset" verification_path = run / "dataset_verification.json" if final_root.exists() and verification_path.exists(): prior = json.loads(verification_path.read_text()) if prior.get("passed"): return prior if final_root.exists() and (final_root / "recovery_verification.json").exists(): prior = json.loads((final_root / "recovery_verification.json").read_text()) if prior.get("passed"): verification_path.write_text(json.dumps(prior, indent=2) + "\n") return prior dataset_root = run / "dataset.partial" if dataset_root.exists(): shutil.rmtree(dataset_root) started = time.time() with h5py.File(run / "trajectory.hdf5", "r") as f: provenance = json.loads(f.attrs['provenance']) obs = f["observations"] n_recorded = len(f["actions"]) if n_recorded == 0: raise ValueError("no recorded steps") terminated = f["terminated"][:].astype(bool) truncated = f["truncated"][:].astype(bool) first_success = int(np.argmax(terminated)) if terminated.any() else None if success and first_success is None: raise ValueError("success outcome without a terminated step") n = first_success + 1 if success else n_recorded actions = f["actions"][:n].astype(np.float32) proprio = obs["robot_r1::proprio"][:n].astype(np.float32) poses = obs["robot_r1::cam_rel_poses"][:n].astype(np.float32) mask = f["teacher/supervision_mask"][:n].astype(bool) if proprio.shape[1:] != (61,) or poses.shape[1:] != (21,) or actions.shape[1:] != (23,): raise ValueError(f"shape mismatch {proprio.shape} {poses.shape} {actions.shape}") if not (np.isfinite(actions).all() and np.isfinite(proprio).all() and np.isfinite(poses).all()): raise ValueError("non-finite state/action") rgb = {r: obs_key(obs, r, "rgb") for r in ROLES} depth = {r: obs_key(obs, r, "depth_linear") for r in ROLES} for r in ROLES: if obs[rgb[r]].shape[1:3] != (RESOLUTION[r], RESOLUTION[r]): raise ValueError(f"{r} resolution {obs[rgb[r]].shape} is not native; run with --resolution 0")
writer = LeRobotDataset.create( repo_id=f"local/task00-recovery-{run.parent.name}", root=dataset_root, fps=30, features=features(official_info), robot_type="R1Pro", use_videos=True, streaming_encoding=True, encoder_queue_maxsize=8, encoder_threads=2, camera_encoder=VideoEncoderConfig(vcodec="hevc", pix_fmt="yuv420p", g=8, crf=30, fast_decode=0, video_backend="pyav", extra_options={"x265-params": "log-level=0:bframes=0"}), depth_encoder=DepthEncoderConfig(vcodec="hevc", pix_fmt="gray12le", g=8, crf=0, output_unit="mm", video_backend="pyav", extra_options={"x265-params": "log-level=0:bframes=0:lossless=1"}), ) for start in range(0, n, 32): end = min(n, start + 32) blocks = {("rgb", r): obs[rgb[r]][start:end] for r in ROLES} blocks.update({("depth", r): obs[depth[r]][start:end] for r in ROLES}) for t in range(start, end): last = t == n - 1 frame = { "task": TASK_NAME, "action": actions[t], "next.reward": np.array([1.0 if (success and last) else 0.0], dtype=np.float32), "next.terminated": np.array([bool(success and last)], dtype=bool), "next.truncated": np.array([bool((not success) and last)], dtype=bool), "observation.state": proprio[t], } for i, role in enumerate(POSE_ORDER): frame[POSE_KEY.format(ROLES[role])] = poses[t, i * 7:(i + 1) * 7] for r in ROLES: frame[RGB_KEY.format(ROLES[r])] = blocks[("rgb", r)][t - start][..., :3].astype(np.uint8) frame[DEPTH_KEY.format(ROLES[r])] = blocks[("depth", r)][t - start].astype(np.float32)[..., None] writer.add_frame(frame) writer.save_episode() writer.finalize() (dataset_root / "meta/tasks.jsonl").write_text( json.dumps({"task_index": 0, "task_name": TASK_NAME, "task": TASK_PROMPT}) + "\n")
# Sidecar: per-frame teacher supervision mask (primitive physically verified). np.save(run / "supervision_mask.npy", mask)
# Verify: reload, compare frame count, features, and decoded samples. ds = LeRobotDataset(f"local/task00-recovery-{run.parent.name}", root=dataset_root, video_backend="pyav") ref = json.loads(Path(official_info).read_text())["features"] info = json.loads((dataset_root / "meta/info.json").read_text()) feature_match = all(tuple(info["features"][k]["shape"]) == tuple(ref[k]["shape"]) and info["features"][k]["dtype"] == ref[k]["dtype"] for k in ref) errors = [] for t in sorted({0, min(30, n - 1), n // 2, n - 1}): item = ds[t] row = {"frame": t, "action_max_abs": float(np.abs(item["action"].numpy() - actions[t]).max()), "state_max_abs": float(np.abs(item["observation.state"].numpy() - proprio[t]).max())} row['pose_max_abs'] = max(float(np.abs(item[POSE_KEY.format(ROLES[r])].numpy() - poses[t, i*7:(i+1)*7]).max()) for i, r in enumerate(POSE_ORDER)) row['terminal_semantics_match'] = ( bool(item['next.terminated'].item()) == bool(success and t == n-1) and bool(item['next.truncated'].item()) == bool(not success and t == n-1) and float(item['next.reward'].item()) == float(success and t == n-1)) for r in ROLES: img = item[RGB_KEY.format(ROLES[r])].numpy() img = np.moveaxis(img, 0, -1) if img.shape[0] == 3 else img img = img * 255.0 if img.max() <= 1.0 else img row[RGB_KEY.format(ROLES[r])] = float(np.abs(img - obs[rgb[r]][t][..., :3]).mean()) dimg = item[DEPTH_KEY.format(ROLES[r])].numpy().squeeze() src = obs[depth[r]][t].astype(np.float32) valid = src > 0 # Units are explicit in the encoder metadata; never guess from max depth. dm = dimg / 1000.0 row[DEPTH_KEY.format(ROLES[r]) + "_mae_mm"] = float(np.abs(dm[valid] - src[valid]).mean() * 1000) if valid.any() else None expected = dequantize_depth(quantize_depth(src, video_backend=None), output_unit='mm').squeeze() row[DEPTH_KEY.format(ROLES[r]) + '_quantized_max_abs_mm'] = float( np.abs(dimg.astype(np.float32) - expected.astype(np.float32)).max()) errors.append(row) stages = [json.loads(line) for line in (run / "events.jsonl").read_text().splitlines()] stages = [dict(e, name=e.get('name', e.get('entry', e.get('phase', 'recovery')))) for e in stages if e.get("event") in ('stage', 'strategy')] video = composite(run, n, 30, obs, [rgb["head"], rgb["left"], rgb["right"]], success, stages)
import av video_counts = {} for path in (dataset_root / 'videos').glob('*/chunk-*/*.mp4'): with av.open(str(path)) as container: video_counts[str(path.relative_to(dataset_root))] = sum(1 for _ in container.decode(video=0)) passed = (len(ds) == n and feature_match and len(video_counts) == 6 and all(count == n for count in video_counts.values()) and all(e['action_max_abs'] < 1e-5 and e['state_max_abs'] < 1e-4 and e['pose_max_abs'] < 1e-5 and e['terminal_semantics_match'] and all(e[DEPTH_KEY.format(ROLES[r]) + '_quantized_max_abs_mm'] == 0 for r in ROLES) for e in errors)) verification = { "passed": passed, "frames": n, "recorded_steps": n_recorded, "post_success_tail_dropped": n_recorded - n if success else 0, "success": success, "features_exact_match": feature_match, "supervised_frames": int(mask.sum()), "depth_encoding": {"codec": "hevc", "pix_fmt": "gray12le", "crf": 0, "g": 8, "bframes": 0, "lossless": True, "output_unit": "mm", "note": "official quantizer; explicit lossless codec; Task-00 used CRF30/GOP2/B4"}, "rgb_encoding": {"codec": "hevc", "pix_fmt": "yuv420p", "crf": 30, "g": 8, "bframes": 0}, "sample_decode_errors": errors, "composite_video": video, "provenance": {k: provenance.get(k) for k in ('source', 'frame', 'source_sha256', 'code_sha256')}, "decoded_video_frame_counts": video_counts, "videos": {p.parent.parent.name: {"bytes": p.stat().st_size} for p in (dataset_root / "videos").glob("*/chunk-*/*.mp4")}, "export_seconds": round(time.time() - started, 1), "case": case, } if not passed: (run / "dataset_verification_failed.json").write_text(json.dumps(verification, indent=2) + "\n") raise ValueError("dataset verification failed") if final_root.exists(): raise FileExistsError(f"Unverified final dataset exists: {final_root}") (dataset_root / "recovery_verification.json").write_text(json.dumps(verification, indent=2) + "\n") dataset_root.replace(final_root) tmp = run / "dataset_verification.tmp" tmp.write_text(json.dumps(verification, indent=2) + "\n") tmp.replace(verification_path) return verification
def slim(run): """Drop image/depth arrays after verified export; keep actions, full sim states, proprio, camera poses, teacher sidecar. Full states allow exact re-rendering.""" src = Path(run) / "trajectory.hdf5" tmp = Path(run) / "trajectory.slim.hdf5" with h5py.File(src, "r") as f, h5py.File(tmp, "w") as g: for k, v in f.attrs.items(): g.attrs[k] = v g.attrs["images_removed_after_export"] = "rgb/depth_linear/depth_valid; see dataset/ videos" for name in f: if name != "observations": f.copy(name, g) o = g.create_group("observations") for k in f["observations"]: if not k.endswith(("::rgb", "::depth_linear", "::depth_valid")): f.copy(f"observations/{k}", o) before = src.stat().st_size tmp.replace(src) return {"bytes_before": before, "bytes_after": src.stat().st_size}
if __name__ == "__main__": p = argparse.ArgumentParser() p.add_argument("run", type=Path) p.add_argument("--official-info", type=Path, required=True) p.add_argument("--case", type=json.loads, default={}) p.add_argument("--slim", action="store_true") a = p.parse_args() result = export(a.run, a.official_info, a.case) if a.slim: result["slim"] = slim(a.run) print(json.dumps({k: result[k] for k in ("passed", "frames", "success", "export_seconds")} | ({"slim": result["slim"]} if "slim" in result else {})))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657"""Merge only verified Task00 datasets, keeping public-instance diagnostics separate."""import argparseimport jsonimport hashlibimport shutilfrom pathlib import Path
def merge(runs, output): import numpy as np from lerobot.datasets.aggregate import aggregate_datasets from lerobot.datasets.lerobot_dataset import LeRobotDataset records = [] for path in Path(runs).rglob('complete.json'): row = json.loads(path.read_text()) if row.get('dataset_passed') and not row['outcome'].get('already_complete_at_start'): records.append(row) output = Path(output) output.mkdir(parents=True, exist_ok=True) for label, selected in [ ('all', [r for r in records if not r.get('diagnostic_only')]), ('success', [r for r in records if r.get('success') and not r.get('diagnostic_only')]), ('public_diagnostic', [r for r in records if r.get('diagnostic_only')]), ]: if not selected: continue target = output/label if target.exists(): raise FileExistsError(target) roots = [Path(r['attempt'])/'dataset' for r in selected] aggregate_datasets([f'local/task00-{i}' for i in range(len(roots))], aggr_repo_id=f'local/task00-recovery-{label}', roots=roots, aggr_root=target, video_files_size_in_mb=0) ds = LeRobotDataset(f'local/task00-recovery-{label}', root=target, video_backend='pyav') assert ds.num_episodes == len(roots) assert len(ds) == sum(r['verification']['frames'] for r in selected) (target/'teacher').mkdir() manifest = [] for i, row in enumerate(selected): src = Path(row['attempt'])/'supervision_mask.npy' mask = np.load(src, allow_pickle=False) if mask.shape != (row['verification']['frames'],) or mask.dtype != np.bool_: raise ValueError(f'Invalid supervision mask: {src}') dst = target/'teacher'/f'episode_{i:06d}_supervision_mask.npy' shutil.copyfile(src, dst) manifest.append(dict(row, episode_index=i, teacher_mask=str(dst.relative_to(target)), teacher_mask_sha256=hashlib.sha256(dst.read_bytes()).hexdigest())) (target/'generation_manifest.jsonl').write_text(''.join(json.dumps(r)+'\n' for r in manifest)) print(label, len(roots), len(ds))
if __name__ == '__main__': p = argparse.ArgumentParser(description=__doc__) p.add_argument('--runs', required=True, type=Path) p.add_argument('--output', required=True, type=Path) a = p.parse_args() merge(a.runs, a.output)PROVENANCE.jsonAdded+13
README.mdAdded+7
SHA256SUMSAdded+53
payload/CODE_SHA256SUMSAdded+49
payload/SHA256SUMSAdded+50
payload/config/local_cases.jsonlAdded+5
payload/config/official_info.jsonAdded+317
payload/config/source_provenance.jsonAdded+92
payload/env_centre.shAdded+8
payload/env_eai.shAdded+12
payload/experiments/__init__.pyAdded
payload/experiments/radio_two_arm/__init__.pyAdded
payload/experiments/radio_two_arm/motion.pyAdded+94
payload/experiments/radio_two_arm/navigation.pyAdded+85
payload/experiments/radio_two_arm/perception.pyAdded+78
payload/experiments/radio_two_arm/policy.pyAdded+197
payload/pipeline/__init__.pyAdded
payload/pipeline/navigation.pyAdded+72
payload/pipeline/sensors.pyAdded+102
payload/recovery.sbatchAdded+19
payload/scripts/__init__.pyAdded
payload/scripts/kinematics.pyAdded+85
payload/task00_recovery/__init__.pyAdded
payload/task00_recovery/grasp_evidence.pyAdded+90
payload/task00_recovery/recording.pyAdded+110
payload/task00_recovery/run.pyAdded+118
payload/task00_recovery/sim.pyAdded+202
payload/task00_recovery/source.pyAdded+73
payload/task00_recovery/student.pyAdded+43
payload/task00_recovery/teacher.pyAdded+480
payload/task00_recovery/vendor/__init__.pyAdded+1
payload/task00_recovery/vendor/data/fork_category_states.jsonAdded+1524
payload/task00_recovery/vendor/fork_serialization.pyAdded+522
payload/task00_recovery/vendor/fork_state.pyAdded+232
payload/tests/fixtures/holding_anchor.jsonAdded+158
payload/tests/fixtures/right_terminal_993.jsonAdded+66
payload/tests/test_contracts.pyAdded+104
payload/tests/test_free_hand_clearance.pyAdded+30
payload/tests/test_holding_anchor.pyAdded+42
payload/tests/test_navigation_resolution.pyAdded+22
payload/tests/test_pilot_resource_gate.pyAdded+24
payload/tests/test_retry_recovery.pyAdded+70
payload/tests/test_source_contract.pyAdded+23
payload/tools/__init__.pyAdded
payload/tools/build_cases.pyAdded+53
payload/tools/centre_pilot.pyAdded+129
payload/tools/download_sources.pyAdded+94
payload/tools/driver.pyAdded+116
payload/tools/export_lerobot.pyAdded+304
payload/tools/merge_datasets.pyAdded+57