diff --git a/.gitattributes b/.gitattributes index ae4af884340adb07235bb947f940a89f5a687808..11f974898561cd81b838613b59116a907f63fc20 100644 --- a/.gitattributes +++ b/.gitattributes @@ -988,3 +988,4 @@ release-20261105/checkpoints/joint8gpu-step25000/distributed/__7_0.distcp filter release-20261105/metadata/eval_evidence_files.nul filter=lfs diff=lfs merge=lfs -text release-20261105/metadata/source_files.nul filter=lfs diff=lfs merge=lfs -text release-20261105/source/workspace_joint/mira/docs/hero.png filter=lfs diff=lfs merge=lfs -text +release-20261107/source/workspace_joint/mira/docs/hero.png filter=lfs diff=lfs merge=lfs -text diff --git a/README.md b/README.md index 154a52695728c162e68493571aa5b30990e948a9..89691ea038f229ea95cac2190f3b8e03c1ce47ac 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,8 @@ tags: # Multi-WAM reproducible handoff +**Latest code: 2026-11-07.** [`release-20261107/`](release-20261107/) contains the updated training and inference pipeline, launchers, held-out mini-eval tools, and checksums. It is a code-only overlay on the 2026-11-05 release; the saved step-6563 checkpoint and its reported evaluation remain historical BGR artifacts. + **Latest: 2026-11-05 backup of the final 4-GPU joint checkpoint and official full evaluation.** [`release-20261105/`](release-20261105/) contains step 6563, its paired World/Action deployment, the older 8-GPU step 25000 and 30181 checkpoints, diff --git a/release-20261107/README.md b/release-20261107/README.md new file mode 100644 index 0000000000000000000000000000000000000000..63b4cebb78519e2e58c08842d1cc723d9a82683a --- /dev/null +++ b/release-20261107/README.md @@ -0,0 +1,35 @@ +# Multi-WAM code refresh: 2026-11-07 + +This release captures the current `workspace_joint/mira`, `workspace_joint/scripts`, `workspace_joint/docs`, and `workspace_joint/patches` source trees after the training and evaluation pipeline update. It contains **code and configuration only**. The saved checkpoints, deployment weights, pinned simulator files, split manifests, evaluation evidence, and environment remain in [`release-20261105`](../release-20261105/), which is the required base release. + +## Changes since 2026-11-05 + +- Adds an explicit image contract for the next training phases: Codec receives BGR and Qwen receives RGB. The step-6563 checkpoint is a historical BGR-input checkpoint; its published full evaluation remains under `--input-color-order bgr --strict-eval`. +- Adds weights-only initialization from a joint checkpoint, training phase options for learning-rate annealing, EMA, and rollout gradients, plus a portable `scripts/pipeline/train_phase.sh` launcher. Phase 1a starts from step 6563; Phase 2 requires the selected Phase 1 checkpoint. These are **plans and code**, not claims that either new phase has finished training. +- Adds a held-out mini-eval suite on seeds 300000+, seed-paired comparison, and checkpoint selection scripts. The suite does not use the 100000+ formal evaluation seed range. +- Updates inference and export code to carry the new image contract through deployment, plus focused tests for color handling, training options, and mini-eval accounting. + +## Restore and run + +First restore `release-20261105` exactly as described in its README, including its base releases and external RoboTwin data. Then overlay this code snapshot onto the restored workspace: + +```bash +cp -a release-20261107/source/workspace_joint/mira/. /path/to/new-project/workspace_joint/mira/ +cp -a release-20261107/source/workspace_joint/scripts/. /path/to/new-project/workspace_joint/scripts/ +cp -a release-20261107/source/workspace_joint/docs/. /path/to/new-project/workspace_joint/docs/ +cp -a release-20261107/source/workspace_joint/patches/. /path/to/new-project/workspace_joint/patches/ +sha256sum -c release-20261107/SHA256SUMS +``` + +The checksum command runs from the repository bundle root. The new training entry point is `workspace_joint/scripts/pipeline/train_phase.sh`; call `--check` before `--train` and set `MIRA_PYTHON`, `DATASET_ROOT`, `JOINT_MANIFEST_DIR`, `INIT_CHECKPOINT`, and GPU settings as needed for the target machine. For example: + +```bash +cd /path/to/new-project/workspace_joint +bash scripts/pipeline/train_phase.sh phase1a_color --check +``` + +Apply the optional simulator state-source patch after the pinned RoboTwin checkout is restored: `bash /path/to/new-project/workspace_joint/scripts/apply_eval_patches.sh`. It checks the base and patched file hashes. The detailed run plan is in `workspace_joint/docs/PIPELINE_V4.md`, and the scoring contract is in `workspace_joint/docs/EVAL_PROTOCOL.md`. + +The held-out suite is `workspace_joint/mira/configs/minieval/heldout_v1.json`. `workspace_joint/scripts/run_minieval.py` runs it on selected GPUs, `compare_minieval.py` compares paired seeds, and `pipeline/select_checkpoints.py` ranks saved checkpoints. Check the simulator and deployment dependencies in the base release before running evaluation. + +This release does not replace or reinterpret any historical checkpoint or score. No credentials, dataset contents, cache, or generated training outputs are included. diff --git a/release-20261107/SHA256SUMS b/release-20261107/SHA256SUMS new file mode 100644 index 0000000000000000000000000000000000000000..4d0fc3354c5b9e6e6a0ab4d22ccfdf564f7d8dad --- /dev/null +++ b/release-20261107/SHA256SUMS @@ -0,0 +1,514 @@ +b6da8578fabc04694fe88b4b9c65c86b2a1c8375c0a85c758256dff5eb6842b3 release-20261107/README.md +ddd24608779acbbf65f2be223ea7d84d9b9838e54e8b4bda0d862cae94927869 release-20261107/source/workspace_joint/docs/EVAL_PROTOCOL.md +725efa46b0f787eccb884d3a08dcc17b98dd5f9f21564838cdd8469b7730ad53 release-20261107/source/workspace_joint/docs/JOINT_EVAL_LANGUAGE_V3.md +96e6dab71cd99b363e70a48c89f729024660b303923158bd277e6928550ec2c1 release-20261107/source/workspace_joint/docs/PIPELINE_V4.md +597c9eb63e7b845fd1b006da99167e61390359bf88d0ca2536c65c8938154123 release-20261107/source/workspace_joint/docs/TRAIN_EVAL_TEXT_MISMATCH_CASES_20261021.md +ee6543694c65a636d2e21ca6cbfaf3c800adde61a4abdb3bfc86a9a37667bea9 release-20261107/source/workspace_joint/docs/gpu_validation_20260920.md +f06d1dcc91e582875e8c9f39f583e3fdc77627bea910e9c80fa49b3d7f83b78c release-20261107/source/workspace_joint/docs/joint_anchor_v2_24gpu_runbook.md +b0dbc244039c69149b7698ec52601751bb4df91e1e9e3bd63027a9d4f8f94d8e release-20261107/source/workspace_joint/docs/joint_training_to_eval_progress_20261010.md +ab61be409185f1f39226da267b7e0f0d75cb312c645c5bb293688134629a461f release-20261107/source/workspace_joint/docs/project_layout.md +ed86ee38d372ff3928a5f2c07713d21856cb1d49fd9feca3c481c879b0d07c10 release-20261107/source/workspace_joint/docs/repair_report_20260920.md +fa003799a464d4b3ae5af8a2a35ead8138e696738bac987777a5f2527d5eb57d release-20261107/source/workspace_joint/docs/validation_20260920.md +f6af738bf29f60bb104c7d39e6f8dea677b06c01b96298f671fb1f158b176410 release-20261107/source/workspace_joint/mira/.gitignore +75efa07c4d2afb14d8226cf00b7763dd2ec1c5585a9dfe919881a3a3fef2ddac release-20261107/source/workspace_joint/mira/LICENSE +9121ecb8deffdf4280d5f650c8b0aeed91aeb10462c6c4aaef5e28a8545562c3 release-20261107/source/workspace_joint/mira/README.md +f03455a5e9abd75a272a377c5de03843e6ff2e738fed9bb5580336084a57fafd release-20261107/source/workspace_joint/mira/THIRD_PARTY_LOCK.md +7606bf7f7a990440527b25133785dd27fea3d11459974b034930811f0ee6ee5b release-20261107/source/workspace_joint/mira/configs/README.md +50f7bffa03ef9ac6d5439166417aa1109e212743ce21c0955d3b4e71ffe30321 release-20261107/source/workspace_joint/mira/configs/action_v10_h1_50/base.yaml +f3a1abb072013704a88052a163941db7a3c98e43941062d22e5349b2dd011c41 release-20261107/source/workspace_joint/mira/configs/action_v10_h1_50/smoke_gt.yaml +13976f2703ac4f9d122b695ad532579f5e69b0fc6c9613ba6ed283200c8d1765 release-20261107/source/workspace_joint/mira/configs/action_v10_h1_50/train_gt10k.yaml +f883384945ff9539456bbe71251e1d900dad54e31413829b98015e509a757b33 release-20261107/source/workspace_joint/mira/configs/action_v10_h1_50/train_pred10k_from4139.yaml +42bbc3b8a5ea2e4186ee709b868592198337ba44cbf4922017cdf38ba2ea1dcf release-20261107/source/workspace_joint/mira/configs/action_v10_h1_50/train_pred20k.yaml +a801493c26c7b5f3f6b2665d5d87caa8f15904703528bf0ecfb68d9b413adfb0 release-20261107/source/workspace_joint/mira/configs/action_v11_pred8k/base.yaml +22fccfc5d7f410aae104e8942eba6e7c2008d37520406c0b6e321fe3927da49e release-20261107/source/workspace_joint/mira/configs/action_v11_pred8k/smoke.yaml +f58c6620e07ef6864da4f9be82bb4d46a68829366a2c901587fc77376d68c423 release-20261107/source/workspace_joint/mira/configs/action_v11_pred8k/supplemental_lift_pot_case.json +42bbc3b8a5ea2e4186ee709b868592198337ba44cbf4922017cdf38ba2ea1dcf release-20261107/source/workspace_joint/mira/configs/action_v11_pred8k/train.yaml +4e82c164df9dca47862fd34c6d211054d90007cba0179141c4a5ad0c97f6b5db release-20261107/source/workspace_joint/mira/configs/action_v12_epoch/base.yaml +2fd847d0f9f263d54f48d10d22594c0bed196c369ceabe421986332318c1ed26 release-20261107/source/workspace_joint/mira/configs/action_v12_epoch/cache_smoke96.yaml +6b59ec9a004d5db6c64ef396038c1266c5e01e5313418c18ec05db181ea56e01 release-20261107/source/workspace_joint/mira/configs/action_v12_epoch/smoke.yaml +42bbc3b8a5ea2e4186ee709b868592198337ba44cbf4922017cdf38ba2ea1dcf release-20261107/source/workspace_joint/mira/configs/action_v12_epoch/train.yaml +87f2cc6894ae011f0b2e78881410fc596a86f49b5764ae2d2321ba7a15824e9d release-20261107/source/workspace_joint/mira/configs/action_v13_continue4epoch/base.yaml +adad464badee0b7d9336ae11680ba54f894888807e6b8b667efcb2f32196de63 release-20261107/source/workspace_joint/mira/configs/action_v13_continue4epoch/perf_smoke.yaml +f7459135a3363d2196be7e9c9a6a4ef9a8c2cba5e4b8974cccd8012fc6d0dae5 release-20261107/source/workspace_joint/mira/configs/action_v13_continue4epoch/perf_smoke4.yaml +6191ff811d83f9e19e6c36a858453650f1c76f16e849364c2854ead6221123d2 release-20261107/source/workspace_joint/mira/configs/action_v13_continue4epoch/smoke.yaml +c092447c79bef32bc3ad34c21f2c9b14e7459f1f02e7cdb0c774a9473a4ab9a9 release-20261107/source/workspace_joint/mira/configs/action_v13_continue4epoch/train.yaml +fc0edc236dda551027fcad6a5a475efa326a5ecaa1d7752f49b6a86f80d3a598 release-20261107/source/workspace_joint/mira/configs/action_v6/base.yaml +762c9f3bf6e065a2bc831ce28f5b46f84077036de614ec0a286990a21bf4f7c0 release-20261107/source/workspace_joint/mira/configs/action_v6/cache.yaml +f1872a677ea5e4548c358044faca89cdaa9fa21f4d492d8013b6b7cae3e53a3d release-20261107/source/workspace_joint/mira/configs/action_v6/canary.yaml +4a03416bbce765f1e25a3f5db599dcdc540798ac8404de3ee20a8f81710ad012 release-20261107/source/workspace_joint/mira/configs/action_v6/canary_corrective_v7_round0.yaml +8ec0c9636d34ef392f7f8748cf5b1d5395a72363f28e77570f0f91d4b89f7c63 release-20261107/source/workspace_joint/mira/configs/action_v6/overfit64.yaml +42bbc3b8a5ea2e4186ee709b868592198337ba44cbf4922017cdf38ba2ea1dcf release-20261107/source/workspace_joint/mira/configs/action_v6/train.yaml +228efa8c544215f9188fea69c8975d7af0b865c7c8274beb1b80bb60a325fca9 release-20261107/source/workspace_joint/mira/configs/action_v6/train_compressed22k.yaml +b75c1e596c41cb46ee67ac68f65947bd868d465ea0eb1230b6ffc93e1c5b5ea0 release-20261107/source/workspace_joint/mira/configs/action_v6/train_continue100k.yaml +895952b636c44cd6a5793e89589032b33e8088d93c62176aaa076bee7a5038f0 release-20261107/source/workspace_joint/mira/configs/action_v6/train_corrective_v7_round0.yaml +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 release-20261107/source/workspace_joint/mira/configs/actions/.gitkeep +e07855a31b075f336a48c0e84b5949f384f7b1b52b68f2581007668969eae66c release-20261107/source/workspace_joint/mira/configs/actions/none.yaml +447150b1cc3d3dfbd612f1e3d6e6abdc8513c710b48182808becd8cea04b1ff2 release-20261107/source/workspace_joint/mira/configs/actions/rocket_league.yaml +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 release-20261107/source/workspace_joint/mira/configs/dataset/.gitkeep +1473c730d6bf0ca0726e71198066ed47c295d48b3f8e049a6679c0fdf087bec2 release-20261107/source/workspace_joint/mira/configs/dataset/robotwin2.yaml +2b45d9b057a21c049d45f330eae1147a2ac8f6605567f9e17d7ce443e997d204 release-20261107/source/workspace_joint/mira/configs/dataset/robotwin_wam.yaml +1a894a05fd2bf63828e79b537dd7965d75b0cea312d7205cb84b2c35cdbf98b6 release-20261107/source/workspace_joint/mira/configs/dataset/robotwin_wam_smoke.yaml +a80e1ff40cbae824c804265b053e56c1d41ca65deb39bf47da64eb38d3f952c8 release-20261107/source/workspace_joint/mira/configs/dataset/rocket_league.yaml +7bb707e62180dc6b8c6715802bc8a5f0479d8f0680b50091337e51a0cf8cf795 release-20261107/source/workspace_joint/mira/configs/eval_action_head_offline.yaml +065f720637df879c6a06f044e3c923db301c470af3f2587a300fd2f7432361a9 release-20261107/source/workspace_joint/mira/configs/eval_world_model.yaml +8651a4cc9d672c2052955d40457622768597565cd419afed7e23d46c809f49df release-20261107/source/workspace_joint/mira/configs/minieval/heldout_v1.json +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 release-20261107/source/workspace_joint/mira/configs/model/.gitkeep +71231c6f88394bb650ce42f33551a5084c2eec805e42128a8591e6fe5b2ad39e release-20261107/source/workspace_joint/mira/configs/model/action_joint_flow.yaml +5e390c0811a4a59421d76db493e057f60309dd2ae2bc52c47505eefbbe610247 release-20261107/source/workspace_joint/mira/configs/model/bihub_world_1b.yaml +06d95f451ce2a7a2078a31674f6e5227c36316e5415a71ea1bdb765e31d51f91 release-20261107/source/workspace_joint/mira/configs/model/bihub_world_5b.yaml +c988cfa8a57588e242a82228130b2cd484b3c36960955c2741fafd7a759960e1 release-20261107/source/workspace_joint/mira/configs/model/bihub_world_smoke.yaml +4ae4b93e1d8f202dc8b170d21b9a71013bdf7092cb76127bb23085926ed55421 release-20261107/source/workspace_joint/mira/configs/model/latent_world_model/1b.yaml +7547721d3e9fde93fb39dca1a5e98deac78e21fd9d891db8cc27a8326dab4b50 release-20261107/source/workspace_joint/mira/configs/model/latent_world_model.yaml +24728ae7e653539a14c44c8f1ce8d3f84a7d83a111590fb0c8123bb72cc6b6b4 release-20261107/source/workspace_joint/mira/configs/model/lingbot_raev2_codec_tdown.yaml +4d535390dfab76df44398d78ab568158c15e8d7fa57199feacdff130dedb4f07 release-20261107/source/workspace_joint/mira/configs/model/multi_wrapper_world_model.yaml +54fafd34e5481a924e158af95c4377cf2e9ab135e7f2ca50e0e39c5c35ccee23 release-20261107/source/workspace_joint/mira/configs/model/raev2_codec_tdown.yaml +d3d4bed3a2af151d78a46d3c8eedb42fd61ffcd24660f74f0391e3ffe0b7d1b2 release-20261107/source/workspace_joint/mira/configs/train_action_head.yaml +3b7858e188a61db484bc45d51ba45c3387201558e4b87448c35efc167fbf8f79 release-20261107/source/workspace_joint/mira/configs/train_action_head_2gpu.yaml +2991bcdebe8917632232329b1c36eb6c0cb6a3d4c2c0f342d6ef86a7dbb2dac0 release-20261107/source/workspace_joint/mira/configs/train_action_head_smoke.yaml +00d596c3639b8de6c6bd1d27bbac3862f9d5a1f05ef9228122a70f56e75db44b release-20261107/source/workspace_joint/mira/configs/train_bihub_wam_world.yaml +f23c4cc97bc12bbc6bdcffb5d9280cbb07015da161381d28bc2ba031a7cb2df2 release-20261107/source/workspace_joint/mira/configs/train_bihub_wam_world_smoke.yaml +8388dbe9695b8842683fa88b0208d80d11159f50a06bb38f2627fe7420c00877 release-20261107/source/workspace_joint/mira/configs/train_codec.yaml +72ca46beb322d7c0f90adf8ad4af6847bf67c1437e1606e108e6fcae6d18bda8 release-20261107/source/workspace_joint/mira/configs/train_world_model.yaml +2ac79e12de7f41164e18e8b6d099861f0d214dc8681e1848327f300b2f586325 release-20261107/source/workspace_joint/mira/configs/world_v10_h1_50/base.yaml +0120a651a381b0d8d648818a81ac90423f2cc9373405a7573da45d862d46614a release-20261107/source/workspace_joint/mira/configs/world_v10_h1_50/smoke.yaml +42bbc3b8a5ea2e4186ee709b868592198337ba44cbf4922017cdf38ba2ea1dcf release-20261107/source/workspace_joint/mira/configs/world_v10_h1_50/train.yaml +e433c5b0380f78d68a3d49e36a1c151640809ef5ed1d8d6e1f0421e483caa08e release-20261107/source/workspace_joint/mira/configs/world_v11_continue30k/base.yaml +b792e11540d17ec9e9674b77e69e10ea2a45d7504de019741adda4640e013e34 release-20261107/source/workspace_joint/mira/configs/world_v11_continue30k/fixed_cases.json +21866af47c891d0e7e0410d9f9b41b95744ac8a21ec0f241b1bb4b5c4cda91e7 release-20261107/source/workspace_joint/mira/configs/world_v11_continue30k/smoke.yaml +99798671e2ba1fbb720ca834f5bb7a503c4378408840ae77ecb924c5e5d7ec35 release-20261107/source/workspace_joint/mira/configs/world_v11_continue30k/supplemental_lift_pot_case.json +42bbc3b8a5ea2e4186ee709b868592198337ba44cbf4922017cdf38ba2ea1dcf release-20261107/source/workspace_joint/mira/configs/world_v11_continue30k/train.yaml +6ffca7f2120e9ef77ae176a3722aa350db1dc1ca7e59af8947ab718577758101 release-20261107/source/workspace_joint/mira/configs/world_v12_eval_aligned_epoch/base.yaml +636608d7c21590e4dc4dff27980cb0bd9d8e34a68e03b98b8a41189abd2645ed release-20261107/source/workspace_joint/mira/configs/world_v12_eval_aligned_epoch/fixed_cases.json +b81a7deff03f460c1840fd520a97052d04421cc34652ba0c64272f63de2f4ea5 release-20261107/source/workspace_joint/mira/configs/world_v12_eval_aligned_epoch/smoke.yaml +42bbc3b8a5ea2e4186ee709b868592198337ba44cbf4922017cdf38ba2ea1dcf release-20261107/source/workspace_joint/mira/configs/world_v12_eval_aligned_epoch/train.yaml +dea7a75f51fbeb23afdc9e4f11cebb744f273a1f3469e8716de94ae7352c792e release-20261107/source/workspace_joint/mira/configs/world_v12_four_gpu_remaining/base.yaml +315df922b92171b02db62ef6a981335df08ebe3bcf216bc529f16213102b1b8a release-20261107/source/workspace_joint/mira/configs/world_v12_four_gpu_remaining/smoke.yaml +42bbc3b8a5ea2e4186ee709b868592198337ba44cbf4922017cdf38ba2ea1dcf release-20261107/source/workspace_joint/mira/configs/world_v12_four_gpu_remaining/train.yaml +b25e72535d07e72c37ee4d7f3b1f525f8d0ccfbc14e7c9d7a7d4552c72781d57 release-20261107/source/workspace_joint/mira/configs/world_v12_largebatch_remaining/base.yaml +bb5876e09ee62b5251c29ff8991c187af6627cdbd2773bc406df8ff819f1a073 release-20261107/source/workspace_joint/mira/configs/world_v12_largebatch_remaining/long_smoke.yaml +f3d64f3b7f45d0136d7ef66e4d8667e037e7978d08e627bf026f874c557ad0ca release-20261107/source/workspace_joint/mira/configs/world_v12_largebatch_remaining/smoke.yaml +42bbc3b8a5ea2e4186ee709b868592198337ba44cbf4922017cdf38ba2ea1dcf release-20261107/source/workspace_joint/mira/configs/world_v12_largebatch_remaining/train.yaml +da8908e8e2fe720771b670d541c734b2d7f89b85be5a8422aa0f47d004446074 release-20261107/source/workspace_joint/mira/configs/world_v6/base.yaml +42bbc3b8a5ea2e4186ee709b868592198337ba44cbf4922017cdf38ba2ea1dcf release-20261107/source/workspace_joint/mira/configs/world_v6/bootstrap.yaml +67fbcafae0508433fb5b3a67d17cd405c232029f51a5af26def7b5bdde72ce76 release-20261107/source/workspace_joint/mira/configs/world_v6/cache.yaml +a2e281d02012f19c11d9d055c1464324613351fa63035aa698345548d0d20c40 release-20261107/source/workspace_joint/mira/configs/world_v6/canary_bootstrap.yaml +293ca1f9613c247d4706836d872343581b95d2cfb060325f15b18d52338145b7 release-20261107/source/workspace_joint/mira/configs/world_v6/canary_train.yaml +c482680f256f0cd349b039a929ad5737b7ab82bf9bb123e3f8c6a4c926118b9f release-20261107/source/workspace_joint/mira/configs/world_v6/eval.yaml +1fb2a7eb0fe184d373ac19d948a597ee98bd4fb8161bd2c2b45fd38ede69985b release-20261107/source/workspace_joint/mira/configs/world_v6/overfit64.yaml +609f9da2c42737f2ec3f30888b651922e3e82b41b27974ebd1d9a9d44ed60f11 release-20261107/source/workspace_joint/mira/configs/world_v6/smoke_base.yaml +40fcc559a976b5c6250eb9fbae0a4dbedb077d0e11886812ac99c22d56ec5815 release-20261107/source/workspace_joint/mira/configs/world_v6/smoke_bootstrap.yaml +37e7438e6ba6d2b0d2be038b275406170eff1c1f5b230d362c0c2b07fefe85c9 release-20261107/source/workspace_joint/mira/configs/world_v6/smoke_cache.yaml +84d045b7de29b6d12e1d2cbdb23cab647d47a25635ed7bbae8edd3da509124dd release-20261107/source/workspace_joint/mira/configs/world_v6/smoke_eval.yaml +4a33da6642492d66180e0b1ce3b43fe9e9a58cfb967928f967b8433f6d30f8fe release-20261107/source/workspace_joint/mira/configs/world_v6/smoke_train.yaml +bab65fc1d9f4311ff1c5ad343dd9ee8feaeb4952c66cdf14a791a938a5f951bd release-20261107/source/workspace_joint/mira/configs/world_v6/train.yaml +e22e75d78f95de7058a4acc3785b08f26dc420e86e4a81d865671cbf78c3e55f release-20261107/source/workspace_joint/mira/configs/world_v7/base.yaml +76757aabd48131b4d0126537880cba19fc79e9e79cbb201745e7b9a1cbe7d87e release-20261107/source/workspace_joint/mira/configs/world_v7/smoke.yaml +42bbc3b8a5ea2e4186ee709b868592198337ba44cbf4922017cdf38ba2ea1dcf release-20261107/source/workspace_joint/mira/configs/world_v7/train.yaml +9aaaf3489c914ef675d17d14b50c60d76db23b233858f3b925a2620961c0c9a5 release-20261107/source/workspace_joint/mira/configs/world_v8/base.yaml +71b7b6ddda1e857f55e5af029c598781da6212acd3ef5c3cc431ae23eb79f1ca release-20261107/source/workspace_joint/mira/configs/world_v8/fixed_cases.json +83061e6f3179f15c46c1d198debfaba1accb17fb3f6c1d36600997484e03dbfc release-20261107/source/workspace_joint/mira/configs/world_v8/smoke.yaml +42bbc3b8a5ea2e4186ee709b868592198337ba44cbf4922017cdf38ba2ea1dcf release-20261107/source/workspace_joint/mira/configs/world_v8/train.yaml +ba46b6b13d8ebb783ebda1d66fa2261a622a92a1e8960be7703d44f09b3ca378 release-20261107/source/workspace_joint/mira/configs/world_v9_episode_start/base.yaml +fe37f68a7c7f8654c22d9da85e7ab998c6629c21d9dfd941c18b88794d961887 release-20261107/source/workspace_joint/mira/configs/world_v9_episode_start/fixed_cases.json +db1129d531a7f402f26146e4819de04c6edb5188ef3d25457c8d8c040004edfb release-20261107/source/workspace_joint/mira/configs/world_v9_episode_start/smoke.yaml +42bbc3b8a5ea2e4186ee709b868592198337ba44cbf4922017cdf38ba2ea1dcf release-20261107/source/workspace_joint/mira/configs/world_v9_episode_start/train.yaml +9ca61a7666ac0b2b1c0e4382304dba1220a4cfb1dcc9189d70dce7156f377429 release-20261107/source/workspace_joint/mira/docs/action_head_stage/README.md +8ef276b64998a78131553799ba4bdf3724a16b9df09b8db6bbb376db2e1e6d03 release-20261107/source/workspace_joint/mira/docs/action_head_stage/compatibility_map.md +8b93ea2ffb488c733f62a3b577e4acfaa514aa0df45523deffdeac6c34aa4ee9 release-20261107/source/workspace_joint/mira/docs/action_head_stage/deployment_and_smoke_report.md +b1d4a386791ac0a9d10443d1d739e3f23e9153814a23b3a4190e5108cf36a23a release-20261107/source/workspace_joint/mira/docs/bihub_wam_stage_w_pipeline.md +e2be5d2073979e1240bf7f2dfe287c21bc394493b2e711bb0ca1a6d63616b294 release-20261107/source/workspace_joint/mira/docs/dataset_card.md +9e68cb0ec466b6736243b450bac7a1a4081803a9ff43446dfda1b38105dd6e91 release-20261107/source/workspace_joint/mira/docs/hero.png +53d57a0394fdde5f46ddf7755b7247b0d11807e76f853092e7eba68ee7eb3dbc release-20261107/source/workspace_joint/mira/docs/joint_rgb_pipeline_20261030.md +82ac31fdeb8619935f032c8e6bbc7cb65bb5147412ca0a71564e90b1d79a04ee release-20261107/source/workspace_joint/mira/docs/joint_world_action_online.md +f7ad09156aa15031e6578586c6fa3843d26035ddbbe070f57244e4da5e421871 release-20261107/source/workspace_joint/mira/docs/pre_full_eval_audit_20261030.md +8d66d079f274db40d69d4a50b55b3d690347b1549d21c7ec814f9bc85f12611d release-20261107/source/workspace_joint/mira/docs/robotwin_lingbot_codec_design.md +3cf58642a96f0d1445e4796049f4bcdfee77624688dfac6924a627ad17d71184 release-20261107/source/workspace_joint/mira/docs/robotwin_lingbot_codec_interface_contract.md +a0b63ab2dea4807ba5bc174d77f6fd6706859f71acc587c5788d580445bc057b release-20261107/source/workspace_joint/mira/docs/world_model_stage/01_final_model.md +1ad7ab4e52edcfbdeb81b342da65eaffd1d347629a2f575efabea5153cd6861c release-20261107/source/workspace_joint/mira/docs/world_model_stage/02_data_and_cache.md +45524cee282a79ce7317834e2e8a173bdb81ea9ab540af9e11fccef979101f46 release-20261107/source/workspace_joint/mira/docs/world_model_stage/03_training_deployment.md +56d99815f76c895453f5fa522d630fd365a26512b0056aa5358c226d672ace40 release-20261107/source/workspace_joint/mira/docs/world_model_stage/04_results_and_handoff.md +06eca3c3440a1dc49b58474091fb121474b11ab898998e53d81cfdc8ee9503b3 release-20261107/source/workspace_joint/mira/docs/world_model_stage/README.md +109f78dcb0fe4fe8582a25fe673de951a814d8a6a28195c8c7c357c25b69dc10 release-20261107/source/workspace_joint/mira/docs/world_model_stage/world_model_stage.zip +bdc00a18a6eb4cc644a30a3d3c1d78d582f2640b75c2f52d132c6d4a4e3578ed release-20261107/source/workspace_joint/mira/docs/world_v6_stage/README.md +2eeec69c2881e661debc14c5f01ad7be451ea5341741d1e3296469488d7365a7 release-20261107/source/workspace_joint/mira/docs/world_v6_stage/deployment.md +189725fd54795ef880d838e0750947c76cf80f1289e690b5bed0f955c07b87fe release-20261107/source/workspace_joint/mira/docs/world_v6_stage/smoke_report.md +bbc6b066fad58ced9b5117ccf59eaf8d345fd5dcf29207716bed8c569ebabbc8 release-20261107/source/workspace_joint/mira/examples/README.md +2ebb0e14ddb8839d8b0c569c36bd3de687128c366d8f812b1c362830bc4afe9c release-20261107/source/workspace_joint/mira/examples/explore.py +214418f3c861dfa87ee72804d0ec8dd2b976ddc3b817848f89f87fd074a7153a release-20261107/source/workspace_joint/mira/pixi.lock +aea63188546716cad6f5cede557974a0322cb1f27f6399498204371fe22acb3c release-20261107/source/workspace_joint/mira/pixi.toml +fa62158ce364dc9fb24b2be539ba520139ff79bba204646689b00e983bc91b14 release-20261107/source/workspace_joint/mira/pyproject.toml +4247c23bc9a7b2c43831232cf3f4efd8163f7c3e048a7de0e9b3c63073fd4894 release-20261107/source/workspace_joint/mira/scripts/README.md +2788ec8d663911c7247db668c3adf4f5c392338b627ab786351b66979101c5ea release-20261107/source/workspace_joint/mira/scripts/audit_robotwin_wam_data.py +630c5b5e089817c5a87bc1d219db298eaf2619404112c794e39c0f6c5c91a7d1 release-20261107/source/workspace_joint/mira/scripts/bench_wm_speed.py +051a12d40ff6075ba6fd37795e156de9936c2355e00fe4b5d5b34c8d4868ab3d release-20261107/source/workspace_joint/mira/scripts/benchmark_robotwin_latent_views.py +6f9f372ff218dd16be01ae298038968f567687f50cbdaf6f82d0ad6c7f44fa40 release-20261107/source/workspace_joint/mira/scripts/build_action_future_cache.py +0eacf1509b5863d7bbe62cbf7f56d77522265c5b8c3e72b5e6519c01fa31a30b release-20261107/source/workspace_joint/mira/scripts/build_joint_eval_language_manifest.py +bbdd1907837272408c029418101b455bacdb5dab0499f08f473f9fe4e5adb71c release-20261107/source/workspace_joint/mira/scripts/build_robotwin_action_manifest.py +7416d0b1c1b8cfd078ea7cb72d6a75cc6045054ead2a2db7d7b5f4221e87efc9 release-20261107/source/workspace_joint/mira/scripts/build_robotwin_manifest.py +cbf4fc25e590a7af5c0fdc7eb5fc472341a86fb2076712ee1ebd44c4a1b65220 release-20261107/source/workspace_joint/mira/scripts/build_robotwin_wam_manifest.py +8338972aac82216313bfa836ce902ab1e1154546c16264f30c30c8ddf9ab4e92 release-20261107/source/workspace_joint/mira/scripts/eval_action_head_offline.py +376df26de319164d40ffd617fadc2b2fa56d7a5adb6f508b1aab9963c603d075 release-20261107/source/workspace_joint/mira/scripts/eval_action_v6_checkpoint.py +0db3b81ce56e0eb0be34868539496f9c3d7847738291c8bb22dc78173cae3933 release-20261107/source/workspace_joint/mira/scripts/eval_bihub_wam_offline.py +a64f3dad464e0f8aaa7a56910d811cab75ed4e75f8a6e8ae38feaa281bffcf4b release-20261107/source/workspace_joint/mira/scripts/eval_world_model_offline.py +2f5b9922f61327f4f7c3ca573be4bdc3a08a25b27c450f0756fe53b09665e940 release-20261107/source/workspace_joint/mira/scripts/export_joint_world_action.py +8edd7bd865b5a35666f8d8c47813ebf9fbb52a227fcbe99fa4725408e002cf30 release-20261107/source/workspace_joint/mira/scripts/filter_robotwin_manifests.py +1b6cc623fc0d369dcda5ae9cdc61d4c81b798f1d25013859333bc101ee32a572 release-20261107/source/workspace_joint/mira/scripts/launch_action_head.sh +c7837fe4985961adc2da91f4e61acc5be3e862a30f8a15eb6a72c12e9a50ecc7 release-20261107/source/workspace_joint/mira/scripts/launch_action_v10_h1_50.sh +881ba839dd7ad89d16742c886c3b0ae1f0d2c6cdcda2dc47a9332d63517c483a release-20261107/source/workspace_joint/mira/scripts/launch_action_v11_pred8k.sh +790b1e55036565d93df86f1255f66b3b975da51d9e4dae437e379e19592e005f release-20261107/source/workspace_joint/mira/scripts/launch_action_v12_epoch.sh +4c05201b67d2de4980c3d822ae6b31a0939ff56cd52cc17048a27d61be7857fa release-20261107/source/workspace_joint/mira/scripts/launch_action_v13_continue4epoch.sh +1f9046e158d7e707e5d041d1f4858ef3df13e3f90ab54b57f899de80e3c62f53 release-20261107/source/workspace_joint/mira/scripts/launch_action_v6_continue100k.sh +8eb10069f2bffc73bd02fde149da9f19c9215d2f037b87398056ec08eb182e1f release-20261107/source/workspace_joint/mira/scripts/launch_bihub_wam_world.sh +883fa0c48f352acdc1b4970faac64b362ce9cae39f09079ca73ba24c53a5afe5 release-20261107/source/workspace_joint/mira/scripts/launch_joint_world_action.sh +382084e1a1b91392e604811b7b2839d15704a502916ff2f37ec14b6265524234 release-20261107/source/workspace_joint/mira/scripts/launch_world_v10_h1_50.sh +71390b486842f00c7f6a02442c7f3342c8316f0f99d20e542cac787fb4cb88df release-20261107/source/workspace_joint/mira/scripts/launch_world_v11_continue30k.sh +e545db9002b9df146666fff249c0bc4b8a27d1398f1c86cd3a01292dc42776dd release-20261107/source/workspace_joint/mira/scripts/launch_world_v12_eval_aligned.sh +98daa5531293cfb63aed80520d57ee114c7002506af901b4e6697286147da8aa release-20261107/source/workspace_joint/mira/scripts/launch_world_v12_largebatch_remaining.sh +1b25e341739fe60c6e6f119b33ac749bc7e25213f8cd30f958b50997d40c1345 release-20261107/source/workspace_joint/mira/scripts/launch_world_v6.sh +d23c77635fe62b1ab40eea46ce7e934e19414c274f162904fb20ee4750cdaf96 release-20261107/source/workspace_joint/mira/scripts/launch_world_v7.sh +b702871a83f6a590c1fc2260c4f55fcc255375898adbbbc5393e9573e998c9ca release-20261107/source/workspace_joint/mira/scripts/launch_world_v8.sh +3b81a3f6b110952afa016cf8ae6b7952b522ba58c1097e2ab832079d12eab3fe release-20261107/source/workspace_joint/mira/scripts/launch_world_v9_episode_start.sh +a76a6c60565e1fa24037b25d282251bff780fe516aaad997327f80b609405005 release-20261107/source/workspace_joint/mira/scripts/maintenance/diagnose_robotwin_expert.py +c9439e3ee100b3940fd75a5eb5c6ac52bec1d771791753ee6063bbf3eed9093f release-20261107/source/workspace_joint/mira/scripts/maintenance/eval_color_pair.py +e4a8b09d63956001c17de7fb67e50cadba6781554b5ba6c1fc390ae129f69a2b release-20261107/source/workspace_joint/mira/scripts/maintenance/eval_prompt_factorial.py +d9d976aef63ad8669d02866c83cd645024f03d345b329180f7156d6f5b24310b release-20261107/source/workspace_joint/mira/scripts/maintenance/eval_prompt_override.py +13de34ce8a7ab913eba6423eb633434e78370995d310a9e1c9034e5347ac8356 release-20261107/source/workspace_joint/mira/scripts/maintenance/install_hf_release.py +a064ee0326853b9231b901f73294faf8f7b0f7a30ec6ca676a409ce000708a95 release-20261107/source/workspace_joint/mira/scripts/maintenance/monitor_joint_eval_gpu.py +697c8a37278e12a820210eb9334c829e0cce6d05b26588d97aa09de15f681ed5 release-20261107/source/workspace_joint/mira/scripts/maintenance/preflight_joint.py +c00806f00661b6de3890f55733e5cf516bb14a5ffded7059f2bc4e8c5612ac1f release-20261107/source/workspace_joint/mira/scripts/maintenance/preflight_robotwin_closed_loop.py +c80784c5aad4d21fc4f34d1adc07ce727204766a5ba5f2bba0d8543e070b0f39 release-20261107/source/workspace_joint/mira/scripts/maintenance/prepare_joint_eval_resume.py +c7ee73db8d0a2eed264f91af687a8bfd7ff8535f74c4f335bd2c79087ea7228e release-20261107/source/workspace_joint/mira/scripts/maintenance/run_formal_offline_eval.py +58093f8e2b6e3abc9215d37e82508c769f3d3449d306fe27d7f0ef1dcd28c70c release-20261107/source/workspace_joint/mira/scripts/maintenance/run_gpu_validation.py +84dc31871b0525603ff2f02c5eb590823762880bb931a657aef60d64e869c0a0 release-20261107/source/workspace_joint/mira/scripts/maintenance/run_joint_eval_local.py +e06b52d9774f419a34d2ddb5acf748a7904627ac3df7e55d937383a7c1bf5a98 release-20261107/source/workspace_joint/mira/scripts/maintenance/run_joint_robotwin_formal.py +60d673ea847c75e0750437a297bce6831ead2e54bdd289f10b33c8242f3fe398 release-20261107/source/workspace_joint/mira/scripts/maintenance/run_prompt_ablation_resumable.py +bbfa338c4ac8a2ddbd472792cfada757d1e7eeaad4ebac4ac56325996c557035 release-20261107/source/workspace_joint/mira/scripts/maintenance/run_prompt_validation_case.py +2c2eb9247c9e14b6e9db559bd0bbe37e025810544fa7195ffba14d55625d47fd release-20261107/source/workspace_joint/mira/scripts/maintenance/run_robotwin_eval_prewarmed.py +319a6e996e242d95a89883c9bfc7632382a9a380f0e1132a2bd5fd2ed1406085 release-20261107/source/workspace_joint/mira/scripts/maintenance/stop_joint_robotwin_eval.py +1093a66500a7e807958496f3a97a7cedd385b302df628fe352ddfa3190bb8ddc release-20261107/source/workspace_joint/mira/scripts/maintenance/summarize_formal_offline_eval.py +ba1fa384e6e5840d6cb825f2348b890645c606387b7297a25e7af77cda64b8e0 release-20261107/source/workspace_joint/mira/scripts/maintenance/summarize_prompt_validation.py +5085e94fd3700662ea590e73b06868b06f21b165d9a3f2910b5c7f60beb1ee20 release-20261107/source/workspace_joint/mira/scripts/merge_robotwin_latent_cache_shards.py +fafa41149f44dfdfd8363b482afecd8d1e8350f8f73f5a4654b263f901fe0842 release-20261107/source/workspace_joint/mira/scripts/monitor_bihub_wam_pipeline.py +3c276dada543c170226692d32e908d7428f5f149295cced63bb6569383f3d3f7 release-20261107/source/workspace_joint/mira/scripts/precompute_instruction_embeddings.py +f99a7c699221a78b20af3d759ff02ea0a313903ea78e9873a9942401e68abac7 release-20261107/source/workspace_joint/mira/scripts/precompute_robotwin_latents.py +a18ef1a51cc070e53eab8618756fd9f50f6ac25bcc50024cdc51b790b65d252b release-20261107/source/workspace_joint/mira/scripts/recycle_world_v12_after_delay.sh +7624dc6934da5d8ef02dfc981f6ed63cf7f523349196ceeeaad8b7934828d7cc release-20261107/source/workspace_joint/mira/scripts/rollout_world_v9_sampling_steps.py +b186f4e7b2e91339c4d7428490ca650899ba711a5abc5a05ab9a137c5b129541 release-20261107/source/workspace_joint/mira/scripts/select_action_world_weights.py +f09b9422dc6de44df55a7df5e7a0f2156adfd2b666ebf3142ffc865bea556c80 release-20261107/source/workspace_joint/mira/scripts/summarize_robotwin_eval.py +2515c885b604596d63a3e604ad85f01bc689e3cf8495e462e1d0545ddca4d6b6 release-20261107/source/workspace_joint/mira/scripts/syncnet_torchrun.py +b1e26615d3db6c130843c2ec082a95e0e09d1fddd32875443ffdcd140b22c7e8 release-20261107/source/workspace_joint/mira/scripts/train_action_head.py +62efb4fc11ddb5940d85f8cf4785f552c5d5ef89e72a5240336da5ecfb83e873 release-20261107/source/workspace_joint/mira/scripts/train_bihub_wam_world.py +7db9dff5bebb03a25a58a4b096e200923d7a32536f183620551c2be3f8f76208 release-20261107/source/workspace_joint/mira/scripts/train_codec.py +30fde8f8a80583e04ebd06011a17b514ee49acf17f3120deeb594ff0be6ce1d6 release-20261107/source/workspace_joint/mira/scripts/train_joint_world_action.py +4ca17bf1aa9bce3f9075353fe2fccbf2ee872b43582d6eb8f881dc1a0701a52d release-20261107/source/workspace_joint/mira/scripts/train_robotwin_codec.sh +0385128f9da1c2d36f9a75a55e767a28939fa42201a52a50b1d16ed1ed5b2ea5 release-20261107/source/workspace_joint/mira/scripts/train_world_model.py +2c61ce97cd6429e711f6fd38244e3b7b40712a432120a1594fc46b37a06f1674 release-20261107/source/workspace_joint/mira/scripts/validate_joint_inference.py +83393edf446188ece0de93389f83cc2eae3ca08f1c7ae507f214e528567d32d8 release-20261107/source/workspace_joint/mira/src/mira/__init__.py +fe36fe22ec0e9172200c98ff4a360fff9054f52820947b314b47d52e4b9f2dcb release-20261107/source/workspace_joint/mira/src/mira/action/__init__.py +00d8d898bb2a06ae926112230f0769c198a397475011c5dece6acd84f94f02d0 release-20261107/source/workspace_joint/mira/src/mira/action/checkpoint.py +bad6cc3eebad4095004747266754fef0b91bc5eb2b99f5e0296fcc01ddb3ea7c release-20261107/source/workspace_joint/mira/src/mira/action/config.py +bffbfea8eda075c4beb34aed497de8e887cca6dff5632c4adff0c3c24ad95c51 release-20261107/source/workspace_joint/mira/src/mira/action/curriculum.py +9f5ca36e56906621c340f7d2f810b44fa7308070c6971a8bcf74be5e9b9abde3 release-20261107/source/workspace_joint/mira/src/mira/action/data.py +bdab76b9b3cf9939764c181af8e92353700ac96dce444c25dc9912d7ba421923 release-20261107/source/workspace_joint/mira/src/mira/action/flow_matching.py +d979e6d4532f604a22079f24726268fdd6c6258151f6174deef369a0998afaeb release-20261107/source/workspace_joint/mira/src/mira/action/joint_action_flow.py +d7298afbf8328d07e8f9988fa412595ca5963e9461d02222d9b0af009ef8e4a7 release-20261107/source/workspace_joint/mira/src/mira/action/visualization.py +00322d01158ce3936efb0c930786641241616c20a195783d8f3a4b40147fcb1b release-20261107/source/workspace_joint/mira/src/mira/action/world_checkpoint.py +c9b9ff25a39a6ca68cbde164c3ca6c9058dafac1c6b8b287be265b1a754f09b3 release-20261107/source/workspace_joint/mira/src/mira/action_v6/__init__.py +6bcc4a18efdf2f61dd19ab6db2dd665fe9a4f15591aa7874366c42f96c45fc44 release-20261107/source/workspace_joint/mira/src/mira/action_v6/layers.py +8ac2ad5b16661367811ce2148c77427fbed7afe936ac924dbc6789fef8b09bce release-20261107/source/workspace_joint/mira/src/mira/action_v6/model.py +ab97941a6f648d79bae633ab12fca5770bae1d8c5cc66f5a27d6f73b6c3239b4 release-20261107/source/workspace_joint/mira/src/mira/benchmark/__init__.py +a32e264423c4b09d699da90ebb53fae0becb3c57e7fa905dc2c736abfbb4815d release-20261107/source/workspace_joint/mira/src/mira/benchmark/robotwin_v6/__init__.py +f3acdd4eb71cb0a9ed2a3c90db55affb9c98d6ff04f7f510443dee12c652ab98 release-20261107/source/workspace_joint/mira/src/mira/benchmark/robotwin_v6/adapter.py +4a3b45648e30ea06b1fcc2bde406ae943a78b76d395db7c6caeac0cae729d642 release-20261107/source/workspace_joint/mira/src/mira/codec/__init__.py +a489279c581a0bb867110140c9a706eded45de3ed25040017abf0981f6120a49 release-20261107/source/workspace_joint/mira/src/mira/codec/codec_model.py +575ab1d5f8ff7362de52a725e991d7ca9494a57a331d44524e66e6d7ca2a70be release-20261107/source/workspace_joint/mira/src/mira/codec/config.py +7621b8e49446c62f07c116068185ac1dbf3c0daefcafd3331c3e3a2e7a739b9f release-20261107/source/workspace_joint/mira/src/mira/codec/dino.py +e38445e243c7ac3c3f3adcc04a81d42e987188c2592a4011c514682608860305 release-20261107/source/workspace_joint/mira/src/mira/codec/lingbot.py +8e1f02be43888070fbc71bb0128cd8a662e18ccfeb02f9c5aa6797a64fa47c80 release-20261107/source/workspace_joint/mira/src/mira/codec/loss.py +dba0689156229b22225d4a8644080792bc4739b83ac1630b61967aa230f8792a release-20261107/source/workspace_joint/mira/src/mira/codec/rae_encoder.py +58a1ca042a792a4e5c922a36ebfa8b4ea0e1c9b5d81e479e41bdf449f85ee2d1 release-20261107/source/workspace_joint/mira/src/mira/codec/vit_decoder.py +5b6f4f056056c3501d91b6b2b0b61beecf69780125a35809b1e47c3bebb731dc release-20261107/source/workspace_joint/mira/src/mira/codec/viz.py +ef0178cb63110a5dbbb7fe4274c884211af4561699b823badc7c2b88a012e979 release-20261107/source/workspace_joint/mira/src/mira/data/__init__.py +daec22b12d165d090fa43d2613f6a15c02bf7a71bde0d7ba4f807588ffa335f4 release-20261107/source/workspace_joint/mira/src/mira/data/action_v10.py +d1d4cc5cb08a9b521b503fe45ae25225c968da3e50c134607de8de2168de07ae release-20261107/source/workspace_joint/mira/src/mira/data/action_v12.py +3d2d1cb08cb0165de45059e1d9c2ab28ebfcb6bc39c2e27ae764f1e43e9952a3 release-20261107/source/workspace_joint/mira/src/mira/data/action_v6.py +64eda353edbca0e89f120bff142585edc4256b36d83eeb804923eb3a3d9b5a78 release-20261107/source/workspace_joint/mira/src/mira/data/action_v6_sampler.py +ecf71a9eac0db79d1a7aa060a8e2cb164490a2a5a25801c0c9c28f8a103186d6 release-20261107/source/workspace_joint/mira/src/mira/data/actions.py +b1c9bb65fa3ae9265389665bed09fbd8986083766e068e773f8b25665c612ba5 release-20261107/source/workspace_joint/mira/src/mira/data/batch.py +349cf7fa025a46cdc9eb14d6ed6eb28cc88bc340326712a336bda81ccc0fa6de release-20261107/source/workspace_joint/mira/src/mira/data/clips.py +934fb88de54b1324de4be43f77f9e933213005e6b3cb4646547f9e68592876cc release-20261107/source/workspace_joint/mira/src/mira/data/dataset.py +103ba56d0f186bde54207d168aa476f4dbf29756dec61f71e89c6dc5fe403274 release-20261107/source/workspace_joint/mira/src/mira/data/decode.py +efb19b580c06084c7ae24d236718e6dc69f2f5e927901fb86580b62387f98404 release-20261107/source/workspace_joint/mira/src/mira/data/events.py +d71fa9d1e87685ab4c1ace7594442b12c578f824ffc372b194d5a925c5549c02 release-20261107/source/workspace_joint/mira/src/mira/data/joint_eval_language.py +60d9cc97b325eaed18a2c7b907ef0eee0813fed519e0e67f04e24a3411d25993 release-20261107/source/workspace_joint/mira/src/mira/data/joint_online.py +5ec76ff643268b503e96a671a9a06da6c4202797111e843fc07db04b27635367 release-20261107/source/workspace_joint/mira/src/mira/data/physics.py +cdc2853ac9a469aff4ab478a418bdbf112f70b5fa7634674d13f2689f11c4cf1 release-20261107/source/workspace_joint/mira/src/mira/data/robotwin_loader.py +fbee8ee24edfcfdaa42c6f6534c65efaa4232e3b0d2d8f97e1ffd39a45f7614e release-20261107/source/workspace_joint/mira/src/mira/data/robotwin_rgb.py +e69655d5052ad55bb15d8baa81bcd79997bb4e2fa23757089efa1bb8530893c3 release-20261107/source/workspace_joint/mira/src/mira/data/robotwin_wam_loader.py +8b8fbde91e5402e928003b17c28219c8964e7c9475b8e3c85ac14c7c6b61c5c6 release-20261107/source/workspace_joint/mira/src/mira/data/robotwin_wam_schema.py +f952491a1ea5cbeb3792a4d4f4e144c0aca906d73a47f469562c9974077d4d93 release-20261107/source/workspace_joint/mira/src/mira/data/schema.py +7e2f270c8aa90412897a615b1a2f58605aaf10c57554d00cd45b33a7eaaee3de release-20261107/source/workspace_joint/mira/src/mira/data/state.py +e01bef8d30fd775c040f2ed8a25a5b02e781e543078fec66b5bc086d219244aa release-20261107/source/workspace_joint/mira/src/mira/data/training_loader.py +e4f14452d59283a53155ca83e14a271e38f84e9d6c059c304ec6ee1d9ae02301 release-20261107/source/workspace_joint/mira/src/mira/data/viz.py +d4309762a729dfa359aa728d69bf028945d63600e0f2f5d953ccdf07fdd973c7 release-20261107/source/workspace_joint/mira/src/mira/data/world_v10.py +1a5f02e048fd72690eb949a895733cf589b7aee9dc2369e12ddc2a0899986190 release-20261107/source/workspace_joint/mira/src/mira/data/world_v12.py +651c4c16a60f015ab14b23aabdbbc1158f0cdf23defb6d1b41b0a2b3590e368a release-20261107/source/workspace_joint/mira/src/mira/data/world_v6.py +c9a9508d53d29492fc674e921fa0c21105c3c4c4e142fad47d3b11e5ac5e6bbd release-20261107/source/workspace_joint/mira/src/mira/data/world_v7.py +9a81df5886b27d4ebe6f081005cc05b85796c27349ae922703521a9a6e4334aa release-20261107/source/workspace_joint/mira/src/mira/data/world_v8.py +cdd064730d34b75a2fe1e12a711ba731eba4980fc8e05bd95e575522453555d0 release-20261107/source/workspace_joint/mira/src/mira/inference/__init__.py +cff62d0b1b1daa0d9ef4d08dd18cfdcb77a1c1441a69a73b0d4eeb8b4f6b18f5 release-20261107/source/workspace_joint/mira/src/mira/inference/bihub_world_rollout.py +1d1d849514c24b1009d406b3224088ff5b30524f6a8439f307d9d94bac396a89 release-20261107/source/workspace_joint/mira/src/mira/inference/loading.py +6d8b20c20cbb241b0d65587306d7b0e357d8f4698973e30832cb3609fcc5d51e release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_action_policy.py +0cddab3983d7157cb329492205f1b2f3958431e603560cd6cb7f3dec5edc9abc release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_joint_runtime.py +ec3198f85c308b48b682ef3245ae9aeb557495c65299d3ddb551ae8af5ff5dc4 release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_v10_runtime.py +0f45608c898e7037e819f0f477d0ce08eff1f7e125f49e8ccc4e09420693393a release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_v11_runtime.py +53f3dafb8e874321289f4eb2c312072de23515204bff7b9dc191b28140f70279 release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_v12_runtime.py +799945070c669f86b73ea44df68279cd547601559e7b7a7a07ce1196b832648f release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_v6_runtime.py +736922b1b2f3a8a67ae9f8e2059c040cad3f412bdd93256f7694519f4813a66d release-20261107/source/workspace_joint/mira/src/mira/inference/rollout.py +d8d35d2a0aac9f64fc9706bb3fa7e54565971277e664bf9d87e1b52c607ba185 release-20261107/source/workspace_joint/mira/src/mira/joint/__init__.py +7c4c139bb09f03781d7ad89fc135db8fad3c9c210fc3fd0409c490ba68fbc8d7 release-20261107/source/workspace_joint/mira/src/mira/joint/deployment.py +a98664202d93d0ed3ec13775593aa9e85c603446313be2d847e563fc9ec8870d release-20261107/source/workspace_joint/mira/src/mira/joint/image_contract.py +ef8bf30b68d1b09c9f8a41301cb0bfb25b5ee30fa77c06ac0d3cb4b4fac2540b release-20261107/source/workspace_joint/mira/src/mira/joint/model.py +3c67f34b480f6b668bdbabb85d7b6dc3b2e2e835916801561409a95338600642 release-20261107/source/workspace_joint/mira/src/mira/joint/paths.py +73c065c77979eb8191d38ce5f288453a19edfc48b9fc7aa56446b1c1c995977d release-20261107/source/workspace_joint/mira/src/mira/joint/training_utils.py +e582f0c97d90d4da598296e74a9fefb7ae454664a33a1c040cbe4570646bd892 release-20261107/source/workspace_joint/mira/src/mira/ml/__init__.py +e18405ab0f8b62de7ee5b526b3e37e505c39a13537735d63fce7800d54302778 release-20261107/source/workspace_joint/mira/src/mira/ml/attention.py +db19fb7378e0d783d352146de351bb8c9225306500c219aa642eeae89ab1f212 release-20261107/source/workspace_joint/mira/src/mira/ml/config_loading.py +cc28a6e6b0a89ada2375449975f1c4b638aa6a9c531de1d7ba329c46905ee05a release-20261107/source/workspace_joint/mira/src/mira/ml/image_config.py +a18ff164029f5634ba19a153a2187467062db937a07f42eaefb4b99b9cd4dbb3 release-20261107/source/workspace_joint/mira/src/mira/ml/init.py +bf3e34d120574a6202e6ad374adb9686bd6edcde5c6eb40a3afbff2229564196 release-20261107/source/workspace_joint/mira/src/mira/text/__init__.py +1c4b03dc1c271ec7b2531dd0e5064c6e856e6d052dd8cb43655601844ffe0898 release-20261107/source/workspace_joint/mira/src/mira/text/wan_umt5.py +eedb6da2105caefe40b7f54bc75b868a9912eaafe5984722b30104f3514e6725 release-20261107/source/workspace_joint/mira/src/mira/training/__init__.py +e9489ed95e130c5d0d271908aa7de8e458cdcae2416a695bf3bdb77f603c189b release-20261107/source/workspace_joint/mira/src/mira/training/action_v10/__init__.py +cefec13bf4a1d4b5d55a96d7c4e9d0a18eb1b9297ce0a9635a59f65f3d213395 release-20261107/source/workspace_joint/mira/src/mira/training/action_v10/build_predicted_cache.py +31292f9de98fc573abb1ab10f6af679bcd81fcedade6b815f3f10d937152ce1a release-20261107/source/workspace_joint/mira/src/mira/training/action_v10/export_state_encoder.py +2c5bb164a089e7c2bc215d72eb0225e9ec4c62449abc42f95ab26e19c4a2e8e1 release-20261107/source/workspace_joint/mira/src/mira/training/action_v10/preflight.py +c993aee66b07be9816744b5bfe7c37f3393f5fdcfde32216d35b532434ece4f7 release-20261107/source/workspace_joint/mira/src/mira/training/action_v12/__init__.py +e6e53a674106c00c17c89e3b48548f1f5cd3a1c48ddb79a6556243ee5a3a3757 release-20261107/source/workspace_joint/mira/src/mira/training/action_v12/preflight.py +9ff019d07c0e5aa99378576a933c4c696b06c44349e338298e96d90efba96565 release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/__init__.py +fe9ec3a33577304fa753195dbbc10b750826c6a3a6745d008762dd636ae58cf0 release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/artifacts.py +1fe04883b67dd5f5c3226fe138888464b4d2ee340f36a91e3d1661ef70aad347 release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/audit_predicted_future_cache.py +c9fc382dfcd6986034031215e1981ab25423981810cfce8734fd11dc51212a30 release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/build_critical_event_index.py +46507a9d3f91e02905a0c3209c55531246ae8cb203fd2a85989971e791487aef release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/build_exact_cold_cache.py +9784cbc17a93a5fc91ec971d239538aca9b0256015b5e053e122e32de7ef4c94 release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/build_predicted_future_cache.py +250bac6b4b0a6010f9c5dcc34f6d39469fe597edcef612fdbdf8b92f19f80517 release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/build_statistics.py +4e931985fe4740b8f93a64740f4a539548e12ec43c066575c7fc744b7a15c03d release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/checkpoint.py +66b387996fecaab86202f7516e0d99411aa3dbc8fd4400d80d6c016f2fc1c1f6 release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/config.py +96f81b8cabe090f4613e44ee284d5489c49a81223c99bd74a0e430531100053a release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/factory.py +29219c140b3a339635b6657cc2b1d69f827e32669448ff213947aefa906564d8 release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/preflight.py +f8dc57f3e2125486d5dabfecdd853bc7272a5418f3ebc6f698523061a1e3321f release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/select_world.py +f19e07643441d40c6160cf2543a8406ba2ca47c04c3e21db17b04555591dcbcb release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/train.py +bac5253bb9ade7f2755228c39da2a3c5e0894f3b857a6133eb27466442e63a92 release-20261107/source/workspace_joint/mira/src/mira/training/bihub_checkpoint.py +62e2b145d25854143cbaad6db957e36746aa23bfe518fc835b2bd4946a6b3d5b release-20261107/source/workspace_joint/mira/src/mira/training/checkpoint_manager.py +064a075b024ed339e0691b1c02932d6a1ce744b44a0cc729a76c29ae3df4bdbc release-20261107/source/workspace_joint/mira/src/mira/training/checkpoints.py +24c5e7db2c758466d3ef6d716249d140c468ef6a3293a69fc4a003f1fba1b806 release-20261107/source/workspace_joint/mira/src/mira/training/distributed.py +3e13cf40c10bf4650664ae2daf3cd559036560a413a49e8fc34191adcfe838dd release-20261107/source/workspace_joint/mira/src/mira/training/ema.py +06aaa157eec79d745cda99d559ba9bc7b9ced32d6c01c685b91691e94af4cea9 release-20261107/source/workspace_joint/mira/src/mira/training/lr_schedule.py +722d317a8a1802608b9bde860170bf9bebb840143bd23dd5da726f4752fe8916 release-20261107/source/workspace_joint/mira/src/mira/training/metrics/__init__.py +a4e22c464723b5b786d3cb629ed46c5c5760703c55769c22c5dff5150e22c58a release-20261107/source/workspace_joint/mira/src/mira/training/metrics/distributed_metric.py +1e27435988c83941618b3a7bea9b8f263dca2e811450be1ad87380ca529cff59 release-20261107/source/workspace_joint/mira/src/mira/training/metrics/frechet.py +81ad410323e9b430a59471befc605cf0ff0a30e6ec774914d57203d4352cb3ff release-20261107/source/workspace_joint/mira/src/mira/training/metrics/image_metrics.py +a1b948ce9d55c2cbaa11ed2a603411ddf3c196310461fc1d74b0aa83b5d0d2d1 release-20261107/source/workspace_joint/mira/src/mira/training/metrics/world_model_metrics.py +e9094881fd5eba0782ef7ba480d03645914d29afde16a063ab451c931009a0a6 release-20261107/source/workspace_joint/mira/src/mira/training/swanlab_tracker.py +fb5d01fbd9e8d7de4791e3d8c8896268ec43fd2324369450db3506176f1142fe release-20261107/source/workspace_joint/mira/src/mira/training/tracker.py +2d818e261f8d570bc1e086deb6413e724b280c2386123251ca50d23e4578d30b release-20261107/source/workspace_joint/mira/src/mira/training/visualization.py +934334d8516b87a5a8b96f82040c020b3be8bad221039987a02a78e01eff0a28 release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/__init__.py +bf85682ea1bd57a270a6e8900eed5fe647fe9b64c29f259b5530fae1804f557d release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/artifacts.py +d87b617ba0eb11bc90b15a0e34d4b64566683d62768fd2fff4cae0579f8c18c6 release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/audit_anchor_cache.py +5553d11756548807f7adb2ead3d5b3841e7750970545656da00651ee4d1602f5 release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/build_anchor_cache.py +d1d737a817718bc75ae776424257aa4e32222f059c6153a062c76979d5e56a80 release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/build_window_manifest.py +37e4e3be1f386f224ad84b06e5e655ddc18ce6e0f135bd150eba34320a864163 release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/checkpoint.py +5d260fc189ed442e3690d97c80ca00d01f2c41234341f4a4614b5988dedbf3ed release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/config.py +d93b9718d8da3c6d3058af01d4a0a7f4f76f7b24eaeed31b4ca7fdb1cdfa527d release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/eval_bootstrap_checkpoint.py +1e88293b2334347eba2b634a6abde262a7b2fbf5e58560c0d332666d92fd570a release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/eval_world_v6.py +d32ae848af2112428f43f333de3ed2bdb5b9b759e4c1d25d445631a782cbab6a release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/migrate_checkpoint.py +1f8ec6daf3f5f7f9c49af7fa31424fce08643ee340a4e726c6a14c8145b2a80a release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/preflight.py +3ad2621db8042fae3ebd6a797ee260b5bbe32e8b8e2501dd28dc60528a92d974 release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/prepare_qwen.py +11acd8cd8fe04b6301fa6f29b8d7cdead73ea582a8ddfc607ef23c76f3cee2dd release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/rollout.py +8c043c689a85fd862a94555b95e7723b2d8b5d7cf5b4fe71c7d6799684ade690 release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/select_anchor_checkpoint.py +df355167228cf36d5eefe75de7588f0ad07ec78a599e261857c047bd08614f09 release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/select_source_world.py +e0ba49e7e228aaef7bb7ee8882099cb3258075a2bc0f86e9491de91ccea9e281 release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/train.py +b094e7d8712bfb529f22b284f340d52716bdfb5e733af7ffc96956d8ab0a558a release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/validate_qwen_contract.py +c75d7fe4eb52c040a877729529ea700d785e54c1bca3d037d458109086389357 release-20261107/source/workspace_joint/mira/src/mira/training/world_v7/__init__.py +686ecb4328244cdee1667dc6f0629d42951fe45129921949da88383182b9d31f release-20261107/source/workspace_joint/mira/src/mira/training/world_v7/build_qwen_hidden_cache.py +b41d427f6dfddd639ce9f3211c61f9f052b70bddd049c1c70c505ad5fa18d44d release-20261107/source/workspace_joint/mira/src/mira/training/world_v7/config.py +edb9b9edaf84ace0223fca5e3d8aa741ce5c292cc470ecf491f8a72a6a5df4d5 release-20261107/source/workspace_joint/mira/src/mira/training/world_v7/preflight.py +5e8a9f0b7dc761e9c314c5e3edc9d56a06c3ee81d03c8afca345c75fab34f095 release-20261107/source/workspace_joint/mira/src/mira/training/world_v7/train.py +bf5a920f86c06279978d9a4305a1190a0a4983fdb290935a5e92e17287d626bc release-20261107/source/workspace_joint/mira/src/mira/training/world_v8/__init__.py +df10dff2c2dc08b229247ce446b989d388e0be21a14dc138a121f3db45dd0a92 release-20261107/source/workspace_joint/mira/src/mira/training/world_v8/build_v12_sampling_contract.py +430106a97489f15d17d44b1bb9944fcfdbddce67a7480eb4df4c79f726b908cd release-20261107/source/workspace_joint/mira/src/mira/training/world_v8/checkpoint.py +ed591e334f56c8bda91ff1d6914ea4c2336c6d058ec63f4598eb8e320e19c577 release-20261107/source/workspace_joint/mira/src/mira/training/world_v8/config.py +34ba02b07a69591f70453a3dafaf257e818f151e474779603d268ef5b8901eb0 release-20261107/source/workspace_joint/mira/src/mira/training/world_v8/named_train.py +5cece7670ca42cd50b5755abae266e9a62a83dc7062149d326b814cedac04a6b release-20261107/source/workspace_joint/mira/src/mira/training/world_v8/plain_train.py +a30a736996878c8763652daa1079ddac42f091ff5a25f8d4ad973ac714f21e68 release-20261107/source/workspace_joint/mira/src/mira/training/world_v8/preflight.py +9e68b0917395231477112b7668df75bfde1f72c810e40f0e023f56622172bae1 release-20261107/source/workspace_joint/mira/src/mira/training/world_v8/train.py +6f89b7f631c07721d971e6f4a44c6fa138e87a2088b263f03e9d90a15eff9806 release-20261107/source/workspace_joint/mira/src/mira/world_model/__init__.py +20ddb2a26149b6856ca11deddcd814dfe04a829920992ef8209519bdf4a1f1e5 release-20261107/source/workspace_joint/mira/src/mira/world_model/actions_config.py +471626e43bf0ca96f71f8423e0420f9404f2c0bc9e4ad69c26d012a1a82630f9 release-20261107/source/workspace_joint/mira/src/mira/world_model/bihub_config.py +4fe8c194a26e52847465d9a7ef17fb6c1e8071e2065aab2b4c828a2457319131 release-20261107/source/workspace_joint/mira/src/mira/world_model/bihub_diffusion_transformer.py +3fefe739aeab73d9e3be6bce5152249728e0304a7c1b733b6b6a936f8a96806a release-20261107/source/workspace_joint/mira/src/mira/world_model/bihub_latent_world_model.py +c9c099cf26aa7ff5d63bb8ddde1e12f33a8491951ded963a03b4cc68b4d46823 release-20261107/source/workspace_joint/mira/src/mira/world_model/config.py +59f1abfd9117830bba8e9431ef969ca9440e565ee70fdd71fdd0b697e8769b06 release-20261107/source/workspace_joint/mira/src/mira/world_model/diffusion_transformer.py +b6570b4ff943960fbdabcf767c09109e210495147e5a7a2ca683054bf80f2ab6 release-20261107/source/workspace_joint/mira/src/mira/world_model/latent_world_model.py +299934c8c26a0b7e31b52594fce0b07e541f2200565270e37d6cc67d6fef56ce release-20261107/source/workspace_joint/mira/src/mira/world_model/layers/__init__.py +8b78e8edac9c89c87ce57c0b996724b1e370beb54e26b2beb95fd0ecf4416906 release-20261107/source/workspace_joint/mira/src/mira/world_model/layers/action_encoder.py +6f41ee23c3c4ce285e9ac6e0ccba5dcfd338fdf210320e36e35d14f3ab0ef0c6 release-20261107/source/workspace_joint/mira/src/mira/world_model/layers/arm_state_encoder.py +0d77bfaaab7c4c651c9fe7aa21643d7a6fbf39d85a7eee6c9629ceb017fa02cd release-20261107/source/workspace_joint/mira/src/mira/world_model/layers/hub_spatial_attention.py +6789c311763b26aa31f97e2352718443dac6794c7f53ba443e3db4273093b9d8 release-20261107/source/workspace_joint/mira/src/mira/world_model/layers/rope.py +c8e3370b3b5ca54afd4a5e776b96881d1bf548f12432fd7f5c429533e1189083 release-20261107/source/workspace_joint/mira/src/mira/world_model/layers/text_cross_attention.py +a73ad8a1f8bcacc5d1f9a393b38db66d9922c5e275f0c77b34c0f8310ad718d5 release-20261107/source/workspace_joint/mira/src/mira/world_model/layers/timestep_encoder.py +d78634f66f4d7b3e9c1be89a0ba67de8c46bd33090cfa39524ee4c2aefc31ac1 release-20261107/source/workspace_joint/mira/src/mira/world_model/layers/transformer.py +e79b73456edee2aa2bc36bbaa4b675a3f0b8fac17eb951c482ce10f81a79019e release-20261107/source/workspace_joint/mira/src/mira/world_model/multi_wrapper_world_model.py +7da79b69b50b50760a64238ad1cf8f1add18988c731a3c3fe5ee6cbfb0a9d2f6 release-20261107/source/workspace_joint/mira/src/mira/world_model/schedule.py +189f6b2670f33ccc2ea6bf8dfca8874b2eca8609a26c97c25557866697985a96 release-20261107/source/workspace_joint/mira/src/mira/world_v6/__init__.py +b01cc99107a669ea2c2c4bf7dc22d1106d2a66686d91fea3aa3a5c282109fc94 release-20261107/source/workspace_joint/mira/src/mira/world_v6/config.py +dcd23c1266ff99a653142839bd5686a4074915025a27adbbaa739761dc7ea645 release-20261107/source/workspace_joint/mira/src/mira/world_v6/current_resampler.py +56b1c0520b996fecc724ca6396759cec572acde09ad9063774602f78792bebc9 release-20261107/source/workspace_joint/mira/src/mira/world_v6/history_hub.py +461468f3d4ead00dc80fd30553aad3ea996ce3f6c64fd9c883eb6981076bbe9e release-20261107/source/workspace_joint/mira/src/mira/world_v6/latent_history.py +2724f54dba9967db4c6aa67824b1ab2812ca6da27fc77a9e8bef0954d983a7f2 release-20261107/source/workspace_joint/mira/src/mira/world_v6/migration.py +086e46c3b4a448fe83f46dd80ff03e1b7cec4931f59fce418efe9714783b9160 release-20261107/source/workspace_joint/mira/src/mira/world_v6/model.py +0c82cb6f7281e73fac6b17b2efefdbf5b7e45e69a5262499885b839609572363 release-20261107/source/workspace_joint/mira/src/mira/world_v6/prompts.py +f94162af9927512498bbf82e6063ef5a1df780e77ec670a16aa9d63f49c02342 release-20261107/source/workspace_joint/mira/src/mira/world_v6/qwen_current_anchor.py +5d2c225871260aa3ccb1647f12f31cc0fad1b54e4c9eba49ab97a1ef8c0ba813 release-20261107/source/workspace_joint/mira/src/mira/world_v6/state_encoder.py +204fcccec700af1ee1248a991a7c6ef26306618f47e8fa8d2f6bfd4d47b46d61 release-20261107/source/workspace_joint/mira/tests/action/test_action_stage.py +0566824f1ba2d091a7a48b776aced7f858eade522c559eb540c0bb82c1479770 release-20261107/source/workspace_joint/mira/tests/action/test_robotwin_action_policy.py +d15fe1fa403e5f3d3b07e58f21f78118c8f5def662e5301291611c4ade876a79 release-20261107/source/workspace_joint/mira/tests/action_v12/test_eval_aligned_epoch.py +37ffa0dc108256e6ee96b18fecefeef5e9d60afa584f860459fd55a33a1324fd release-20261107/source/workspace_joint/mira/tests/action_v6/test_action_v6_contracts.py +3d756b95a7e1dc5f4a1a46c33e53ee8bc62e97a3cda331b4b6d1550a9f75dfd8 release-20261107/source/workspace_joint/mira/tests/action_v6/test_compressed_protocol.py +378eca76c32461007a3ec807b09f9b531ed3fc129133ffeb548b381686d51a25 release-20261107/source/workspace_joint/mira/tests/codec/conftest.py +3778e71d3d7f43574cdd84edc6745c22734843f589b0629ac3a380fbcbaf67df release-20261107/source/workspace_joint/mira/tests/codec/fixtures/raev2_codec_tdown.yaml +c384b62c2402093c64a54b85347983c53bc79228013bed326c1767289d7dde85 release-20261107/source/workspace_joint/mira/tests/codec/test_codec_model.py +069161c7d6c1c574c4b072e2474738d9415696e93ef04979037523f7e5e430b5 release-20261107/source/workspace_joint/mira/tests/codec/test_config.py +8dad939a7eb469b2404d1dbf3f3f486dc6010a1a34680f743fa5717a43e034a8 release-20261107/source/workspace_joint/mira/tests/codec/test_lingbot_loss.py +0420810ef2017bf64c6a5fd1cb835e9762d01ce6a8f8aefbe7be931b7adcc209 release-20261107/source/workspace_joint/mira/tests/codec/test_load_from_checkpoint.py +a5716a33df293380af9c71c59d47e8e1500b6eeb692f72a38aadf4baa70213da release-20261107/source/workspace_joint/mira/tests/codec/test_loss.py +30f171db3aecff12f2f187669259f5d2a369a86edab8803742c595f877157b86 release-20261107/source/workspace_joint/mira/tests/codec/test_train_hydra.py +54de709472fff4c873d0074059b0cf6a4ef0bd2cb9d46ad3974c1304ca592b6c release-20261107/source/workspace_joint/mira/tests/codec/test_vit_decoder.py +53aa156b8cf45908176a01a36e91dc26f915385404a963584ad9c5f581a92e80 release-20261107/source/workspace_joint/mira/tests/data/conftest.py +ca326573e5585cd0682ddc799a455b996ad6b2f4d9133904a50af877257e990a release-20261107/source/workspace_joint/mira/tests/data/test_actions.py +e9cc663c71c0c21f77e7539d481ccac4ece38f5af24010c395ea918ccd72aace release-20261107/source/workspace_joint/mira/tests/data/test_batch.py +c5f45892f8cd5c0aa3c400e7b86ee8ec5f7242f0e317442ab05395a68426f51d release-20261107/source/workspace_joint/mira/tests/data/test_clips.py +163692716f78dd9cf036f498e27ce4e39e828137071a0237c056f927374d8213 release-20261107/source/workspace_joint/mira/tests/data/test_decode.py +9e96621744fbfd2aaa783ec3712c488cc965a3c3a5d2f188d7c7e1f47088fe83 release-20261107/source/workspace_joint/mira/tests/data/test_events.py +873c47b4cfeea011eda26f1aab154e7110136acc0a0d5dad56b99560e7802aaa release-20261107/source/workspace_joint/mira/tests/data/test_from_hub.py +210fb4354efb2a0d6a6045001a10652710be4821002d51ed11247f9b06889800 release-20261107/source/workspace_joint/mira/tests/data/test_loader.py +e4d275f900cce67c6d0155347dc2a297ff8171689557cd7459ff2a64235b9e43 release-20261107/source/workspace_joint/mira/tests/data/test_loader_clip_guard.py +9d4830b90e6f7971aa8787efe3dbc810ca376a83f6a073dd7b8b32f92bb664a3 release-20261107/source/workspace_joint/mira/tests/data/test_physics.py +6295fc532fa438738970f93f39b32d4541a1efc8a5e6c659aef54f3754572392 release-20261107/source/workspace_joint/mira/tests/data/test_robotwin_loader.py +08274a9416651d63b6ce132eebbd370193b6bade5f9e37005384a3932d07a79b release-20261107/source/workspace_joint/mira/tests/data/test_schema.py +d39182f3093f777316ee795f1e4171de213748384e30abde06e10c39403bf867 release-20261107/source/workspace_joint/mira/tests/data/test_select.py +959057be5206a507f23074c9f70b8c66ebd53ac03a1fbb455d8c314d81123fdc release-20261107/source/workspace_joint/mira/tests/data/test_training_loader.py +38ae5a78587f10d86904ad0889369ca1fdb6041460670ce23b4689675fdefe47 release-20261107/source/workspace_joint/mira/tests/data/test_training_loader_shuffle.py +7698575774b397fa1258062f82cb9fbd00eb60591176b52bbe24ab7b13083f57 release-20261107/source/workspace_joint/mira/tests/data/test_viz.py +ee03a279a8cfcd5bb0b9aa1c2b20c20c485038ff02a3167d9a1b3625e5948162 release-20261107/source/workspace_joint/mira/tests/inference/conftest.py +69fe94744b568a9b97b35e2517f01a34103d0c45d3c5bf06af1b6c1bd1942afc release-20261107/source/workspace_joint/mira/tests/inference/test_eval_world_model_offline.py +8d79e054b77c158438d92bce0bd7150ac71afe0e036f71c4d02f28a55c1650df release-20261107/source/workspace_joint/mira/tests/inference/test_rollout.py +dd749a2e737179e2c19d0c14ebf35ad03431f835f2c713705cdf64c201395bde release-20261107/source/workspace_joint/mira/tests/joint/test_action_gradient.py +c577b09a27650bc258cb622260592b698db0644a70dcfe71e7509a0db42f7874 release-20261107/source/workspace_joint/mira/tests/joint/test_anchor_contract.py +18def7e51f450c838df9aecc70a52460a1bdd471219edc9a29d39a20701a8c17 release-20261107/source/workspace_joint/mira/tests/joint/test_eval_language.py +fbf66b0a00e96262025b9cda69c09217a11dcf30d32a615ec5b3ff019ab161da release-20261107/source/workspace_joint/mira/tests/joint/test_eval_resume_protocol.py +17e62326d395b5302f9968e44829aa97ffa953f3bc52e8f55760015d96567bd6 release-20261107/source/workspace_joint/mira/tests/joint/test_eval_runner_accounting.py +39193fefba07fe00173e3290d47ee8249e072516df1fbf7c1af73e6e0d795478 release-20261107/source/workspace_joint/mira/tests/joint/test_flow_tail.py +9f1507b799805d13280e23394d8dcb6b8132b837e46c4a753eb16d75197c2b8d release-20261107/source/workspace_joint/mira/tests/joint/test_formal_eval_contract.py +79d0c0aefe7c614eb2f510f5e21b7cc93b7d7933419146c590e2a97da3fa7dcc release-20261107/source/workspace_joint/mira/tests/joint/test_official_adapter_contract.py +4e66bb9e2cc7fd9c90ac1a1228e3fe412c9bc5005cf11a59e62047050f7e7f98 release-20261107/source/workspace_joint/mira/tests/joint/test_pipeline_color_runtime.py +337940cc0ab0e4cb77265d6354df5a4f71a315eebd8fc6ed84b5b0244c124aa7 release-20261107/source/workspace_joint/mira/tests/joint/test_pipeline_minieval.py +3115a94e555fbe57e90522210ec07283d11d04e94e7d06e08670715e6afea396 release-20261107/source/workspace_joint/mira/tests/joint/test_pipeline_training_options.py +b63aa959764e0a60f7ccacf05684ae80dbfb74b93f57f12d932299d5e4cab5d8 release-20261107/source/workspace_joint/mira/tests/joint/test_rgb_contract.py +55f50a3aed7545e47be92f5f5864ab2aaca4f393aebeaa7d433aaaa0e3b0890b release-20261107/source/workspace_joint/mira/tests/ml/test_config_loading.py +1d52f7107ebd05b62f0a0c9196e5e245766dcd51a483d26fed38aecf270d0500 release-20261107/source/workspace_joint/mira/tests/ml/test_ml_smoke.py +e82c61a0c7b39801fcb20570ebcec3399d5234840654bf500cbfe7ce5866c21d release-20261107/source/workspace_joint/mira/tests/test_bihub_1b_config.py +f44603ae58347d35cb85a20042b2ef6d47ce6db3d83fe3e43651b7a8fadc3f25 release-20261107/source/workspace_joint/mira/tests/test_bihub_attention_graph.py +c97caacd89058ef3a3c3b21af1836c56ef88f63c9dc51d8c4e430f518136511a release-20261107/source/workspace_joint/mira/tests/test_bihub_batch_roles.py +2166400019e3172b6097cb35dca125abb4fba71dc92b33a7f4d56ffd5227edd4 release-20261107/source/workspace_joint/mira/tests/test_bihub_offline_metrics.py +a9c7724eada4d8b3c14bc2811c30368d65e61a860b34ea8a98425f9f0631f4f4 release-20261107/source/workspace_joint/mira/tests/test_checkpoint_resume_stages.py +2b63ed9c5f630900bc2b6b49872edd21de3cdb07d43de1ae96e271f2110f6f57 release-20261107/source/workspace_joint/mira/tests/test_latent_cache_equivalence.py +26ebb46330976dce9a31b1e96f0a21b80ad8eced6a5edb3eeb0e8e50ee5a1974 release-20261107/source/workspace_joint/mira/tests/test_no_future_leakage.py +a1731b661f65675e7833156a7a9c4bb1a2008a8ec26a93abe5965cce3663b9a0 release-20261107/source/workspace_joint/mira/tests/test_robotwin_instruction_prompt.py +239fe64cc8be24fa08746b2aca6001b3a60ec99604aebcb5aa52cfdd6662f659 release-20261107/source/workspace_joint/mira/tests/test_robotwin_time_alignment.py +3226fa48d5674d37f6f8bb433124c4d9cdc5b3f91034cbccd5f77a352de08972 release-20261107/source/workspace_joint/mira/tests/test_state_text_conditioning.py +bc60f92c2c327aef9a7abf1b2051bea4f2e75901eeee27e8909fbb89ebb560fc release-20261107/source/workspace_joint/mira/tests/training/test_checkpoint_manager.py +aaa1fe4be0b122475dc63f27fdbd8feb6728f3307b667e75b8d36df9528c319a release-20261107/source/workspace_joint/mira/tests/training/test_distributed.py +915ef5c1cd1a76b4b29832e49eec39060135e4fce89c01b3afae349eacf21bf4 release-20261107/source/workspace_joint/mira/tests/training/test_ema.py +d1a17857f01740f0a8f01c5858ac84866c1f5d4bd508b98b07e3455d0486df09 release-20261107/source/workspace_joint/mira/tests/training/test_lr_schedule.py +98425babfd3e942680de5cff391b45a732f457613135124004326accb080c45a release-20261107/source/workspace_joint/mira/tests/training/test_metrics.py +9f88a2df0700a4533884a03d190a45c31a784a00c29de7e5b046140dda0e491b release-20261107/source/workspace_joint/mira/tests/training/test_swanlab_tracker.py +cf4d4d7b5f8904f69869c7f46facdda647046b8ccb8bc8214a22504db30802b7 release-20261107/source/workspace_joint/mira/tests/training/test_visualization.py +104dac30759e1746c85a0fbcf39d344499e6b22657811ba3cb833adede869337 release-20261107/source/workspace_joint/mira/tests/training/test_world_model_metrics.py +4355b434241a974cbe5a92a42e185b5702d3f6e1878dceeeddee7f585c2dd2ef release-20261107/source/workspace_joint/mira/tests/world_model/conftest.py +42b38bea16ad8153c215b91a61251b34aad52a79afa5e06499d00a6a6047e633 release-20261107/source/workspace_joint/mira/tests/world_model/test_action_encoder.py +c4325a99bd33cb63cde263cba4991115e7e546973fdc835461115333810a2f10 release-20261107/source/workspace_joint/mira/tests/world_model/test_actions_config.py +965578ca2b1babd7f9a5850ef4fa8803b01734f2f7308b6ce6ccf96a855d0a28 release-20261107/source/workspace_joint/mira/tests/world_model/test_inference_context.py +fe9c612e1330b7b726dcf970a39431092073f82080789add3383750a6e0c7560 release-20261107/source/workspace_joint/mira/tests/world_model/test_latent_world_model.py +76b1218de0c39c43b202b98f01a5825dbeab56997d9273e1a4c59aa7b937a931 release-20261107/source/workspace_joint/mira/tests/world_model/test_multi_wrapper_world_model.py +e8b62295adfeaacbc94d73a2c04c04315238bca7ab0ea0dd6d97da53e9e264f5 release-20261107/source/workspace_joint/mira/tests/world_model/test_psd.py +70a2a5aa6ad9ac0efd29db98d211be845079ab48c118e672b87f56c9a9e660a8 release-20261107/source/workspace_joint/mira/tests/world_model/test_rope.py +b41a539564c0835785a1d0439f94966b03cc8455fc4028e601962b20b23ceb0f release-20261107/source/workspace_joint/mira/tests/world_model/test_train_step.py +7f8c62f97c1e9484e35a41b163a1c43ac3d6e1770c46d11212bd3b2afdb7aeb2 release-20261107/source/workspace_joint/mira/tests/world_model/test_train_world_model_hydra.py +65a31e3d0ac2eba8638b21a4aa9a3d11a0a4dff9f2491bf1a14881346bc9f0ff release-20261107/source/workspace_joint/mira/tests/world_model/test_visualize.py +707043badb1a6e04d140aad265195c1707e273881d36d188a8d51cb79f8f37fe release-20261107/source/workspace_joint/mira/tests/world_model/test_world_model_metrics.py +ad5a4fece0ec18df78cf6e3bc3a4d701539e17bd0c7ae53f4808fe496beee12a release-20261107/source/workspace_joint/mira/tests/world_v6/conftest.py +d698fde36146a6a69e08eda33636b1ab80d6d8599298c97ba8048e4d99bb1c19 release-20261107/source/workspace_joint/mira/tests/world_v6/test_balanced_sampler.py +5d6434330f66e9485a428eb4926eba62005fbcbdb1d478b70e5800c263b157ee release-20261107/source/workspace_joint/mira/tests/world_v6/test_codec_data_contracts.py +55aff566158ec6cb648f4cc9ce92f97d0db620fd595649a329649aaa61fc768d release-20261107/source/workspace_joint/mira/tests/world_v6/test_distributed_recovery.py +0aed1f1f4857bf5eff827c3854276c4bc500cb5684e23d782cb290b596d2e0c7 release-20261107/source/workspace_joint/mira/tests/world_v6/test_hhr_topology.py +9eab290a9390900b5aa0c60dca8369ce24dcc0188f5b8dc925a4916a97b44e3d release-20261107/source/workspace_joint/mira/tests/world_v6/test_interventions.py +44b570212f7fa74d9431b3890305797e12ed84ab0386be47e9b4bd438ebdb758 release-20261107/source/workspace_joint/mira/tests/world_v6/test_qwen_resampler_cache_contracts.py +025a191ddfbd9843114cae05ec34a728ff8f89283ba616d48d9733a1b50ba242 release-20261107/source/workspace_joint/mira/tests/world_v6/test_rgb_preprocess.py +ac2f5f48f8fde32bc2aa3215a78188bd0095e99006d9394e43eeb3aed94c957b release-20261107/source/workspace_joint/mira/tests/world_v6/test_world_flow_contracts.py +67bb49a835b4e772f5afe0cc8cbcf35ef1d3a64e394dff138c4bbe668b27ec82 release-20261107/source/workspace_joint/mira/tests/world_v7/test_short_history_masks.py +3a026dc1a4d41137387420d69f6acb69103f31446f4a6d80aa6560393193ca95 release-20261107/source/workspace_joint/mira/tests/world_v8/test_eval_aligned_v12.py +0f99310576514966a1b16bbc379ab54aae929a66d5b269c34f6377a28fa153fd release-20261107/source/workspace_joint/mira/tests/world_v8/test_h1_50_priority.py +5c38393099ca10292421aa135522d9309ec866522da9da5eb498ad14b3a19e7d release-20261107/source/workspace_joint/mira/tests/world_v8/test_h1_priority.py +8383956d808b5edd8b56bd0c8996f415c74f4a2761b114823fa49863effed68f release-20261107/source/workspace_joint/patches/xpolicylab-bihub-state-source.patch +122d7188b259abd3e89854632fe6a6a8701710c4a99c59f013657f615c9307f2 release-20261107/source/workspace_joint/scripts/apply_eval_patches.sh +cff7db20dde23d7ad77ee8e12a27301563f2dc4b2c46ff51d48b01bfcf2d99be release-20261107/source/workspace_joint/scripts/audit_before_full_eval_20261030.py +3dfbeed2616b62c5558134b2d44af1bdb8c7d9884d46e6937e44f97a3215b103 release-20261107/source/workspace_joint/scripts/audit_joint_rgb_pipeline.py +50ba2a4f2bfb2b0c56f957895d4d44933e42a1ccb86eab179e013d11f8394968 release-20261107/source/workspace_joint/scripts/audit_joint_train_eval_20261030.py +73fe977a638e87ea2fbb1916d7bf9ec71032bcd86336e9b3a27b432ed77cdbc7 release-20261107/source/workspace_joint/scripts/auto_train_joint_after_eval.sh +fefcbdef67ce84385775e54f6b121ecaace3800118daed2815301ef0b321c708 release-20261107/source/workspace_joint/scripts/backfill_joint_swanlab.py +00dfdf1a11b084d3f619e468f5c2f93f57fb18d43d0c4cfa3e3b2b76bf92e7ac release-20261107/source/workspace_joint/scripts/compare_minieval.py +4864b8b0696f547d42241731908e47969ea14a74ad8c6c90b73d970e90fe7762 release-20261107/source/workspace_joint/scripts/continue_joint_eval_language_8gpu.sh +91d4c9d2fbc3d18e6b07012d5513c4b34e420cb8bb0fc2ea14a56211ebe97ef7 release-20261107/source/workspace_joint/scripts/graceful_stop_joint_after.sh +fc193ca07caef640bf230d14c122b40a3f6fc7dbecb713888c92ed95974c1bd9 release-20261107/source/workspace_joint/scripts/hold_eval_gpu.py +5e8ec98a6a9607dfce88cf5db64a83e42e1a31005ff345313094e9b5e68aff57 release-20261107/source/workspace_joint/scripts/launch_joint12531_paper100_eval.sh +ced7d45f1436ab6905001fcac4dcb455853c827d0d2ea18e5c383c3062dda665 release-20261107/source/workspace_joint/scripts/launch_joint2449_two_sim_eval.sh +0a201be3994e8e70d7c975be0f2e793fb6a23c7bb860fe8d20aa4f11b88b7123 release-20261107/source/workspace_joint/scripts/launch_joint4fresh_full100_4gpu.sh +f7864191fe116c2ed9d6ceb3dab8be0fc4c8dfe259b098253de8683d25c29ae1 release-20261107/source/workspace_joint/scripts/launch_joint_anchor_v2_24gpu_cluster.sh +cb24d7728ed4895c9158618e1e49630f00734844b6b47fc606f4d8367ba91c18 release-20261107/source/workspace_joint/scripts/launch_joint_robotwin_formal_24gpu.sh +cbfbae14e9b80bcb8cbb7aaad33a0bb28fb1bbf172f2f2a259b4f3300d5370e2 release-20261107/source/workspace_joint/scripts/launch_robotwin_closed_loop_8gpu.sh +b08733df3e399bb05f47ea5fee46f08be30c263da4c70cc375803619009efc5a release-20261107/source/workspace_joint/scripts/migrate_joint_batch_checkpoint.py +693e5a1f94ca7edcb4ee1548928cc74927c81b41ac9c03ca8abf436b7edd3c28 release-20261107/source/workspace_joint/scripts/pipeline/select_checkpoints.py +72af81cdaf05aa8db5b3326b69b7143bddd7c1fae503d7b51839b09c71a4a754 release-20261107/source/workspace_joint/scripts/pipeline/train_phase.sh +b333c97f56ef50596c0ab427ad3942a6e67357195c279cd73b4aa54adedb1954 release-20261107/source/workspace_joint/scripts/preflight_robotwin_closed_loop.sh +6a9008f2184ac035cfaea6da307063d3f2c09c4e38c46d727384fa7f4d0f927c release-20261107/source/workspace_joint/scripts/probe_joint_eval_language_1gpu.sh +d58690f6fde09ef8470e0d88c334122c53c73b2e73630fe09a355c555082695f release-20261107/source/workspace_joint/scripts/queue_prompt_validation_extensions.sh +97d1405b91ec2d30978f773a59b20c6a6df07e9439d5d71d325726ba5f6f32ed release-20261107/source/workspace_joint/scripts/repair_robotwin_eval_env.sh +56b598e226eb2f9d5d8b5ab5737bcaa892046a1e507e9b71952b38f8caffec86 release-20261107/source/workspace_joint/scripts/report_color_ab.py +8f6b93dfe382c7444af44e7681a110acc2205b615214a86aa8498b4e0ff35ec7 release-20261107/source/workspace_joint/scripts/report_joint4fresh_full100.py +2397e8680833e57591c0454c53d6d1f3174ce652af3ec3c74f65582816329042 release-20261107/source/workspace_joint/scripts/rolling_restart_runners_node08.py +68616110e5125144faea5a79fba3be0fcc55448a8df18716954e3eaa17b890fb release-20261107/source/workspace_joint/scripts/run_color_ab.py +48895f4bc2153d0aea3701dead7077aa54ade9336dfa36df283405905cede7aa release-20261107/source/workspace_joint/scripts/run_joint_eval_local.sh +21b079a4d3e50b78f4cd795fd58dbc8cde97fe8f3bb65e62d1d67f66ef4536e0 release-20261107/source/workspace_joint/scripts/run_joint_lowacc_confirmation.sh +6fd76a9a218cd6fe8d4defa46a6e94d9cdf41c1e79d8bf6296da64d82a15428b release-20261107/source/workspace_joint/scripts/run_joint_prompt_ablation.sh +c7c896f6cb60fdb5fed349d61ad5fc4d9505f2b9286eefdd2a191f2da43ae1e3 release-20261107/source/workspace_joint/scripts/run_joint_prompt_ablation_resumable.sh +f130aa7be02b50797febf42a124bae096c97baa83be1a78466d9636116edec56 release-20261107/source/workspace_joint/scripts/run_joint_prompt_validation_case.sh +5111c9a05b5468dff72ed97292e6823220620481a533f1a9fc66c95d1a6168e5 release-20261107/source/workspace_joint/scripts/run_lowacc_eval_shard_09.sh +5a911fe8e798c7384e04e5c2d140e4ccfc79ac914ad9d0556280fe2f0749fa9b release-20261107/source/workspace_joint/scripts/run_lowacc_eval_step5500_shard.sh +23254e4a97726b2337bb5e678133fc22fda183c32e4de16f06a8f2bec95fc2b9 release-20261107/source/workspace_joint/scripts/run_minieval.py +8d6089657104ffbcf203283ff0cffd8b082180f4d67d9b411a532394c0ac0aab release-20261107/source/workspace_joint/scripts/schedule_joint4fresh_full100_4gpu.py +d4240d1bc97248e483080985ac86869edac7cb2c5f6812d5ea1843f3d12dc4b8 release-20261107/source/workspace_joint/scripts/schedule_joint4fresh_full100_node08_8gpu.py +1ad0d833be0ec41436d4febf2d0bfcfda4f1ce41543d5631d10a0930eba4b853 release-20261107/source/workspace_joint/scripts/score_official_eval.py +e806961f00400059f4698ec8d037db6bac38138a02e65df5465b27ccce6fc08c release-20261107/source/workspace_joint/scripts/serve_policy.sh +c024c104ab1a6eb432b5ae88c743356d68187c3f41fca0aa866c0d290b5de644 release-20261107/source/workspace_joint/scripts/setup_robotwin_eval_b20z.sh +49676d486ff89c527d22c99e97abf31dea2cdd3a08b27447543fe4f55d888c24 release-20261107/source/workspace_joint/scripts/setup_robotwin_graphics_env.sh +f99f6bd6556c83fe481860964b977ca41b05e57d49fda295ad9f2e5951ad3d77 release-20261107/source/workspace_joint/scripts/start_joint_eval_language_8gpu_on_idle_node.sh +dae2764866d98e012e6aeb2f7da200103a14f962ad0542c3ad9d77b771299d7a release-20261107/source/workspace_joint/scripts/summarize_joint_lowacc_confirmation.py +cfe2dd42cfd54076846ec0ee934164b1e197f2c60a8b51f86aa37665ed01f727 release-20261107/source/workspace_joint/scripts/train_joint_anchor_v2_24gpu_node.sh +f181ea85a682240004508a0c2fdec97a7cad9240dd47a2e23e129ea8d65a2fa9 release-20261107/source/workspace_joint/scripts/train_joint_anchor_v2_4gpu.sh +c057e084f2b94b077f529ae5a1642f49d69d1bf3dcf3d4199ce3ce2f309473a2 release-20261107/source/workspace_joint/scripts/train_joint_eval_language_v3_4gpu.sh +1070b4b2ba78bad42d0545189c1abe0a3990ecaae88c4ec927e10560eefb2d62 release-20261107/source/workspace_joint/scripts/validate_joint.sh +7474cda965629cb490044f4e980a7860cc9db43c48fbe3fd6906e0ab0ae92feb release-20261107/source/workspace_joint/scripts/wait_for_joint_eval_language_8gpu.py +8ed417a1e5d31af89484ffdd6a10c8b23162b09de999528b5fe26996057ed05a release-20261107/source/workspace_joint/scripts/wait_for_prompt_validation_gpu.sh +ec7a98e924b9c32eee7f0741567425c5447f001a39e5fcb3fb40ad7bb0325abd release-20261107/source/workspace_joint/scripts/wait_launch_joint24_14h.sh +09ab5296805537dd0227d35cd6bb0caea80d76d106d961d32cfa0bfa7098a653 release-20261107/source/workspace_joint/scripts/wait_lowacc_eval_shard_09.sh diff --git a/release-20261107/source/workspace_joint/docs/EVAL_PROTOCOL.md b/release-20261107/source/workspace_joint/docs/EVAL_PROTOCOL.md new file mode 100644 index 0000000000000000000000000000000000000000..ad1d38310b424e96e6028c5ef245df4cdfe4a438 --- /dev/null +++ b/release-20261107/source/workspace_joint/docs/EVAL_PROTOCOL.md @@ -0,0 +1,120 @@ +# Closed-loop RoboTwin 2.0 evaluation protocol + +This document states exactly how the Multi-WAM joint World+Action policy is +evaluated, where the pipeline follows the upstream RoboTwin 2.0 evaluator and +where it deliberately differs, how a score is computed, and which files let a +reader audit every episode. It is written so that a third party can reproduce +or challenge any number we report. + +## 1. Benchmark definition (unchanged from upstream) + +| Item | Setting | +| --- | --- | +| Simulator and tasks | Pinned RoboTwin 2.0 checkout `transfer/robotwin-official-20260921`; all 50 official tasks under `envs/` | +| Embodiment and cameras | ALOHA-AgileX (`arx_x5` config), D435 head + wrist cameras, official camera parameters | +| Domains | `demo_clean` and `demo_randomized`, each with the official task config | +| Instructions | `demo_clean` uses the official `seen` instruction set, `demo_randomized` uses `unseen`; both are produced by the official `generate_episode_descriptions` from the scene's `episode_info` | +| Episodes | 100 scored episodes per task and domain, environment seeds scanned upward from `seed_start = 100000` (the upstream value for `--seed 0`) | +| Expert feasibility filter | `expert_check=true`: a seed is scored only if the official expert demonstration succeeds on it; seeds where the expert fails or raises are skipped, as in upstream | +| Success and step limits | Official per-task success predicates and `env_cfg/task_config/_eval_step_limit.yml` | +| Control | `action_type=joint`, absolute joint targets executed by the official controller (TOPP), no controller changes | +| Result file | The official evaluator writes `_result.txt` with `successes / 100` and one `episode{i}.mp4` per scored rollout | + +## 2. Policy interface + +The policy runs as an XPolicyLab websocket server (`XPolicyLab/policy/BiHubJoint`) +and is called through the official `update_obs` / `get_action` protocol. Inside the +policy: three RGB views (left wrist, head, right wrist), a 20-step history of +issued joint targets, one frozen Qwen3-VL-2B query per view with a per-arm +`Role:` suffix appended inside the policy, a 10-step World rollout, a 10-step +Action sampling, and execution of the first 8 of 20 predicted joint targets +before replanning. Sampling noise is seeded from (task, domain, seed, replan +index, checkpoint fingerprint), so a rollout is reproducible. Normalized +actions are clipped to ±5σ and then to the physical joint range; the clip counts +are logged per replan. The policy never receives anything but the official +instruction string, observation and robot state. + +Checkpoint-specific colour handling: checkpoints trained before 2026-10-30 were +trained on legacy JPEG decoding that produced BGR-valued inputs. For those +checkpoints the adapter swaps channels once on the policy side +(`input_color_order=bgr`), applied identically to the codec and Qwen inputs. The +mode is recorded in every shard manifest; results obtained under different +colour modes are never pooled. + +## 3. Deviations from the upstream evaluator and why + +Every deviation below is in infrastructure, logging or recovery. None changes the +scene, the instruction pool, the controller, the success predicate or the policy +input. + +| Deviation | Upstream behaviour | This pipeline | Why / fairness argument | +| --- | --- | --- | --- | +| Instruction selection (`ROBOTWIN_STRICT_EVAL=1`) | `generate_episode_descriptions(..., test_num)` then `np.random.choice` with process-global RNG | Same generator with a per-(task, domain, seed) seeded RNG, 100 candidates, deterministic index; global RNG restored afterwards | Same candidate pool and uniform choice; makes the instruction independent of retries, sharding and `test_num`. Protocol id `strict_seeded_candidates100_v1` | +| Missing instruction | Falls back to the task name | Aborts the attempt | A policy must not be scored on a degenerate instruction | +| Expert-check exceptions | Skipped without limit | Skipped and recorded; the case aborts as *infrastructure failure* after 50 consecutive exceptions | Identical scoring; the bound only detects a wedged simulator (an earlier bound of 3 made feasible cases uncompletable and was removed on 2026-11-03) | +| Rollout / setup exception after the expert check | Crashes the evaluator | Attempt is aborted and retried from the same seed; after 3 attempts the seed is **scored as a failure** (`outcome=abandoned`) | Never skips a seed that passed the official filter; infrastructure trouble can only lower the score. Abandoned seeds are listed in the score report | +| Simulator stall | n/a | A simulator with no log output for 30 minutes is killed and the case resumes from its progress record | Same attempt accounting as above | +| Resume | n/a | `progress.json` next to the official result directory records every scored, skipped and abandoned seed and is the only authority for resuming | Makes partial runs auditable; counters are cross-checked against `_result.txt` | +| Renderer denoiser | OIDN default | OptiX (`ROBOTWIN_RAY_DENOISER=optix`) | OIDN produced `invalid handle` errors on the B20Z driver; affects rendering only | +| Websocket keepalive | 20 s ping | Disabled on the localhost link | Avoided spurious disconnects during long policy calls | +| Co-location | Separate processes | One policy server and one simulator share a reserved GPU; several such pairs may share a node | Throughput only; per-replan latency is logged | +| Process names | n/a | Evaluator processes are renamed `pi0.5_eval` for cluster scheduling | Cosmetic; manifests retain the true identity | + +Known comparability limits that are not pipeline deviations: the policy was +trained on both clean and randomized RoboTwin data, so results are not the +official clean-only C2C/C2R protocol; and `demo_randomized/unseen` is the +upstream generalisation setting. + +## 4. Scoring rules + +1. A task/domain case is scored only when the official `_result.txt` exists, the + progress record shows exactly 100 scored episodes with the same success count, + and every non-abandoned episode has its rollout video. +2. The per-case success rate is `successes / 100`, where abandoned episodes count + as failures. Expert-skipped seeds are not episodes (upstream rule). +3. The domain score is the mean of the 50 per-task success rates; a pooled + Wilson 95% interval over the 5,000 episodes is reported alongside. +4. A run is reported as a benchmark score only when all 100 cases are scored. + Partial runs are labelled incomplete and their numbers are progress counts. +5. Results from different checkpoints, colour modes, instruction protocols or + renderer settings are separate runs with separate run IDs and are never + pooled. +6. `scripts/score_official_eval.py --run-id ` produces the score tables and + the list of abandoned seeds; nothing is computed by hand. + +## 5. Audit trail per run + +| File | Content | +| --- | --- | +| `artifacts/evaluation//shard-*/manifest.json` | Checkpoint fingerprint, colour mode, instruction protocol, SHA-256 of the evaluator, adapter, renderer and runner sources, and one entry per session with GPU, host and transport settings | +| `.../shard-*/cases/_/status.json` | Case state, official result path, success count, abandoned seeds, skipped-seed counts | +| `.../cases//client*.log`, `server.log` | Full simulator and policy console output, including every resume | +| `.../cases//diagnostics/episodes.jsonl` | Per-episode instruction, seed, success and per-replan policy diagnostics | +| `transfer/.../eval_result//BiHubJoint////` | Official `_result.txt`, `episode{i}.mp4`, `progress.json` | +| `artifacts/evaluation//score.md`, `score.json` | Generated score report | + +## 6. Change log + +- **2026-11-03, resume protocol v1.** Added `progress.json` as the authoritative + resume record, removed the 3-consecutive expert-exception bound in favour of a + 50-exception infrastructure guard, and introduced the bounded-attempt rule that + scores an uncompletable seed as a failure. Motivation: three cases of the + running step-6563 evaluation could not finish because resuming restarted at the + same seed (two with deterministic expert-planner exceptions on the next seeds, + one with a deterministic policy stall). No scored episode of any case completed + before this change was altered; those cases carry `audit=result_file_only` in + the score report. The evaluator source hashes before and after the change are + recorded in each shard's `manifest.json` session entries and in + `artifacts/backups/eval_resume_protocol_20261103/SHA256SUMS`. + +- **2026-11-07, pipeline v4 switches (default off).** The runner gained + `--codec-incremental`, `--action-clip-sigma`, `--state-source` and + `--stage-timing`. The first three change policy computation and are recorded in + each shard manifest's identity (older manifests default to off/`command`), so + runs with different settings cannot be resumed into each other or paired as the + same protocol. Formal full evaluations keep all of them off unless a report + states otherwise. Checkpoint and ablation selection uses the held-out mini-eval + suite `mira/configs/minieval/heldout_v1.json` (seeds from 300000), never the + formal test seeds. Checkpoints with the split image contract + (`robotwin-official-split-v1`) take RGB at the policy interface; the runtime + reverses channels for the codec branch only. See `docs/PIPELINE_V4.md`. diff --git a/release-20261107/source/workspace_joint/docs/JOINT_EVAL_LANGUAGE_V3.md b/release-20261107/source/workspace_joint/docs/JOINT_EVAL_LANGUAGE_V3.md new file mode 100644 index 0000000000000000000000000000000000000000..a6c4841a5059dd1f6e61af3ba2f4ec617ad14ee9 --- /dev/null +++ b/release-20261107/source/workspace_joint/docs/JOINT_EVAL_LANGUAGE_V3.md @@ -0,0 +1,122 @@ +# Joint training: RoboTwin eval-language continuation + +Status (2026-10-21 18:37 China time): code, two-source manifest, and launch +preflight verified. The `pi05_joint_wait` tmux session on node03 is running +`scripts/wait_for_joint_eval_language_8gpu.py` and polling for a fully idle +eight-GPU node. No formal training has started yet. The live watcher log is +`artifacts/training_watchers/pi0.5_joint_eval_language_wait.log`. + +## Reason for the change + +The original joint manifest used a fixed Fast-WAM-style sentence for each +episode. RoboTwin's formal `seen` evaluation uses per-scene natural-language +descriptions from `description/task_instruction/*.json` and +`scene_info.json`. The completed 20-seed factorial found, for +`pick_dual_bottles`, 0/20 with the original official instruction, 1/20 with +that instruction wrapped in the old video prefix, and 9/20 with the fixed +training task text either with or without the wrapper. This supports a content +distribution mismatch; it does not establish that retraining will fix it. + +## Data preparation + +`mira/scripts/build_joint_eval_language_manifest.py` reads only the original +train/val episode manifests and each episode's archived `scene_info.json`. +It runs RoboTwin's own `generate_episode_descriptions` on that scene with the +formal evaluation's candidate count of 100, retains deduplicated `seen` +descriptions, and stores these alongside the task's `full_description`. +The old training sentence is excluded from the new manifest and sampling. +It never reads formal-eval episodes, seeds, +rollouts, or `unseen` templates. The RGB, state, action, episode hashes, +train/val split, and source archive references are retained verbatim. + +The prepared manifest is +`datasets/RoboTwin2.0/mira_manifests/joint_eval_language_v3/`. Its +`summary.json` records source and output hashes, candidate counts, and the +task-instruction catalog hashes. The original `joint_anchor_v2` manifest +remains available. + +## Why retain both text sources + +`seen` is grounded to an episode's objects and arm assignment and matches the +formal evaluation's instruction generator. Some of its templates describe +only an early subgoal: for `handover_block`, one generated instruction is +"Lift the red block with your left arm." `full_goal` describes the complete +success condition for the task, including the handover and placement on the +blue pad, but is fixed across episodes. For `pick_dual_bottles`, its generic +"simultaneously pick up one bottle with each arm" omits bottle appearance +that the `seen` instructions often name. Using only `full_goal` would remove +training exposure to these evaluation-style, scene-specific phrasings; it +could still help full-task behavior and must be measured in a controlled run. + +The previous fixed training sentence is not a selectable source and is not +stored in the new manifest's instruction pool. The original source manifest +is retained solely to reproduce the preexisting checkpoint/data lineage. + +Full manifest audit on 2026-10-21: 26,950 train and 550 validation episodes, +covering 50 tasks in each split. All rows retain their original order and +non-language fields; the splits remain disjoint and normalization statistics +are byte-identical. Each episode has 30–100 unique `seen` variants. The +launch preflight resolved `joint-checkpoint-30181` as the source checkpoint. +The superseded three-source derived manifest was removed after this audit. +Fifteen targeted tests pass, and a real archive sample decodes with the new +instruction pool. + +## Training path + +`mira.data.joint_eval_language` chooses a text variant for each sampled +training draw using the saved sampler position and an episode hash. A resumed +run reproduces the same choice without worker-local random state. The +provisional mix is **80% raw RoboTwin seen text and 20% full task goal**. +The mix is a launch argument. Validation uses raw `seen` text. + +The existing three-view Qwen role suffixes remain in place: left and right +lanes append `Role: Left-Arm.` and `Role: Right-Arm.`; the global lane uses +the text unchanged. Instruction augmentation changes only the text before +that lane-specific suffix. + +The joint trainer now accepts an explicit source joint checkpoint in a new +output directory. `--resume-from-joint-checkpoint` loads joint model, +optimizer, scheduler, sampler, and RNG state. The blocking identity-hash +comparison was removed as requested; model architecture and tensor loading +still validate compatibility. A separate +`--init-from-joint-checkpoint` option loads model weights only, if a fresh +optimizer becomes preferable after the experiment. + +## Prepared launch + +`scripts/continue_joint_eval_language_8gpu.sh --check` audits the full +manifest and latest source checkpoint without starting GPU work. `--train` +requires an allocated set of eight GPUs and writes to a new output directory. +Its defaults preserve the original 55k learning-rate schedule and optimizer +state, and stop after another 2,000 steps. Batch size and instruction mix +remain adjustable. The default per-device batch of 15 previously reserved +approximately 155 GiB of PyTorch memory per 179 GiB card at step 30181, +leaving about 24 GiB; actual utilization must be checked after restart. + +`scripts/probe_joint_eval_language_1gpu.sh` completed one optimizer step on +node04 GPU5 with weight-only initialization, and a separate one-step probe +fully restored model, optimizer, scheduler, sampler, and RNG from step 30181. +The full-resume probe reached step 30182 with finite loss and peak PyTorch +reserved memory of 45.6 GiB at batch 1. These tests do not predict the +eight-GPU batch-15 peak. + +`scripts/wait_for_joint_eval_language_8gpu.py` polls all accessible cluster +nodes and requires eight physical GPUs with at most 1 GiB used and at most +5% utilization each. It reserves the node atomically through `cluster-gpu`. +The on-node `start_joint_eval_language_8gpu_on_idle_node.sh` repeats the +physical and process checks twice before launching. The waiter records its +state under `artifacts/training_watchers/` and verifies a completed optimizer +step before declaring the `pi0.5` training active. Nodes that cannot be +queried are never treated as free. + +## Checks after the eight-GPU launch + +- RoboTwin `seen` includes shortened instructions that omit a later step of + the benchmark success condition. The full-goal portion anchors the complete + behavior, but the best mix requires measured closed-loop comparison. +- The new instruction distribution may change Qwen memory use. Inspect + eight-GPU reserved memory and free device memory after the first optimizer + step; the one-GPU batch-1 probe does not establish the batch-15 peak. +- The 20-seed factorial separates wrapper and content effects, while the + 100-seed replications test stability and expose remaining physical failure + stages. A new training run must be compared on paired evaluation seeds. diff --git a/release-20261107/source/workspace_joint/docs/PIPELINE_V4.md b/release-20261107/source/workspace_joint/docs/PIPELINE_V4.md new file mode 100644 index 0000000000000000000000000000000000000000..adf076b9f723e151e786049e26f71a2902b8c46c --- /dev/null +++ b/release-20261107/source/workspace_joint/docs/PIPELINE_V4.md @@ -0,0 +1,150 @@ +# Post-6563 training and selection pipeline (v4) + +Goal: raise the RoboTwin 2.0 score of the joint World + Action model (step 6563: clean 74.22%, +randomized 69.96%) towards and past Fast-WAM (91.88 / 91.78) without touching the formal test +protocol. This document covers what the pipeline adds, the order to run it in, and how each piece +was verified. Nothing in it has been run on a GPU yet. + +## 1. Order of work + +| Phase | What | Command | GPU | +| --- | --- | --- | --- | +| 0 | Baseline mini-eval of step 6563 (legacy BGR) on held-out seeds | `run_minieval.py` | yes | +| 1a | Colour contract split: Qwen gets true RGB, codec keeps its BGR latent space; 3k steps from 6563 | `scripts/pipeline/train_phase.sh phase1a_color` | yes | +| 1b | Policy-side ablations on the Phase 1a winner (no training) | `run_minieval.py -- ` | yes | +| 2 | Main run from the selected Phase 1 checkpoint: 30k steps annealed to 0, EMA, truncated rollout gradient | `scripts/pipeline/train_phase.sh phase2_main` | yes | +| — | Rank checkpoints of any run by paired mini-eval | `scripts/pipeline/select_checkpoints.py` | yes | +| final | Formal full evaluation (seeds 100000+, 100 per case) of the one selected checkpoint, new run ID | existing full-eval launchers | yes | + +Every GPU step has a dry-run or `--check` mode that validates inputs and prints the exact commands. + +## 2. Colour contract (RGB/BGR fix) + +All historical checkpoints were trained on reversed-channel (BGR-valued) frames. The frozen codec's +latent space and the World model built on it depend on that order; Qwen3-VL was pretrained on RGB. + +`mira.joint.image_contract.SPLIT_IMAGE_CONTRACT` (trainer flag `--image-contract +codec-bgr-qwen-rgb`, now the default) fixes this without retraining the codec: + +* The policy interface is RGB: the official simulator frames pass through the adapter unchanged + (`resolve_deployment_color` returns `rgb` for these checkpoints). +* The codec branch reverses channels internally (trainer: before `codec.encode`; runtime: + `BiHubJointRuntime.encode_history`). Its latents are therefore identical to the historical + ones, so World/Action statistics and the latent space are unchanged. +* Qwen receives true RGB, so colour words in instructions match what it sees. +* Checkpoints record the contract; resuming optimizer state across contracts is refused + (`require_resume_contract`). Weight-only initialization (`--init-from-joint-checkpoint`) from + step 6563 is the intended path. Legacy checkpoints keep evaluating with BGR input exactly as before. + +Do not use `scripts/train_joint_eval_language_v3_4gpu.sh` for new runs: it predates the split and +was written for the all-RGB contract (it now inherits the split default; use the phase launcher). +Retraining the codec on RGB is not part of this plan: it would create a new latent space and +require retraining World. + +## 3. Held-out mini-eval and paired comparison + +* Suite: `mira/configs/minieval/heldout_v1.json` — 10 gap tasks (largest shortfall against + published Fast-WAM per-task results) + 6 control tasks, both domains, 30 episodes per case, + seeds from **300000**. The loader refuses suites starting below 200000, so selection can never + touch the formal test seeds (100000+). Formal-protocol settings (strict instructions, expert + check, official success criteria) are unchanged. +* `scripts/run_minieval.py --deploy DIR --run-id ID --gpus 0,1,...,7 [--workers-per-gpu 2] + [--resume] [-- extra runner args]` splits the 32 cases round-robin into shards, one + `run_joint_eval_local.sh` per shard and GPU. It does not hold or reserve GPUs. +* `scripts/compare_minieval.py --baseline RUN_A --candidate RUN_B --write` pairs episodes by seed + (the expert check is policy-independent, so both runs score the same seeds), counts abandoned + seeds as failures and reports per-case and pooled exact McNemar p-values. Runs with a different + evaluation protocol (seed range, episode count, instruction protocol) are refused; policy-side + switches may differ and are listed. + +## 4. Training options (all default to the historical behaviour) + +| Flag | Meaning | Phase 1a | Phase 2 | +| --- | --- | --- | --- | +| `--image-contract` | `codec-bgr-qwen-rgb` or `rgb` | split | split | +| `--min-lr-ratio` | cosine floor at `--steps` (historical 0.05) | 0 | 0 | +| `--ema-decay` | EMA of all trainable weights, saved in the checkpoint; export with `--weights ema` (policy in §6) | 0 (off) | 0.9999 | +| `--rollout-grad-steps` | backpropagate only through the last N of the 10 World rollout steps (values unchanged) | 0 (all) | 2 | +| `--task-weights` | JSON `{task: weight}` for the task draw; must list every task | — | optional | +| `--clean-probability` | probability of a clean episode for the drawn task (historical 0.5) | 0.5 | 0.5 | +| `--action-loss-mode` | `source`, `masked_action_flow_mse_only`, `masked_action_flow_mse_execute8_gripper_weighted` | source | env `ACTION_LOSS_MODE` | +| `--state-noise-std` | Gaussian noise on valid normalized state history (training only) | 0 | env `STATE_NOISE_STD` | + +Derive task weights from held-out mini-eval failure rates, never from formal test results. + +`scripts/pipeline/train_phase.sh PHASE --check` parses every argument with the trainer's own +parser, checks the inputs and prints the torchrun command; `--train` additionally requires +`CUDA_VISIBLE_DEVICES` to list exactly `NPROC_PER_NODE` GPUs. Environment overrides: +`MIRA_PYTHON`, `DATASET_ROOT`, `JOINT_MANIFEST_DIR`, `NPROC_PER_NODE`, `PER_DEVICE_BATCH`, +`GRADIENT_ACCUMULATION`, `INIT_CHECKPOINT`, `OUTPUT_DIR`, `STEPS`, `WARMUP_STEPS`, `EMA_DECAY`, +`ROLLOUT_GRAD_STEPS`, `TASK_WEIGHTS`, `ACTION_LOSS_MODE`, `STATE_NOISE_STD`, `LR_WORLD`, `LR_ACTION`, +`SWANLAB_MODE` (default offline). The global batch stays 120. + +## 5. Evaluation switches (off by default, recorded in the run manifest) + +| Runner flag | Effect | Status | +| --- | --- | --- | +| `--codec-incremental` | Encode only the frames that are new since the previous plan and reuse the other latents. The codec backbone is per frame and its temporal bottleneck pairs frames without overlap, so this is mathematically exact; bf16 kernels with a different batch size may differ in the last bits. Set `BIHUB_CODEC_INCREMENTAL_VERIFY=1` on the policy server to log the deviation per plan. | validate on GPU before use in a formal run | +| `--stage-timing` | Synchronized per-stage latency (codec, qwen, world, action) in plan diagnostics | diagnostic only | +| `--action-clip-sigma S` | Override the ±5σ normalized action clip | ablation | +| `--state-source observed` | Adapter state history from the observed joint state instead of the issued waypoint; every plan logs the largest issued-vs-observed gap. Requires the adapter patch below. | ablation | + +The adapter lives in the pinned evaluator tree, which the migration stores as +`.migration/transfer.tar.zst`. After every restore run `bash scripts/apply_eval_patches.sh` +(idempotent; refuses targets whose SHA-256 is neither the pinned base nor the patched file). + +## 6. Checkpoint selection + +`scripts/pipeline/select_checkpoints.py --train-output OUT --baseline-run MINI_6563 --gpus 0,...,7 +--every 2000 --weights ema` exports (CPU) every N-th and the last checkpoint, runs the suite and the +paired comparison, and keeps `OUT/minieval_selection.md` as a leaderboard. Reruns skip finished +steps; `--steps 10000` evaluates exactly the listed steps. Select on the mini-eval; the fixed-seed +validation loss does not predict closed-loop success. + +### EMA policy + +EMA never changes training: the optimizer updates the live weights, and the EMA is a separate +shadow copy updated after each step and never written back. Its cost for this model (1.87 B +trainable parameters) is one fp32 copy: about 7.5 GB in total, about 0.9 GB per GPU on 8 GPUs, and +about +36% checkpoint size (21 GB to roughly 28.5 GB). + +The earlier World-v6/v7 `ModelEMA(decay=0.9999, unbias=False)` started from the initial weights +with a fixed decay, so after T steps the initial weights kept a 0.9999^T share (37% at 10k steps, +8% at 25k); EMA checkpoints of short runs looked barely trained. The joint trainer warms the decay +up as `min(decay, (1+t)/(10+t))`: the initial weights' share is ~0 after a few dozen steps, and +the EMA averages roughly the last 10-25% of the steps taken so far (mean lag 0.1·t; 92% of the +weight from the last quarter), whether the run stops at 3k, 10k or 30k steps. + +* **Phase 1a: off.** Its only purpose is a single-variable comparison against step 6563 (colour + contract); EMA would add a second difference. With 3k steps annealed to zero the final EMA and + live weights would also be nearly identical. +* **Phase 2: on (0.9999), selection uses EMA weights**, because checkpoints taken every 2k steps at + high learning rate are noisy. Confirm this once, at step 10000, with a paired comparison of the + two weight sets on the same seeds: + + ```bash + python3 scripts/pipeline/select_checkpoints.py --train-output OUT --baseline-run MINI_6563 \ + --gpus 0,1,2,3,4,5,6,7 --steps 10000 --weights model + python3 scripts/compare_minieval.py --baseline minieval--s10000-model \ + --candidate minieval--s10000-ema --write + ``` + + Keep EMA unless the live weights are better with p < 0.05 (a tie favours EMA, which is less + sensitive to the exact step); otherwise switch the remaining selection to `--weights model`. + +## 7. Verification done (CPU only) + +* `mira/tests/joint`: all tests pass (49 existing + 18 new: `test_pipeline_color_runtime.py`, + `test_pipeline_training_options.py`, `test_pipeline_minieval.py`), run with + `CUDA_VISIBLE_DEVICES=` on the pinned evaluator tree, before and after applying the adapter patch. + They cover contract resolution, codec-branch channel routing, exact incremental reuse and cache + invalidation, the historical schedule and sampler stream, EMA save/export through DCP, + task-weight validation, truncated rollout values and gradients, suite/launcher sharding, McNemar + values, paired comparison, checkpoint planning, and the patched adapter. +* `train_phase.sh phase1a_color --check` and `phase2_main --check` against this workspace print the + 8-GPU torchrun commands; `run_minieval.py --dry-run` and `select_checkpoints.py --dry-run` produce + the expected plans. +* Not yet verified (needs GPU): a training step with the split contract, EMA and truncated rollout + under FSDP2; the incremental codec deviation in bf16; the observed state semantics in the simulator. + +Deployed files, their previous versions and SHA-256 sums: `artifacts/backups/pipeline_v4_20261107/`. diff --git a/release-20261107/source/workspace_joint/docs/TRAIN_EVAL_TEXT_MISMATCH_CASES_20261021.md b/release-20261107/source/workspace_joint/docs/TRAIN_EVAL_TEXT_MISMATCH_CASES_20261021.md new file mode 100644 index 0000000000000000000000000000000000000000..19e7cd951ed211c01297e8d7cfed3d84962d1432 --- /dev/null +++ b/release-20261107/source/workspace_joint/docs/TRAIN_EVAL_TEXT_MISMATCH_CASES_20261021.md @@ -0,0 +1,78 @@ +# 25k checkpoint:训练与评测指令的实际对照 + +以下字符串直接取自本次 joint 训练的 `joint_anchor_v2/train.jsonl` 和 25k +正式评测的 policy server `episodes.jsonl`。`eval seed` 指评测环境 seed, +`demo_clean` 每个已完成任务有 100 个评测回合。英文原文保留,方便核对。 + +## 共同的文本格式差异 + +训练 manifest 的指令由构建脚本生成,当前 `instruction_catalog` 为 `null`。 +默认格式是: + +```text +A video recorded from a robot's point of view executing the following instruction: {task} using the {arm} arm to manipulate {A} +``` + +其中 `{task}` 是任务名改写的短句,`{arm}` 和 `{A}` 来自场景信息;这个 +默认模板没有使用第二个物体 `{B}`。正式评测则从场景信息生成候选自然语言指令, +再按 seed 选择一条,**没有前面的 “A video recorded...” 包装**。 +因此下表的差异同时涉及包装、措辞、任务步骤和物体描述,单看两个文本不能断言 +哪一项导致失败。 + +### 三视角的 `Role` 后缀仍然生效 + +下表比较的是 manifest 与 policy server 日志中的**原始 instruction**。 +它还不是 Qwen 实际收到的三路文本。训练和推理都经过同一个 +`lane_text()`:左相机追加换行和 `Role: Left-Arm.`,全局相机保持原文, +右相机追加换行和 `Role: Right-Arm.`。例如 `handover_block`: + +```text +训练左路:A video recorded from a robot's point of view executing the following instruction: handover block using the appropriate arm to manipulate object + Role: Left-Arm. +评测左路:Grab red block, pass to the right arm, then drop on blue pad. + Role: Left-Arm. +``` + +这里缩进仅用于展示,实际拼接符是一个换行。右路对应 `Role: Right-Arm.`, +全局路没有 `Role` 后缀。因此先前指出的不匹配发生在**Role 后缀之前的 +任务指令本体**;Role 机制并未被忽略。见 +`../mira/src/mira/world_v6/prompts.py` 和 +`../mira/src/mira/world_v6/qwen_current_anchor.py`。 + +| 任务 | 训练 manifest 中的原文 | 25k 正式评测中实际发给模型的原文 | 可直接看到的差异 | +|---|---|---|---| +| `handover_block` | `A video recorded from a robot's point of view executing the following instruction: handover block using the appropriate arm to manipulate object` | seed `100000`: `Grab red block, pass to the right arm, then drop on blue pad.` | 训练用任务短句和泛称 `object`;评测明确红块、右手接力、蓝色目标垫和动作顺序。 | +| `handover_block` | 同上 | seed `100003`: `Hand the red block to the right arm.` | 这条评测句子只说交接,未提最终放到蓝垫;但 benchmark 成功条件仍要求物体到目标位置、满足高度阈值且右夹爪打开。这里还存在**评测句子与成功判据不完全一致**的问题。 | +| `pick_dual_bottles` | `A video recorded from a robot's point of view executing the following instruction: pick dual bottles using the appropriate arm to manipulate bottle` | seed `100000`: `Simultaneously grasp and lift the medium dark brown bottle and the handheld green bottle.` | 训练是单数泛称 `bottle`,没有第二瓶的外观;评测描述了两个具体物体和同时操作。 | +| `pick_dual_bottles` | 同上 | seed `100001`: `Use each arm to grab one of the brown bottle with red label and the bottle with ridges near base.` | 每个 seed 的物体描述会变;这句只说抓取,而成功判据还要求两瓶分别到达目标区域且高度大于 `0.89 m`。 | +| `pick_diverse_bottles` | `A video recorded from a robot's point of view executing the following instruction: pick diverse bottles using the appropriate arm to manipulate bottle` | seed `100007`: `Pick up both the smooth bottle with rounded edges and the bottle with white screw cap using separate arms.` | 训练的默认模板未写出第二瓶 `{B}`,评测用两瓶的属性和双臂操作来指代目标。 | +| `place_can_basket` | `A video recorded from a robot's point of view executing the following instruction: place can basket using the left arm to manipulate can`(另有 `right arm` 版本) | seed `100000`: `Lift the rounded red Coca-Cola soda container, put it in the yellow basket, and carry the yellow basket afterward.` | 训练默认句只说操作易拉罐;评测是“罐入篮,再提篮”的两段动作,并包含颜色和品牌属性。 | +| `open_laptop`(反例) | `A video recorded from a robot's point of view executing the following instruction: open laptop using the right arm to manipulate laptop`(另有 `left arm` 版本) | seed `100001`: `Raise the laptop with foldable screen design lid with the right arm.` | 同样存在包装和措辞差异,但此任务正式评测是 **86/100**。文本不匹配本身不足以解释所有低准确率任务。 | + +前四个任务的正式评测成绩分别为:`handover_block` **1/100**, +`pick_dual_bottles` **2/100**,`pick_diverse_bottles` **0/100**, +`place_can_basket` **11/100**。这些成绩是任务整体结果,不是表中单个 seed +的成功率。 + +## 已做过的同 seed 提示词小实验 + +在 `handover_block` 和 `pick_dual_bottles`,把评测指令替换成该任务训练 +manifest 中的固定原文,保持 checkpoint、评测环境和前 20 个通过专家检查的 +评测回合 seed 一致(它们不一定是连续整数): + +| 任务 | 正式评测原指令,前 20 回合 | 训练原文,配对的 20 回合 | +|---|---:|---:| +| `handover_block` | 0/20 | 2/20 | +| `pick_dual_bottles` | 0/20 | 9/20 | + +瓶子任务显示明显的提示词敏感性;交接任务的 2 次改善还不足以支持同样强的结论。 +这次替换**同时改变了包装、任务措辞和物体细节**,所以不能据此把原因单独 +归给某个词或包装。当前正在跑的 2×2 对照会分别改变包装与文本内容,并记录 +失败阶段;结果未完成前,不应把上述差异当作已经确认的唯一根因。 + +## 核对位置 + +- 训练所用 manifest 路径见 `../outputs/joint_8gpu_07_resume12975_20261011/resolved_config.json` 的 `manifest_dir` 和 `dataset.manifest`。 +- 训练文本原文见 `../datasets/RoboTwin2.0/mira_manifests/joint_anchor_v2/train.jsonl`;生成规则见 `../mira/scripts/build_robotwin_wam_manifest.py` 的 `_instruction()`。 +- 正式评测原文见 `../artifacts/evaluation/joint25000_full100_optix_20261018/shard-*/cases/demo_clean_/diagnostics/episodes.jsonl` 的 `env_seed`、`instruction` 和 `success` 字段;指令选择逻辑见 `../transfer/robotwin-official-20260921/scripts/eval_policy_xpolicylab.py` 的 `build_instruction()`。 +- 20-seed 替换实验结果见 `../artifacts/evaluation/joint25000_prompt_ablation_20261020/resume_state.json`;新 2×2 实验设计和进度见 `../artifacts/evaluation/joint25000_factorial_20261021/README.md`。 diff --git a/release-20261107/source/workspace_joint/docs/gpu_validation_20260920.md b/release-20261107/source/workspace_joint/docs/gpu_validation_20260920.md new file mode 100644 index 0000000000000000000000000000000000000000..c2888459b0d039c100127a91596045f63ea39fc2 --- /dev/null +++ b/release-20261107/source/workspace_joint/docs/gpu_validation_20260920.md @@ -0,0 +1,86 @@ +# 2026-09-20 GPU 只读验证结果 + +## 结论 + +按授权在物理 GPU 4、5、6、7 上与原有进程并行进行了验证,四类检查最终通过。 +**没有启动训练:没有 backward、没有 optimizer step、没有写入或替换 checkpoint。** +所有前向位于 `torch.inference_mode()`;模型 eval/frozen,结束时检查参数没有梯度。 + +| GPU | 验证内容 | Case 数 | 峰值 allocated / reserved (GiB) | 结果 | +|---|---|---:|---:|---| +| 4 | World25066 + Action23016 完整推理 | 8 | 16.27 / 17.04 | 通过 | +| 5 | World25066 + Action11508 完整推理 | 8 | 16.27 / 17.04 | 通过 | +| 6 | 初始化后的修复版 joint 前向、真实 mask 与 loss | 5 | 18.24 / 19.99 | 补跑通过 | +| 7 | codec 编解码、时序一致性、FP32对照 | 5 | 7.68 / 9.07 | 通过 | + +这是26个验证case,包含对照重复,不是26个独立episode,更不是完整任务评测。 +输入来自既有 val split 的 adjust_bottle / lift_pot、clean / randomized,覆盖 H1/H5/H9/H10 和尾段。 + +## 具体通过项 + +- 真实 DCP 权重加载、原始三视角 RGB→codec→Qwen→World 10步→Action 10步→20×14动作链路通过。 +- 两个 Action checkpoint 输出全部有限,首个case重复运行的动作最大差异均为0。 +- joint 前向使用预训练 World/Action 初始化,**不是新训练后的 joint 模型**。各case损失有限。 +- 终段 future_valid=0 时,World FM和latent loss均为0,Action loss仍有限(本case约0.04432)。 +- codec 重建与 World 预测已输出 MP4;视频可读取,分别为40帧/20帧,20fps。 +- 单个进程最高 PyTorch allocated 18.24 GiB,reserved 19.99 GiB。**不能据此估计训练显存**:没有反向激活、梯度和Adam状态。 + +## 显存与进程约束 + +启动时4~7卡各剩约50~56 GiB。每个worker的PyTorch allocator上限设为32 GiB; +supervisor每3秒采样GPU状态,若剩余低于8 GiB只终止自己创建的worker;启动前还要求留下至少16 GiB预算。 +首轮监控记录的最小剩余显存依次约36.62、34.73、30.41、44.04 GiB,无OOM,无低显存安全停机。 +allocator上限不包含全部CUDA库/驱动内存,因此同时记录卡级显存,不能将其视为系统级硬配额。 + +本次进程名为 `syncnet_eval_4` 等,不运行训练launcher,不操作其他任务的PID。 +所有模型离线加载;网络代理变量清空,HF/Transformers offline开启,无新增下载。 + +## 发现与处理:BF16 编码差异 + +初次验证以固定容差比较40帧完整编码前缀和20帧历史编码,部分元素超出容差,codec/joint检查因此中止。 +原始失败日志保留,没有把初次失败改写为成功。 + +进一步对照结果: + +1. 相同40帧形状,只反转未来20帧像素:被检查case的历史latent最大差异为0。 +2. 关闭TF32、以FP32计算40帧与20帧历史前缀:被检查case最大差异为0。 +3. BF16跨batch形状的latent RMSE约0.009~0.017,个别元素最大差异达到0.125。 + +这些结果支持差异来自低精度计算/不同batch形状,而非该case的未来信息泄漏。 +验证器改为分别记录BF16数值差异,并用同形状未来扰动和FP32对照检查因果契约; +没有简单提高原BF16阈值,没有改动模型权重,也没有据此断言这类数值差异对任务成功率绝对无影响。 + +## 外部中断 + +首轮结束后,GPU6的补充joint进程在通过两个case后收到SIGTERM,退出码143; +同一时刻观察到整机原有GPU进程也已退出。原因无法从本次日志确认,没有OOM证据;本次没有发出终止其他任务的命令。 +随后仅在GPU6重新执行5个只读joint case,通过并自动释放显存。 +因此完整joint结果的末次补跑是在其他GPU任务退出后完成,不能将所有最终case都称为共享卡压力测试。 + +## 日志与可视化 + +- 最终Action:`artifacts/reports/gpu_validation_20260920_run1/final23016/` +- 最佳Action:`artifacts/reports/gpu_validation_20260920_run1/best11508/` +- codec/FP32对照:`artifacts/reports/gpu_validation_20260920_codec_precision/` +- 完整joint补跑:`artifacts/reports/gpu_validation_20260920_joint_retry/` +- 首轮卡级监控:`artifacts/reports/gpu_validation_20260920_run1/gpu_memory.jsonl` +- 被SIGTERM中断的记录:`artifacts/reports/gpu_validation_20260920_joint_forward/` + +各成功目录有 summary.json、逐case metrics.jsonl。Action输出另存NPZ,带GT和有效位置mask。 +World预测视频在final23016/best11508目录的 world_prediction.mp4;codec视频为 codec_reconstruction.mp4。 +视频三列依次L/G/R,上排GT,下排预测/重建。 + +## 下一步边界与重跑 + +新只读入口(不会执行训练): + +```bash +bash scripts/validate_joint.sh gpu-inference +``` + +它只使用4~7卡,结果写入自动生成的独立报告目录。原 `smoke` 模式会更新参数,**本次没有执行,未经授权不要启动**。 + +本次不构成闭环成功率验证,不据8个离线case判断11508优于23016。 +两种checkpoint的原runtime动作噪声seed包含checkpoint fingerprint,因此也不是完全相同动作噪声的统计比较。 +XPolicyLab/仿真基础依赖仍需补齐;真实闭环、joint训练、FSDP2反向/恢复及已训练joint的成对导出还未验证。 +即使后续GPU空闲,也不自动启动训练。 diff --git a/release-20261107/source/workspace_joint/docs/joint_anchor_v2_24gpu_runbook.md b/release-20261107/source/workspace_joint/docs/joint_anchor_v2_24gpu_runbook.md new file mode 100644 index 0000000000000000000000000000000000000000..9bfb7c164339404f2700d4d1673d1e5297ad401f --- /dev/null +++ b/release-20261107/source/workspace_joint/docs/joint_anchor_v2_24gpu_runbook.md @@ -0,0 +1,26 @@ +# Joint Anchor-v2:24 GPU 正式训练 + +## 启动与监控 + +在 node12(本机、rank 1)的项目根目录执行: + +```bash +bash scripts/launch_joint_anchor_v2_24gpu_cluster.sh --check +bash scripts/launch_joint_anchor_v2_24gpu_cluster.sh --train +tail -f outputs/joint_anchor_v2_24gpu_main/node-0.log +tail -f outputs/joint_anchor_v2_24gpu_main/metrics.jsonl +``` + +启动器用已配置的 SSH 密钥连接 node17(rank 0/master)和 node16(rank 2);三节点共用代码、环境、数据和输出。每台机器使用 8 张 H200。训练会话名为 `joint_anchor_v2_24gpu_train`,运行在各节点的 `tmux -L hc` server 中。启动器会拒绝重复同名会话;不要在已有训练运行时再次启动。 + +SwanLab 仅由全局 rank 0 初始化,项目为 `Multi_WAM`,实验名为 `Joint-World-Action-24GPU-FullFinetune`。脚本清除代理变量并设 `NO_PROXY=*`,从 `z_oranger/token.txt` 读取 SwanLab 项,不上传 HF token。云端仅记录训练/验证标量、配置与必要的硬件信息;本地 `metrics.jsonl` 和 `validation.jsonl` 为上传失败时的权威备份。 + +## 本次配置 + +- 从 World-v12 step 25066 和 Action-v13 step 23016 初始化;不继承旧 joint step 500 的能力或优化器状态。 +- Qwen3-VL 与 LingBot codec 冻结;World 全量、current resampler、state encoder、Action 全量训练。 +- 每卡 microbatch 3,24 卡全局 batch 72,梯度累积 1;每节点 8 卡 FSDP2 分片,跨节点 3 路复制梯度同步。 +- World/Action 学习率分别为 `1e-5`、`3e-5`,warmup 500 steps;World/Action flow loss 权重均为 1。验证每 200 steps,保存每 100 steps,保留最近 3 份及 5000-step 里程碑。 +- `--steps 55000` 是长期上限;单次运行按 12 小时墙钟时间停止,在完整 optimizer step 后保存可恢复的模型、优化器、调度器、采样器与 RNG 状态。重新执行同一启动命令会从输出目录中的最新完整 checkpoint 自动续训,并重新计时 12 小时。 + +预检要求启动前每卡至少有 100000 MiB 空闲;此阈值用于避免与现有任务并跑时 OOM,不代表训练稳态空闲量。2026-09-29 的 24 卡 smoke test、定时保存和断点恢复均通过。正式运行初期每卡总占用约 123–125 GB,剩余约 18–20 GB;实际余量会随其他任务变化。 diff --git a/release-20261107/source/workspace_joint/docs/joint_training_to_eval_progress_20261010.md b/release-20261107/source/workspace_joint/docs/joint_training_to_eval_progress_20261010.md new file mode 100644 index 0000000000000000000000000000000000000000..037785979190aeed43be085d940fc8cb765e6ca5 --- /dev/null +++ b/release-20261107/source/workspace_joint/docs/joint_training_to_eval_progress_20261010.md @@ -0,0 +1,225 @@ +# Multi-WAM:近期联合训练至 RoboTwin 评测的实验纪要 + +整理日期:2026-10-10(UTC)。本文是供后续人工撰写报告和诊断使用的**事实底稿**,不是论文最终结果,也不预设性能问题的根因。重点覆盖 2026-09-20 的诊断/修复、09-23 的 4 卡训练、09-29 至 10-02 的 24 卡联合训练,以及 10-02 至 10-05 的 step-12531 闭环评测。更早的 codec、World-v12、Action-v13 独立训练只作为本次初始化来源,不在这里重建各自完整训练史。 + +## 1. 一页结论与状态 + +- 本次正式分析对象是 **Joint Anchor-v2 step 12531**。它从 World-v12 step 25066、Action-v13 step 23016 初始化,然后在 24 张 H200 上联合训练;不是从 09-23 的 4 卡 step-500 checkpoint 续训,也不是从零初始化 World/Action。 +- 训练时只冻结 Qwen3-VL-2B 与 LingBot codec;World、current resampler、state encoder 和 Action 分支共约 **1.866B 参数**进入优化器。训练目标为 `L_world_flow + L_action_flow`,latent/RGB 辅助损失权重均为 0。 +- 24 卡训练先在每卡 batch 3 下走到 step 2449,再保留模型、优化器、LR scheduler、sampler、RNG 状态,将每卡物理 batch 提高到 5 后续训至 **step 12531**。计划上限为 55000 steps;目前只走到这个 step 上限的约 **22.8%**。这次因需要评测而停在 12531,不能写成“训练完成 55000 steps”。 +- step-12531 的 50 task × 2 domain × 100 valid rollout 评测**进程已经结束,但协议未完整完成**:100 个 task-domain 配置中 96 个成功结算,4 个因仿真 expert initialization check 连续异常而失败。已结算部分为 Easy **2546/4900 = 51.96%**、Hard **1891/4700 = 40.23%**,合并 **4437/9600 = 46.22%**。这些是**缺失组之外的观察值**,不是完整 50-task 官方均值。 +- 本模型训练同时使用 clean 与 randomized 数据(各任务分别 49 和 490 条训练 episode),因此 `demo_clean` / `demo_randomized` 两个**测试条件**分别对应 Easy/Hard,但不能把该实验严格称为 clean-only 训练的 C2C/C2R,也不能直接与其榜单数值横比。 + +主要事实源:[诊断/修复报告](repair_report_20260920.md)、[24 卡 runbook](joint_anchor_v2_24gpu_runbook.md)、[训练配置](../outputs/joint_anchor_v2_24gpu_long_20260930/resolved_config.json)、[step-12531 状态](../outputs/joint_anchor_v2_24gpu_long_20260930/joint-checkpoint-12531/trainer_state.json)、[评测协议](../artifacts/evaluation/joint12531_paper100_20261002/README.md)、[评测汇总](../artifacts/evaluation/joint12531_paper100_20261002/summary.json)。 + +## 2. 时间线及各阶段之间的关系 + +| UTC 时间 | 事件 | 产物与解释 | +|---|---|---| +| 09-20 | 对此前低闭环成功率做代码/评测诊断并同步发布权重;落实可确认的数据采样、时间历史、mask、部署和日志修复 | [修复报告](repair_report_20260920.md)。这时尚不能声称成功率提高。 | +| 09-21 至 09-23 | GPU 前向、显存、配置探测;09-23 启动 4 卡联合训练 | [4 卡运行](../outputs/joint_anchor_v2_4gpu_main/)于 09-23 06:52 保存 step 500。这是独立试跑,**没有成为随后 24 卡模型的父 checkpoint**。 | +| 09-29 17:39 左右 | 3 节点 × 8 卡正式 24 卡 run 从发布 World/Action 初始化,per-device batch 3、accumulation 1 | [第一段](../outputs/joint_anchor_v2_24gpu_main/);09-30 04:09 保存 step 2449。 | +| 09-30 上午 | 对 step 2449 做 pilot/缩短版闭环诊断;同时做多节点 batch 5 探测 | 20-trial 运行并未覆盖全部配置,不能视作正式 50-task 结果。 | +| 09-30 14:03–14:12 | 将 step 2449 checkpoint 迁移到 batch 5 的输出目录,续训而非重新初始化 | [迁移记录](../outputs/joint_anchor_v2_24gpu_long_20260930/resume_migration.json)证明模型/优化器/LR/sampler/RNG 保留;global batch **72 → 120**。 | +| 10-02 14:12 | 24 卡联合训练停在 step **12531** 并保存可恢复状态 | [checkpoint](../outputs/joint_anchor_v2_24gpu_long_20260930/joint-checkpoint-12531/trainer_state.json)、[部署导出](../outputs/joint_anchor_v2_24gpu_long_20260930/deploy-12531/deployment.json)。 | +| 10-02 18:22 | 启动 step-12531 正式规模评测,50 task × Easy/Hard × 100 valid episodes | [manifest](../artifacts/evaluation/joint12531_paper100_20261002/manifest.json)固定 checkpoint 指纹、RoboTwin revision、seed 与拓扑。此前两个 1-trial pilot 不计入正式评测。 | +| 10-05 19:22 | 评测 supervisor 完成处理 100 个配置后退出 | 96 passed、4 failed;成功结算 9600 次,尚缺 400 次规范结果。[summary](../artifacts/evaluation/joint12531_paper100_20261002/summary.json)。 | +| 10-10 核查时 | 无该 run 的活跃 tmux/主评测进程 | 当前没有自动补跑;本文仅整理证据,**没有重启训练或评测**。 | + +09-23 的 4 卡 checkpoint 与 09-29 起的 24 卡 lineage 必须分开。24 卡 lineage 仅是 `发布 World-v12 + 发布 Action-v13 → step 2449 → batch 迁移 → step 12531`。 + +## 3. 为什么要改联合训练链路 + +09-20 审计的主要问题是训练/部署接口错位,而非已证实的“World 架构不行”。旧采样大量固定在短前缀;旧训练历史 H1/H3/H6/H10 与真实闭环重规划常见的 H1/H5/H9/H10 不同;冷启动重复首观测与训练首帧构造不一致;末端不足完整未来窗口的锚点被丢弃。另有旧联合训练代码的导入阻塞、2-step 训练 rollout 与 10-step 部署不一致、联合导出/验证不足等工程问题。详见[原审计](../artifacts/audits/training_audit_20260920/README.md)与[修复报告](repair_report_20260920.md)。 + +本次实际运行使用的修复包括: + +1. 在线按 **task → domain → episode → 当前 anchor** 采样;history 由该 anchor 的真实可用观测决定,冷启动重复初始观测,历史随 episode 进展增长。 +2. 末端分别使用 `action_valid[20]`、`future_valid[10]`、`future_rgb_valid[20]`,padding 不参与相应目标;短 episode 不因缺少完整 2 秒未来而整体废弃。 +3. 训练和部署均使用 10-step `linear_quadratic` World Euler rollout;Action loss 经可微的预测未来回传至 World,Action 使用 live World state encoder,而不是冻结副本。 +4. codec/Qwen 冻结;增加固定验证集、checkpoint 保存/自动恢复、联动导出与 BiHubJoint runtime。SwanLab 上传故障不使训练 step 失败,本地 JSONL 为权威备份。 + +这些修复是**本次实现/训练协议事实**;它们是否单独导致成功率变化,需要控制实验才能归因。旧 World/Action 预训练权重本身并不会被这些后加修复追溯改写。 + +## 4. 数据、采样与输入/动作语义 + +数据为 RoboTwin 2.0 `aloha-agilex` 的 50 个 task。联合训练 [manifest 汇总](../datasets/RoboTwin2.0/mira_manifests/joint_anchor_v2/summary.json)记录: + +| 项目 | 实际值 | +|---|---:| +| Train episode | 26,950;每任务 539 = clean 49 + randomized 490 | +| Validation episode | 550;每任务 11 = clean 1 + randomized 10 | +| Train/validation episode 交集 | 0(manifest 审计) | +| Train 可选 20Hz anchor 位置 | 3,960,801;**不是**实际独立见过的样本数 | +| 原始视频 / RGB 输入 / codec latent 频率 | 30 / 20 / 10 Hz | +| 视角顺序 | left / global / right,三视角共同输入,不是把三视角当三个独立 task | +| 状态语义 | 14 维左右臂 `simulator_drive_target_not_measured_qpos` | +| 动作标签语义 | 下一 20Hz 时刻的绝对 14 维 drive target | + +每个在线样本以一个当前 20Hz anchor 为中心读取三视角共 40 帧:前 20 帧是当前/历史,后 20 帧是未来;每两帧对应一个 codec latent,故 World 输入是 10 个历史 latent、预测 10 个未来 latent。Action target 是未来 20 个 14D absolute joint targets。开头不足的历史 repeat-pad,尾端不足的未来/action 用独立 mask。原始 zip/HDF5 每次按需读取和 JPEG 解码;**没有使用预先缓存的 codec latent、Qwen hidden 或预测未来 cache**,这些在训练时在线生成。[数据实现](../mira/src/mira/data/joint_online.py)。 + +采样器先等概率抽 50 task,再以 **0.5/0.5** 选 clean/randomized,再均匀抽该 task-domain 下的 episode 和该 episode 内可用 anchor;因此虽然原始 train episode 数约为 1:10,**期望训练采样域占比是 1:1**。这是有放回的随机采样,不是遍历一个固定 epoch,也不能把 `step × batch` 误解为 unique episode 覆盖率。训练按固定 seed/rank/全局位置产生采样序列,并在 checkpoint 保存 sampler 消耗位置。[采样器](../mira/src/mira/data/joint_online.py)。 + +按实际 batch 设置计算,第一段 `2449 × 72 = 176,328` 个**样本抽取**;后段 `(12531−2449) × 120 = 1,209,840` 个;合计约 **1,386,168 次 anchor 抽取**。这是训练机会数而非 1,386,168 个不同样本;相同 episode/anchor 可以重复出现,也不能据此断定模型见完了 3,960,801 个位置。离线验证使用固定 episode、anchor 选择和固定 noise,不参与梯度。[trainer 数据/验证逻辑](../mira/scripts/train_joint_world_action.py)。 + +特别注意:训练中的 `20Hz` 是数据重采样/标签契约;RoboTwin 闭环控制器在每个 waypoint 内可能运行可变数量的仿真步。此前审计已指出,不能未经控制遥测就把评测中 20 个重规划观测解释为物理时间上严格等间隔的 1 秒。[审计说明](../artifacts/audits/training_audit_20260920/01_code_and_evaluation_audit.md)。 + +## 5. 模型、损失和优化配置 + +| 组件 | 本次实际配置 | +|---|---| +| 初始化 | World-v12 `main-checkpoint-25066`;Action-v13 `action-checkpoint-23016`;codec `checkpoint-125000`;Qwen3-VL-2B-Instruct | +| 冻结 | Qwen 约 2.128B、codec 约 0.900B;两者不入 optimizer | +| 可训练 | World 约 1.350B、Action 约 0.516B;joint optimizer 参数共 **1,865,580,740** | +| World 主干 | hidden 2048、16 layers、16 query heads / 4 KV heads;三视角 latent `[3,10,32,9,12]` 的历史/未来契约 | +| 当前场景/状态 | Qwen 当前帧语义进入 trainable current resampler;World state encoder 处理 20 步双臂历史 | +| Action | horizon 20、width 1024、8 layers、16 heads;左/右通过 global hub 通信,不直接左↔右 attention | +| 推理求解 | World 10-step `linear_quadratic` Euler;Action 10-step Euler;一次预测 20 步、执行前 8 步再重规划 | +| 损失 | `1 × World flow FM + 1 × masked Action flow FM`;latent 重建与像素目标虽然可作为诊断指标计算,训练权重为 0 | +| 优化器 | AdamW,betas `(0.9,0.95)`,eps `1e-8`,weight decay `0.01`;World LR `1e-5`、Action LR `3e-5`;warmup 500 steps,之后 cosine 衰减 | +| 分布式 | 3 节点 × 8 H200;每节点 8-way FSDP2 shard、跨节点 3-way replication;BF16 参数/输出、FP32 reduce | +| 显存策略 | World 16 blocks 中 15 个 activation checkpoint;最后 block 的 MLP 和 condition attention 局部 checkpoint;Action block checkpoint 0 | + +配置依据:[resolved_config](../outputs/joint_anchor_v2_24gpu_long_20260930/resolved_config.json)、[联合模型实现](../mira/src/mira/joint/model.py)、[训练脚本](../mira/scripts/train_joint_world_action.py)、[部署导出](../outputs/joint_anchor_v2_24gpu_long_20260930/deploy-12531/deployment.json)。checkpoint 明确记录 `frozen_modules_excluded=[codec,qwen]`,并在训练入口检查 optimizer 参数集合等于全部 joint trainable 参数集合。训练输出对 codec/Qwen 做了冻结断言。这里的“全量微调”只指 joint World/Action,不指 Qwen/codec。 + +### Batch、吞吐和模型选择 + +| 阶段 | GPU | 每卡 batch × accum | 全局 batch | checkpoint 观察到的吞吐 | 最大 rank allocated 峰值 | +|---|---:|---:|---:|---:|---:| +| 09-23 4 卡试跑,独立分支 | 4 | 4 × 2 | 32 | step 500:1.12 sample/s | 114.56 GiB | +| 09-29 24 卡第一段 | 24 | 3 × 1 | 72 | step 2449:6.32 sample/s | 82.66 GiB | +| 09-30 起 24 卡续训 | 24 | 5 × 1 | 120 | step 12531:7.04 sample/s | 129.08 GiB(reserved 131.84 GiB) | + +上表吞吐与显存取自相应 checkpoint 的训练日志/状态,不是跨全过程稳定均值;batch 变化也改变了每 step 的梯度样本数,不能仅用 loss-vs-step 曲线判定相同数据预算下哪个配置更优。batch 迁移不是严格相同优化轨迹,但它保留了模型/优化器/LR/sampler/RNG 状态,没有从头重训。[迁移记录](../outputs/joint_anchor_v2_24gpu_long_20260930/resume_migration.json)。 + +SwanLab 项目是 [`Multi_WAM`](https://swanlab.cn/@Oranger/Multi_WAM);第一段 24 卡 run 为 [`f475a21e344b49489a8d9`](https://swanlab.cn/@Oranger/Multi_WAM/runs/f475a21e344b49489a8d9),后段为 [`0943698507ba4de181e5f`](https://swanlab.cn/@Oranger/Multi_WAM/runs/0943698507ba4de181e5f)。启动脚本清除代理环境变量、设置 `NO_PROXY=*`。本地 [metrics.jsonl](../outputs/joint_anchor_v2_24gpu_long_20260930/metrics.jsonl)、[validation.jsonl](../outputs/joint_anchor_v2_24gpu_long_20260930/validation.jsonl) 和三节点 log 是云日志之外的核验依据。 + +### 训练数值与离线验证:不能直接等同闭环性能 + +| step | 单次记录的 train `loss_world_flow` | train `loss_action` | 固定验证 `loss_action`(若有) | +|---:|---:|---:|---:| +| 2449 | 0.20243 | 0.00432 | —(第一段边界) | +| 5000 | 0.19851 | 0.00338 | 0.00992 | +| 8400 | 0.17944 | 0.00439 | **0.00693**(本目录 `best_validation.json` 的 Action FM 最低点) | +| 10000 | 0.19869 | 0.00289 | 0.00726 | +| 12400 | 0.19539 | 0.00265 | **0.01198** | +| 12531 | 0.19328 | 0.00193 | —(停止点本身未做该次固定验证) | + +验证每 200 step 运行一次,后段每次 3 batch/rank,按固定 Action flow MSE 写 `best_validation.json`。**正式评测使用最新 step 12531,而不是 offline-best step 8400。** 到 step 12400 时固定验证 Action loss 高于 step 8400;这值得后续排查,但不能单凭这个指标证明 12531 闭环较差,因为 FM teacher-forced MSE 不等于闭环成功率,且两者没有在同一全量 benchmark 上做对照。[best_validation](../outputs/joint_anchor_v2_24gpu_long_20260930/best_validation.json)、[validation.jsonl](../outputs/joint_anchor_v2_24gpu_long_20260930/validation.jsonl)。 + +## 6. 闭环评测协议、拓扑与可比性 + +本轮固定对象:`deploy-12531`,checkpoint fingerprint 为 `e22257d6...d0e87e13162c93`,RoboTwin commit `6dde57155eafa3e4ebf6ad1f93a7cf7d5d41a755`,run ID `joint12531_paper100_20261002`。评测是 50 个官方 Aloha-AgileX task、`demo_clean` / `demo_randomized` 两个 domain、每 task-domain **100 个有效 expert-checked closed-loop rollout**,目标共 10,000 次。seed 起点 100000;不合格 expert 初始状态跳过,成功/失败策略 episode 均存视频。部署 Action 为 joint/qpos target,World/Action 各 10-step,20-step chunk 执行前 8 步后重规划。[评测 manifest](../artifacts/evaluation/joint12531_paper100_20261002/manifest.json)、[评测说明](../artifacts/evaluation/joint12531_paper100_20261002/README.md)。 + +本次**实际** instruction 配置是 clean=`seen`、randomized=`unseen`(见[supervisor 代码](../mira/scripts/maintenance/run_joint_robotwin_formal.py)),不是 v6 计划文档中“两个 domain 均 unseen”的写法;整理对外报告时应以实际运行配置为准,必要时单独解释偏离。[计划原文](../z_oranger/plan/action_head_v6_stage/04_robotwin_benchmark.md)。不能把配置不同的历史 eval 直接合并。 + +原计划尝试两台仿真、一台策略;但 node17 的官方 SAPIEN/Vulkan renderer preflight 报 `failed to find a rendering device`,CUDA 可见不等于图形渲染可用,故**实际拓扑**为 node16 一台仿真节点(8 GPU)、node12/node17 两台策略节点(各 8 GPU)。最大并发 80 个 task-domain worker、每仿真 GPU 10 slot;策略计划 node12 每 GPU 4 副本、node17 每 GPU 6 副本。没有用 dummy 显存占位冒充评测吞吐。[启动脚本](../scripts/launch_joint12531_paper100_eval.sh)、[preflight log](../artifacts/evaluation/joint12531_paper100_20261002/node17_preflight.log)。 + +GPU 监控记录的各节点单卡**时间序列峰值**:node12 116,632–121,278 MiB、node17 127,719–134,911 MiB、node16 77,570–82,251 MiB。三个节点每卡都曾有 100% utilization 读数,但“曾到 100%”不代表全程 100%;node16 仿真卡显存较低也不意味着没有计算瓶颈。这些是 `nvidia-smi` 的整卡已用显存(可能含共跑进程),不等同本模型进程独占显存。[gpu_peaks](../artifacts/evaluation/joint12531_paper100_20261002/gpu_peaks.json)、[gpu_trace](../artifacts/evaluation/joint12531_paper100_20261002/gpu_trace.csv)。 + +### C2C/C2R 术语边界 + +RoboTwin 官方榜单的 C2C/C2R:只用 **每任务 50 条 clean demo** 训练,然后分别在 clean/randomized 评测,每条件每任务 100 次。[官方榜单](https://robotwin-platform.github.io/leaderboard)。本项目的训练是每任务 **49 clean + 490 randomized**;且评测 4 组缺失,因此即便评测场景对应 Easy/Hard,这一轮仍应写为 **“mixed clean+randomized training → clean/randomized evaluation,96/100 task-domain groups complete”**,不能标成与 clean-only 榜单直接可比的完整 C2C/C2R 分数。若后续需要论文对齐,必须先确定训练协议是否也重做,不能只把 Hard 改名为 C2R。 + +## 7. 评测结果:总体、逐任务与故障 + +截止 [summary.json](../artifacts/evaluation/joint12531_paper100_20261002/summary.json) 的最终写入时间 2026-10-05 19:22 UTC: + +| 口径 | 已完成组 | 成功 / 有效 rollout | 观察到的成功率 | +|---|---:|---:|---:| +| Easy=`demo_clean` | 49/50 | 2546/4900 | 51.959% | +| Hard=`demo_randomized` | 47/50 | 1891/4700 | 40.234% | +| 合并已结算 rollout | 96/100 | 4437/9600 | 46.219% | + +**分母不同,不能把上表的 Easy/Hard 平均或 46.219% 称为完整 50-task `average_easy_hard`。** 程序没有填充该最终字段。缺失的四组不是随机抽样而是特定仿真异常,观察到的 96 组成功率也不能简单当作完整结果的无偏估计。仅由缺失 1 个 Easy、3 个 Hard、每组 100 次这一事实可得算术边界:补齐后 Easy 必在 **50.92%–52.92%**,Hard 必在 **37.82%–43.82%**,两域等权平均必在 **44.37%–48.37%**;这是未知成功数取 0–100 的范围,**不是**置信区间或当前点估计,也不表示应该把失败组算 0。 + +下面每个数字是该 task-domain **100 次有效 rollout 中的成功次数**,因此数值也等于百分比。`失败` 表示没有形成合法 100-trial 结果,绝不表示模型 0% 成功。 + +| Task | Easy 成功/100 | Hard 成功/100 | +|---|---:|---:| +| adjust_bottle | 55 | 34 | +| beat_block_hammer | 51 | 58 | +| blocks_ranking_rgb | 8 | 1 | +| blocks_ranking_size | 37 | 41 | +| click_alarmclock | 100 | 90 | +| click_bell | 100 | 100 | +| dump_bin_bigbin | 88 | 70 | +| grab_roller | 100 | 56 | +| handover_block | 5 | 0 | +| handover_mic | 13 | 32 | +| hanging_mug | 23 | 10 | +| lift_pot | 60 | 7 | +| move_can_pot | 20 | 3 | +| move_pillbottle_pad | 15 | 3 | +| move_playingcard_away | 53 | 49 | +| move_stapler_pad | 25 | 14 | +| open_laptop | 78 | 69 | +| open_microwave | 77 | 82 | +| pick_diverse_bottles | 0 | 0 | +| pick_dual_bottles | 2 | 1 | +| place_a2b_left | 38 | 34 | +| place_a2b_right | 44 | 25 | +| place_bread_basket | 45 | 28 | +| place_bread_skillet | 48 | 17 | +| place_burger_fries | 85 | 88 | +| place_can_basket | 25 | 5 | +| place_cans_plasticbox | 45 | 1 | +| place_container_plate | 93 | 70 | +| place_dual_shoes | 49 | 29 | +| place_empty_cup | 77 | 32 | +| place_fan | 64 | 22 | +| place_mouse_pad | 51 | 40 | +| place_object_basket | 50 | **失败** | +| place_object_scale | 45 | 32 | +| place_object_stand | 87 | 82 | +| place_phone_stand | 59 | 56 | +| place_shoe | 82 | 53 | +| press_stapler | 92 | 94 | +| put_bottles_dustbin | **失败** | **失败** | +| put_object_cabinet | 9 | **失败** | +| rotate_qrcode | 77 | 63 | +| scan_object | 43 | 13 | +| shake_bottle | 100 | 97 | +| shake_bottle_horizontally | 98 | 99 | +| stack_blocks_three | 0 | 0 | +| stack_blocks_two | 13 | 14 | +| stack_bowls_three | 65 | 60 | +| stack_bowls_two | 88 | 68 | +| stamp_seal | 37 | 30 | +| turn_switch | 27 | 19 | + +分布并非“整体都差”:已结算的 96 组中,**12 组 ≥90/100、16 组 <10/100、5 组为 0/100**。例如 click_bell=100/100(两域)、shake_bottle=100/97;pick_diverse_bottles=0/0、stack_blocks_three=0/0、handover_block=5/0。`lift_pot` 60→7、`place_cans_plasticbox` 45→1、`place_empty_cup` 77→32 等出现较大 domain gap;`beat_block_hammer` 51→58、`open_microwave` 77→82 则 Hard 并非必然低于 Easy。以上只描述现象;任务难度、动作精度、视觉随机化、语言、控制时间与训练覆盖等候选解释尚未被单独证明。 + +### 四个未结算组:不要记成策略失败 + +| 组 | 中断前日志最后显示的部分进度 | 异常 | +|---|---:|---| +| Easy `put_bottles_dustbin` | 1/19 | task expert `IndexError: list index out of range` | +| Hard `place_object_basket` | 22/54 | task expert `AssertionError: target_pose cannot be None for move action` | +| Hard `put_bottles_dustbin` | 4/13 | 同上类 `IndexError` | +| Hard `put_object_cabinet` | 0/18 | 同上类 `target_pose` AssertionError | + +四组都在 **3 次连续 expert initialization check 异常**后按 evaluator 保护逻辑停止,`summary.json` 没把这些部分 rollout 纳入 9600 的正式分母。部分日志可保留作诊断,但不能与已完成组混算,也不能把异常归因于策略动作。[逐组日志目录](../artifacts/evaluation/joint12531_paper100_20261002/jobs/)、[supervisor.log](../artifacts/evaluation/joint12531_paper100_20261002/supervisor.log)。本轮进程已退出且没有自动补跑。 + +此前 step-2449 的 20-trial 诊断仅成功结算 14 组、280 次、250 成功(89.3%);task/domain 是挑选/未覆盖全量,还存在 1 组失败。它不能作为“2449 比 12531 好”的证据,分母、任务难度和试验长度完全不同。[早期诊断汇总](../artifacts/evaluation/joint2449_formal20_20260930/summary.json)。同理,step-12531 两个 1-trial pilot 的 2/2 也只说明接口跑通,不是模型性能估计。 + +## 8. 已验证的可复核性、尚未解决的分析问题 + +### 已经可以复核 + +- [step-12531 checkpoint](../outputs/joint_anchor_v2_24gpu_long_20260930/joint-checkpoint-12531/)有 trainer state、distributed 模型/优化器状态,可恢复;[deploy-12531](../outputs/joint_anchor_v2_24gpu_long_20260930/deploy-12531/)是本次评测实际加载的导出,manifest 记录其指纹。 +- step-12531 `trainer_state.json` 记录数据 manifest / normalization / 上游 checkpoint / codec / Qwen 指纹及五个关键源码 SHA。2026-10-10 核对时,这五个本地源码文件的 SHA 与记录一致;这降低了“当前训练源码与记录不同”的不确定性,但不代替完整环境/依赖锁定。 +- 96 个成功结算的 task-domain 均有 100 个视频;逐 task 的 `_result.txt` 与视频在 `transfer/robotwin-official-20260921/eval_result//BiHubJoint//joint12531_paper100_20261002//`。例如 [click_bell Easy 结果目录](../transfer/robotwin-official-20260921/eval_result/click_bell/BiHubJoint/demo_clean/joint12531_paper100_20261002/);`jobs//status.json`、`client.log`、`server.log` 可重查异常与种子。 +- [评测 manifest](../artifacts/evaluation/joint12531_paper100_20261002/manifest.json)有 checkpoint 指纹、RoboTwin commit、任务清单、seed 起点与实际节点拓扑;[gpu_trace](../artifacts/evaluation/joint12531_paper100_20261002/gpu_trace.csv)有硬件时间线。 + +### 待后续报告/实验特别处理(**问题,不是结论**) + +1. **完整性**:先处理四组 expert 初始化异常,在同一冻结模型/协议下补齐至 100/100 组;若必须改变 task 实现、seed 分布或 expert-check 逻辑,应记录为新评测协议,不能无声明地拼接旧结果。 +2. **checkpoint 选择**:step 12531 是最新权重而非 offline-best step 8400;当前无同协议全量闭环对照,不能从验证 MSE 推断哪一个成功率更高。 +3. **训练协议可比性**:clean + randomized 联训与官方 clean-only C2C/C2R 不同;本次 clean 训练每任务 49 条而非官方 50 条;实际 Easy seen/Hard unseen 与计划“两域 unseen”也不同。报告应同时写清训练集、instruction 设置和缺失任务。 +4. **长尾任务失效**:0/0 与较低任务有明显结构性聚集,但未做控制实验。建议后续逐任务观察失败视频、动作轨迹、gripper/双臂同步、状态误差、world future 质量和控制时序;不要仅凭任务名或低成功率断言某一模块失效。 +5. **训练数据与评测分布**:sampler 按 task/domain 均衡,但只从专家轨迹 anchor 学习;闭环偏离专家后的恢复状态未必在训练支持内。当前没有量化闭环 OOD 距离,也没有证明这是低分主因。 +6. **离线/在线指标脱节**:后段 train Action FM 值下降,不代表闭环更好;验证 Action FM 最低在 8400,12531 选用是为了评估最新训练进度,不是验证选择出的最优控制 checkpoint。 +7. **物理时间语义**:数据按 20Hz 设计,仿真 waypoint 的实际 `sim_steps/dt` 可能变动。若要检验对性能的影响,应保留当前控制器,先读取已有 controller telemetry/失败轨迹,而非直接改 benchmark 控制器。 + +本文没有执行新的训练、模型改动、失败组补跑或论文式显著性检验。任何后续对外结果应从成功补齐的同协议 task-domain 汇总重新计算,并独立说明训练数据设置。 diff --git a/release-20261107/source/workspace_joint/docs/project_layout.md b/release-20261107/source/workspace_joint/docs/project_layout.md new file mode 100644 index 0000000000000000000000000000000000000000..0393cd4a91696ffbea65588572ba9e2958370839 --- /dev/null +++ b/release-20261107/source/workspace_joint/docs/project_layout.md @@ -0,0 +1,45 @@ +# 项目目录与逻辑边界 + +```text +Mutil_WAM/ +├── README.md 当前入口,不把历史计划当作已验证结论 +├── docs/ 工作区级报告、验证步骤、目录导航 +├── scripts/ 简短操作入口:validate_joint.sh / serve_policy.sh +├── mira/ 主代码仓库 +│ ├── src/mira/codec/ 冻结视觉编码器与 codec +│ ├── src/mira/data/ 数据、采样与时序契约 +│ │ └── joint_online.py 当前修复版在线原始数据路径 +│ ├── src/mira/world_v6/ v6–v12 共用 World 网络实现 +│ ├── src/mira/action_v6/ v6–v13 共用 Action 网络实现 +│ ├── src/mira/joint/ 联合模型、成对导出、路径迁移 +│ ├── src/mira/inference/ 发布版 / research / joint 三类运行时 +│ ├── src/mira/training/ 历史分阶段训练基础设施 +│ ├── scripts/ 各阶段训练、导出、评测汇总 +│ │ └── maintenance/ HF 校验安装、CPU 预检 +│ ├── configs/ 按历史实验版本分组的配置 +│ ├── tests/joint/ 本次新增契约/梯度回归测试 +│ └── docs/ 代码级说明与历史阶段设计 +├── lingbot-vision/ 第三方编码器源码 +├── vendor/RoboTwin-official-eval/ HF 评测源码快照 + 本地适配修改(非完整评测安装) +├── models/ 冻结基础模型,不放训练日志 +├── datasets/ 原始数据与 episode manifests,不复制/下载数据集 +├── outputs/ 原始训练 checkpoint,以及之后的新实验输出 +├── artifacts/ +│ ├── audits/ 用户原始 zip 和解压后的只读证据 +│ ├── reports/20260920/ 本次校验、测试与真实数据预检结果 +│ ├── backups/20260920-pre-sync/ 同步前源码备份、已删除 smoke 的元数据备份 +│ ├── releases/20260902/ 发布参考身份与说明 +│ ├── legacy_logs/ 从代码目录移出的历史日志 +│ └── ... 原有缓存/统计(保留稳定入口) +├── transfer/ 下载与迁移暂存,不是训练源目录 +└── z_oranger/plan/ 原始设计资料,不作为执行状态 +``` + +没有把 `world_v6` 强行改名为 `world_v12`:它是多个版本共用的网络实现,直接改名会破坏旧导入与复现。 +同样不移动原有 outputs/缓存路径,也不批量重写 hash-bound JSON。跨机器路径仅在运行时解析。 +新实验用独立目录 `outputs/joint_anchor_v2*`;旧训练脚本保留作对照,不作为修复版入口。 + +本次实际清理:移走源码中的 `mira/z_tmp` 日志;审计 zip 归档到 artifacts/audits;删除无代码引用的 +codec 30-step smoke 的 checkpoint-29(约 14 GiB),保留其配置、日志和可视化。 +旧 5B、World-80k、codec-125k 等非 smoke 权重仍保留,不能仅凭版本旧判定无用。 +Python 编译缓存加入 mira/.gitignore,避免在源码变更列表中混入生成物。 diff --git a/release-20261107/source/workspace_joint/docs/repair_report_20260920.md b/release-20261107/source/workspace_joint/docs/repair_report_20260920.md new file mode 100644 index 0000000000000000000000000000000000000000..27d296e3eb37b1cb9b8fa735087c7130cfce7550 --- /dev/null +++ b/release-20261107/source/workspace_joint/docs/repair_report_20260920.md @@ -0,0 +1,73 @@ +# 2026-09-20 同步与修复报告 + +后续验证更新:经用户授权,已完成GPU4~7卡的只读推理/前向检查,见 [GPU验证补充报告](gpu_validation_20260920.md)。 +下文“没有启动GPU任务”等表述描述初次修复交付时点;训练和闭环评测仍未启动。 + +## 结论与验证边界 + +已经直连同步最新 HF 代码和发布 checkpoint,完成可确认问题的实现修复与 CPU 验证。 +**没有启动 GPU 任务,没有更新权重,没有证据证明成功率已经提高。** 修复集中在报告路线 A 的数据/接口可靠性; +没有直接实现路线 B 的 current-feature 新架构,也没有把多项研究假设当作已证实的原因。 + +## 同步与可追溯性 + +源仓库 `Orangerl/multi-wam`,固定 revision `1d9b974503993785fc6f59ec62379909173271ea`。 +先恢复 9 月 2 日完整源码包,再覆盖该 revision 中 9 月 4 日的 `source/mira` 联合训练代码。 +源码包 SHA256:`2173c25bd03db0b4f5448087c6b393f266bf8666d429c7e0f9bdb3e5e663cdf4`。 +评测包 SHA256:`5ddb3e8909341a0744ef877fbeb16b5005e87f857f9ef21fec09c67ac9cf25b0`。 +下载前清除全部大小写代理变量,设置 NO_PROXY/no_proxy=*。没有重新下载数据集、codec 或相同基础模型。 + +校验并安装 72 个 checkpoint 文件(约 34.93 GB 十进制):World-v12 25066、Action-v12 5754、 +Action-v13 11508 和 23016,均保留 optimizer/rank state。逐文件 SHA256 匹配发布清单,详细证据在 +`artifacts/reports/20260920/hf_sync.json`。暂存与 outputs 使用硬链接,未重复占用一份 checkpoint 空间;请勿原地修改权重。 +codec-125000 复用本机,SHA256 `c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615` 已重新验证。 +同步前本地源码/计划已备份;未清空用户 worktree、未执行 git reset、未上传本地修复到 HF。 + +## 已修复的内容 + +| 问题 | 落地处理 | +|---|---| +| Joint trainer 缺失 WorldV6System 导入 | 补齐导入,CLI/import 通过;不再在初始化触发该 NameError | +| 75% 样本来自固定短前缀,许多进度锚点缺失 | 新 joint sampler 按 task→domain→episode→当前 20Hz 观测均匀采样,再决定可见 history;不再人为等分 H1/H3/H6/H10 | +| 部署首次为重复当前 RGB,训练却用相邻两帧 | 原始 RGB 在线构造与 adapter 相同:初始两个有效 state,重复首观测;随观测追加;replan 0/8/16/24 对应 H1/H5/H9/H10 | +| 完整未来窗口筛掉尾段 | 独立 action_valid[20]、future_valid[10]、future_rgb_valid[20];末段 repeat padding 不进入对应 loss;最后只剩一个动作也可训练 | +| 旧 manifest 排除短 episode | builder 增加 --min-latents 1,专用于 masked joint 路径;不改变旧默认20。新 joint manifest 保留奇数末观测;已有旧 manifest 仍按其原契约读取 | +| action 加权 loss 的 gripper transition 可受 padding 值影响 | 只在有效动作位置检测 gripper 变化 | +| warm-start 可能重估 normalization | 使用发布 World state stats 并验证哈希;action normalization/delta buffer 从发布 checkpoint 严格加载,bounds 也校验 | +| 2-step train / 10-step deploy 不一致 | 默认统一10步 linear-quadratic;joint export 绑定训练步数,新 runtime 按导出契约执行,不能默默改回10 | +| 多个 rollout 重建 loss 同时开启,难以判断作用 | latent/RGB 默认为0,只保留 World FM + Action FM;非零为显式独立消融;pixel=0 时跳过 decoder 计算 | +| 联合训练无验证与最佳模型管理 | 固定验证 episode/进度/noise,独立 validation.jsonl;按固定 Action FM 选 offline-best,保存最近3份和5000-step里程碑;这不是闭环最佳模型 | +| 新 joint 无完整部署接口 | 成对导出 World/Action,Action 重绑定当前训练后的 World state encoder;导出 SHA、配置、stats、采样参数写入 deployment.json;增加 BiHubJoint runtime/adapter | +| 旧部署把 Action step 写死为最终步 | 保留原正式版约束,另增显式 BiHubResearch,允许11508等同架构 checkpoint;仍校验 World 绑定 | +| checkpoint 路径绑定旧机器 | 在内存中映射到当前 workspace,World 配置从自身 trainer_state 读取,不修改原始 fingerprint 元数据 | +| 分布式停止/最佳保存不同步风险 | stop 与 best decision 跨 rank 同步;先完整 checkpoint 后提交 best 指针;异常梯度停止,不静默 step;禁止 no-auto-resume 覆盖已有 checkpoint | +| 评测统计不完整、可能忽略无 replan 回合 | 新汇总工具保留所有失败/零 replan 分母,检查重复及混合 checkpoint,分别给 observed macro/micro 和完整性标记 | +| 20Hz metadata 不等于仿真实际 waypoint 时间 | 添加可选 controller telemetry,记录每个 waypoint 的实际 sim steps/dt 和12个 arm joint跟踪误差;不改变 TOPP 或控制频率 | + +尾段没有有效 future latent 时,World FM 允许可微零损失,Action 仍监督有效下一目标;老 World-only 训练默认仍拒绝空 future。 +当前锚点均匀并不意味着与策略实际访问分布完全相同,也不等于专家外恢复数据。旧 cache/sampler 不被悄悄改写: +**以上采样修复通过新的在线 joint 路径使用,不会追溯修复既有 v12/v13 权重或 predicted-future cache。** + +## 已做检查 + +- 新增 CPU 测试:真实格式 zip/HDF5/JPEG、全部锚点覆盖、冷启动、独立尾段 mask、跨 rank 采样序列/恢复、成对 state encoder 导出。 +- 小模型 CPU 验证:空 future 零 loss、padding 不影响有效 World loss、2/4/10 步训练/部署 rollout 数值一致(容许 FP32 内核舍入)。 +- 仅反传 Action loss,已验证梯度到达 World、Qwen 后的 current resampler、live state encoder 和 Action。 +- 真数据 CPU 预检读取 train/val 的首段、anchor8、尾段共6个样本;三视角解码正常、split无 episode 交叉、checkpoint 指纹和 codec/state stats 哈希匹配。 +- 第一组回归 23 tests 全部通过;扩大回归 **151 tests 全部通过**,有7条第三方单进程DCP/fork/storage警告。 + 首次扩大检查发现历史 YAML 仍引用旧机器:已仅对源码 configs 做路径迁移,再在 mira 工作目录重跑通过。 + 没有改写 checkpoint 的 trainer_state 或 hash-bound artifact。结果见 `artifacts/reports/20260920/extended_cpu.log`。 +- 重新统计发布 partial full50:1052 回合 / 25任务,586成功,micro55.70%、observed macro41.38%,28个零replan记录仍计入分母;不是完整50任务结果。 + +## 未声称修复/仍需验证 + +1. 两卡 FSDP2 的真实峰值显存、速度、断点恢复,以及完整 codec/Qwen/World/Action GPU前反向:当前没有空闲 GPU,尚未测量。 +2. 10-step rollout 比原2-step成本高。若显存不足,先减 micro-batch、累积保持 global batch;改 rollout步数是新训练/部署协议,不能当作质量不变的优化。 +3. 完整短 episode manifest 尚未重新全盘扫描;CPU preflight/smoke 用现存 ALOHA 审计 split,正式运行前执行 prepare。新数据路径不使用陈旧 future cache。 +4. 固定 Action FM 是便宜的选择代理,不能替代固定seed的真实采样误差和官方闭环 SR。8个验证batch默认只适合初筛。 +5. HF 评测 archive **缺少 XPolicyLab/model_template.py、setup_policy_server.py 等基础文件**,本机没有已验证的 RoboTwin eval conda 环境。应从原评测机器恢复其固定 revision 和资源,不能为方便换成未知的最新控制器。 +6. telemetry 已实现、语法检查通过,但真实 SAPIEN 下尚未执行;不会声称完成 expert action replay 或物理时间对齐。 +7. 不更换 command-state 为 measured qpos,不更改已有 action shift、gripper单位、执行8步、控制器、codec/Qwen/主干容量。报告没有证据支持这些是确定 bug。 +8. 没有强推 current-only、新 current-feature架构、KI、恢复数据、language预训练;这些是独立研究对照,不宜与修 bug 混成一次无法归因的实验。 + +目录整理与删除明细见 project_layout.md,后续实际命令见 validation_20260920.md。 diff --git a/release-20261107/source/workspace_joint/docs/validation_20260920.md b/release-20261107/source/workspace_joint/docs/validation_20260920.md new file mode 100644 index 0000000000000000000000000000000000000000..5babfb9a669fcdbfd9d00ea33f1dfc3a7221f9bd --- /dev/null +++ b/release-20261107/source/workspace_joint/docs/validation_20260920.md @@ -0,0 +1,128 @@ +# 修复版验证顺序 + +后续更新:CPU和GPU只读验证均已通过,见 [GPU验证结果](gpu_validation_20260920.md)。 +本文的训练smoke、续训、已训练joint导出及闭环步骤仍**未执行**,当前用户要求不启动训练。 +仅做推理检查可运行 `bash scripts/validate_joint.sh gpu-inference`,使用GPU4~7,不会执行optimizer step。 +不要直接跑旧的 World-v12 remaining-epoch launcher:该发布训练已经结束。 + +## 1. 无 GPU 检查 + +在工作区根目录运行: + +```bash +export MIRA_PYTHON=/private/software/conda/envs/mira/bin/python +bash scripts/validate_joint.sh cpu +bash scripts/validate_joint.sh preflight +``` + +cpu 默认禁用 CUDA,执行151项契约/回归测试。preflight 检查已恢复 checkpoint、codec、state normalization、 +split隔离,并解码真实首段/中段/尾段。已有结果在 artifacts/reports/20260920。 + +正式联合实验前,准备可保留短 episode/奇数末帧的新 manifest(解压读取原 zip,可能较慢,但不使用 GPU): + +```bash +JOINT_PREPARE_ONLY=1 MIRA_PYTHON="$MIRA_PYTHON" \ + bash mira/scripts/launch_joint_world_action.sh datasets/RoboTwin2.0 + +JOINT_MANIFEST_DIR="$PWD/datasets/RoboTwin2.0/mira_manifests/joint_anchor_v2" \ + bash scripts/validate_joint.sh preflight +``` + +现有 source train/val split 复用;新 manifest 写到独立目录,不覆盖旧 split/cache。检查 summary.json 的 +complete_audit、rejected、split_overlap 和任务分布。源码修改 min-latents 后不要复用旧 joint-v1 manifest。 +预训练 state/action normalization 继续使用发布版,不随新 manifest 重估。 + +## 2. 两卡 GPU smoke:先检查显存,不先开长训练 + +```bash +CUDA_VISIBLE_DEVICES=6,7 bash scripts/validate_joint.sh smoke +``` + +默认 micro-batch1、accumulation1、3个 optimizer steps、10-step rollout、末步2个validation batches。 +仅做 smoke 可用既有 ALOHA manifest;正式跑使用新 joint_anchor_v2。 +日志在终端,以及 outputs/joint_anchor_v2_smoke/{metrics.jsonl,validation.jsonl,resolved_config.json}。 +检查:所有 loss/grad_norm 有限;checkpoint-3完整;没有 NaN/OOM;World/Action 都有更新。 +metrics 的 `peak_memory_gib_max_rank` / `peak_reserved_gib_max_rank` 是所有 rank 的 PyTorch 峰值; +它们不包含其他进程及全部驱动/NCCL开销,同时用 nvidia-smi 检查卡级总占用。 + +若只剩40GB/卡,**不能保证10-step联合反传装得下**。不要擅自扩大到其他卡;记录 OOM 后再决定资源/配方。 +将 rollout 改2/4步必须用新 output 目录,并同步使用导出的 joint runtime;不能宣称这是无损加速。 + +测试续训: + +```bash +CUDA_VISIBLE_DEVICES=6,7 bash scripts/validate_joint.sh smoke --max-steps 6 +``` + +应从3继续到6,而不是重跑1。seed、global batch、lr、总计划steps、loss、数据/code identity不同会拒绝旧恢复。 +比较 uninterrupted 6-step 与 3+3-step 的固定验证指标;首次先接受合理浮点误差,不预设所有 GPU 内核逐bit一致。 + +## 3. 成对导出与 GPU 推理 + +```bash +bash scripts/validate_joint.sh export \ + outputs/joint_anchor_v2_smoke/joint-checkpoint-6 \ + outputs/joint_anchor_v2_smoke/deploy-step6 +``` + +CPU导出需要容纳完整 World/Action 参数的主机内存。目标目录必须不存在,避免覆盖旧部署。 +deploy目录含 World/Action safetensors、deployment.json;codec/Qwen仍使用 models/ 和 codec checkpoint稳定入口。 +其中 Action state encoder 必须等于导出 World 的 live encoder,采样步数从metadata读取。 + +正式闭环评测前还有环境依赖:HF archive 缺失 XPolicyLab/model_template.py 和 setup_policy_server.py。 +请从原评测机恢复**相同版本**完整 RoboTwin/XPolicyLab、SAPIEN/Vulkan、机器人资产与对应 eval conda环境。 +不要直接 `git pull main` 改变 benchmark。已有封装会在缺失时明确停止。 + +将本次 BiHubJoint/BiHubResearch 两个 adapter目录复制到完整checkout的 XPolicyLab/policy 下; +完整checkout使用本工作区 mira/src。服务器示例: + +```bash +export ROBOTWIN_EVAL_ROOT=/path/to/complete/pinned/RoboTwin +CUDA_VISIBLE_DEVICES=6 bash scripts/serve_policy.sh BiHubJoint \ + outputs/joint_anchor_v2_smoke/deploy-step6 19200 +``` + +这只启动 policy server,不会自动运行 simulator。client沿用原评测协议、真实 ALOHA 机器人配置; +`arx_x5` 是已发布 adapter 使用的6+1 action profile,不代表更换仿真 embodiment。 +先验证一次真实 observation→20×14有限动作→执行8步→重规划,以及初始 H1→H5→H9→H10。 + +## 4. 已有模型优先做的诊断(不重训) + +- 相同 World25066,分别评测 Action23016 和11508;使用 BiHubResearch,实际step与fingerprint写入provenance。 +- 固定 probe8、domain、seen/unseen、expert seeds、controller与执行长度。首先确保原23016参照可复现。 +- 在完整 simulator中应用本次 controller telemetry 补丁,设置 `ROBOTWIN_CONTROL_AUDIT=/path/to/new/run/controller`。 + 记录sim steps/dt、issued target、12D arm实测qpos/跟踪误差;gripper state不冒称实测角度。 +- 用同一控制器回放专家目标,观察接触、抓取、释放和尾段。先排查接口,再讨论模型容量。 +- 独占资源时单独测端到端延迟;共享卡的推理耗时不直接归因为模型造成控制失败。 + +官方 full50 的统计必须足量并保留失败/异常。对一个单独run汇总: + +```bash +"$MIRA_PYTHON" mira/scripts/summarize_robotwin_eval.py /path/to/one/run \ + --expected-tasks /path/to/tasks50.json --episodes-per-task 100 \ + --output artifacts/evaluation/one_run_summary.json +``` + +tasks50.json是50个task名组成的JSON数组。脚本检查计数完整性、重复和混合模型,不能代替seed/指令协议检查; +未完成结果会标 incomplete,零replan回合不被删除。基础设施错误单独分类,修复后用同一seed重跑,不能挑成功回合。 + +## 5. 从 smoke 到实验 + +先选少量任务与1/10/100个episode做可学习性验证,再扩大数据,先不要直接跑数万步。 +小数据过拟合和闭环仍失败时,继续查接口/目标,不通过堆训练量掩盖问题。 +本次 joint-anchor-v2 同时改变了采样、cold start、联合优化配方,结果不能全部归因于“移除history偏置”。 +研究对照应分别保留 released A0、修正数据的冻结World版本、匹配rollout的joint版本;不临时复用旧future cache。 + +通过 smoke / 恢复 / 部署验证后,一个global batch32的两卡起点为: + +```bash +CUDA_VISIBLE_DEVICES=6,7 NPROC_PER_NODE=2 H200_PROFILE=0 \ +MIRA_PYTHON="$MIRA_PYTHON" OUTPUT_DIR="$PWD/outputs/joint_anchor_v2_main" \ + bash mira/scripts/launch_joint_world_action.sh datasets/RoboTwin2.0 \ + --per-device-batch 1 --gradient-accumulation 16 --world-rollout-steps 10 \ + --weight-latent 0 --weight-pixel 0 --log-every 100 \ + --validate-every 500 --validation-batches 40 +``` + +这是待验证的实验起点,不是已证明最优配方。优先保持global batch/样本暴露量一致做对比; +后续增加latents/RGB loss、current-only或新结构须单独命名。用闭环成功率决定有效性,不能仅看loss下降。 diff --git a/release-20261107/source/workspace_joint/mira/.gitignore b/release-20261107/source/workspace_joint/mira/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..3ddfc73c065c878ca6d62628c2f5212b356646a1 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/.gitignore @@ -0,0 +1,5 @@ +__pycache__/ +*.py[cod] +.pytest_cache/ +.ruff_cache/ +*.egg-info/ diff --git a/release-20261107/source/workspace_joint/mira/LICENSE b/release-20261107/source/workspace_joint/mira/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..834d9d9c16094a386cd9b5a6f9ced9a3a9b4e7fb --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative + Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/release-20261107/source/workspace_joint/mira/README.md b/release-20261107/source/workspace_joint/mira/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c79155e3b34f6436b6d489c05b11cad8d0eae700 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/README.md @@ -0,0 +1,207 @@ +## MIRA: Multiplayer Interactive World Models with Representation Autoencoders + +[![Live demo](https://img.shields.io/badge/demo-mira--wm.com-0091FF.svg)](https://mira-wm.com)  +[![Paper](https://img.shields.io/badge/paper-technical%20report-b31b1b.svg)](https://arxiv.org/abs/2607.05352)  +[![Dataset](https://img.shields.io/badge/%F0%9F%A4%97%20dataset-rocket--science-yellow.svg)](https://huggingface.co/datasets/kyutai/rocket-science)  +[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE) + +https://github.com/user-attachments/assets/ca82b521-3e53-4f1b-8b27-9126a49aa5ea + +MIRA is a real-time world model of Rocket League: a 5B parameters +latent diffusion model generates the video frame by frame from all four players' actions, so a full 2v2 +match can be played inside the model at 20 FPS on a single GPU. Play it live at +[mira-wm.com](https://mira-wm.com). + +This is the official code release for the technical report:
+[MIRA: Multiplayer Interactive World Models with Representation Autoencoders](https://arxiv.org/abs/2607.05352), a collaboration between
+[General Intuition](https://www.generalintuition.com), [Kyutai](https://kyutai.org), and [Epic Games](https://www.epicgames.com/site/home). + +architecture + +``` +@article{mira2026, + title={{MIRA}: Multiplayer Interactive World Models with Representation Autoencoders}, + author={Hu, Anthony and Volhejn, V{\'a}clav and Ramanana Rahary, Adrien and Mulder, Chris and Makkar, Aditya and Liao, Alyx and Royer, Am{\'e}lie and Orsini, Manu and Jelley, Adam and Alonso, Eloi and Laurent, Florian and Nor{\'e}n, Fredrik and Swingos, James and H{\"u}nermann, Jan and Rollins, Kent and Hosseini, Lucas and Le Cauchois, Matthieu and Peter, Maxim and de Witte, Pim and Brown, Tim and Micheli, Vincent and B{\"o}hle, Moritz and de Marmiesse, Gabriel and Sharmanska, Viktoriia and Specia, Lucia and Black, Michael and P{\'e}rez, Patrick}, + year={2026}, + note={Technical Report}, +} +``` + +### Installation + +```bash +pixi run setup # one-time: creates the environment and installs MIRA (requires an NVIDIA GPU) +pixi run test # run the test suite +``` + +Requires [pixi](https://pixi.sh) and torch >= 2.8 (installed for you). + +The stable design contract for the RoboTwin/LingBot codec and its downstream WAM interface is +documented in [docs/robotwin_lingbot_codec_design.md](docs/robotwin_lingbot_codec_design.md). +The post-codec three-view BiHub Stage-W pipeline, measured memory budget, and launch gates are in +[docs/bihub_wam_stage_w_pipeline.md](docs/bihub_wam_stage_w_pipeline.md). + +This workspace defaults codec training to the local LingBot-Vision-Large backbone. Install the +sibling source tree into the same environment: + +```bash +uv pip install --python "$CONDA_PREFIX/bin/python" -e ../lingbot-vision +export LINGBOT_VISION_MODEL_DIR=../models/lingbot-vision-vit-large +``` + +The LingBot adapter accepts only an existing local directory or `.pt` file and never falls back to +downloading weights. The original MIRA DINO codec remains available as +`model=raev2_codec_tdown`. + +### RoboTwin codec dataset + +Codec training defaults to the local RoboTwin 2.0 dataset at `../datasets/RoboTwin2.0`. The loader +streams HDF5 episodes directly from the task zip archives, so the 1.4 TB dataset does not need to be +extracted or duplicated. It reads the aligned `head_camera`, `left_camera`, and `right_camera` +JPEG streams. + +Training assigns each episode one camera per epoch and rotates the assignment across the three +cameras. This provides balanced coverage over three epochs without putting three highly correlated +views next to one another in a batch or reading the same HDF5 payload three times. + +The RoboTwin codec uses 288×384 frames rather than the original Rocket League codec's 288×512. +This preserves the cameras' native 4:3 aspect ratio without letterbox waste while remaining +divisible by the codec's 32× spatial downsampling (a 9×12 latent grid). + +The first launch creates an episode-disjoint train/validation manifest under +`../datasets/RoboTwin2.0/mira_manifests`. Splitting is performed independently inside every +task/robot/domain archive. It then builds a clip-compatible manifest under +`mira_manifests/codec_40f_30to20`: 40 output frames at 20 FPS require at least 60 source frames at +30 FPS. Every archive is probed at evenly spaced episodes, and an archive is fully audited when a +probe is short, corrupt, missing a camera, or has misaligned camera lengths. The audit is cached; +set `REBUILD_COMPAT_MANIFEST=1` to force it to run again. Any rare invalid episode missed by +probing is remembered by each loader worker after its first failure instead of being retried every +epoch. Set `REBUILD_MANIFEST=1` if the downloaded archive set changes. + +### Rocket League dataset + +Each sample is a 4-second window of a 2v2 match, captured from all four players' synchronised views. +For every frame of every view, the dataset provides the video frame, the player's keyboard action, +and the game state (ball, cars, and score). The full dataset is on +the [HuggingFace Hub](https://huggingface.co/datasets/kyutai/rocket-science) (see the +[dataset card](docs/dataset_card.md)). + +```python +from mira.data import RocketScienceDataset + +# Download the test split. shards=1 pulls just one shard for a quick look; omit it for the full split. +ds = RocketScienceDataset.from_hub("kyutai/rocket-science", split="test", shards=1) + +# Load the clips of the first match (16 frames each, sampled at 20 FPS) and take the first one. +clips = ds.load_match(ds.match_ids()[0], clip_len=16, target_fps=20) +clip = clips[0] + +# A clip holds P=4 synchronised player views over T=16 frames: +clip.frames # tensor (P, T, C, H, W) uint8 — the rendered video, one per player +clip.actions # tensor (P, T, 9) int32 — multi-hot keyboard state, aligned to each frame +clip.events # list of game events overlapping this window (goals, boost pickups, ...) +clip.physics # per player, per frame: game state (ball, cars, score) +``` + +Explore it interactively (4-player grid, keyboard overlay, top-down overview of the game using the game state): + +```bash +pixi run explore +``` + +### Training + +Entry points under `scripts/` are Hydra apps — override any config key as `key=value`. Multi-GPU runs +go through `torchrun`; single-GPU works too. + +```bash +# Inspect the fully resolved launch without starting training. +DRY_RUN=1 ./scripts/train_robotwin_codec.sh + +# Start on all visible GPUs. Rank zero logs to the private SwanLab project Multi_WAM. +./scripts/train_robotwin_codec.sh + +# Common overrides (all optional). +CUDA_VISIBLE_DEVICES=0,1,2,3 \ +NPROC_PER_NODE=4 \ +BATCH_SIZE=1 \ +NUM_WORKERS=4 \ +LOG_EVERY=100 \ +OUTPUT_DIR=/path/to/output \ +SWANLAB_MODE=online \ +SWANLAB_TOKEN_FILE=/path/to/token.txt \ +RUN_NAME=lingbot-robotwin-codec \ +./scripts/train_robotwin_codec.sh + +# On a shared node, queue until every selected GPU is genuinely idle. Actual launches refuse +# occupied GPUs by default; set REQUIRE_IDLE_GPUS=0 only when co-scheduling is intentional. +WAIT_FOR_IDLE_GPUS=1 \ +GPU_IDLE_STABLE_CHECKS=3 \ +./scripts/train_robotwin_codec.sh + +# Enable compilation only after an uncompiled real-data step succeeds. +RUN_COMPILE=true ./scripts/train_robotwin_codec.sh + +# The original Rocket League codec path remains available explicitly. +MIRA_PROCESS_NAME=syncnet_codec \ +exec -a syncnet_codec_train python scripts/train_codec.py \ + dataset=rocket_league \ + dataset.train_index=/path/to/train \ + dataset.test_index=/path/to/test + +# Train the single-player world model +python scripts/train_world_model.py \ + model.architecture.config.codec_checkpoint=/path/to/codec_ckpt \ + dataset.train_index=/path/to/train dataset.test_index=/path/to/test + +# Train the 4-player world model, warm-started from a single-player checkpoint +python scripts/train_world_model.py model=multi_wrapper_world_model dataset.n_players=4 \ + model.architecture.config.wm_config.codec_checkpoint=/path/to/codec_ckpt \ + run.finetune_from=/path/to/single_player_ckpt \ + dataset.train_index=/path/to/train dataset.test_index=/path/to/test +``` + +The preflight/waiting shell is named `syncnet_wait`; the distributed launcher and workers use +`syncnet_codec*`. Fixed reconstruction cases are retained under +`$OUTPUT_DIR/visualizations/case-*/step-*_all_views.mp4`. Each video has three rows (`head`, `left`, +`right`), and every row is ground truth beside reconstruction. +Terminal loss summaries and SwanLab scalar metrics are logged every 100 steps by default; this is +independent of the more expensive visualization, validation, and checkpoint schedules. +`cases.json` pins the episode and temporal window, so resumed runs always compare the same cases. +The launcher reads the SwanLab credential from `z_oranger/token.txt` by default without putting it +in the command line or persisting it in SwanLab's global login file. Rank zero records training and +validation losses, learning rate, latent statistics, gradient norms, step time, GPU memory, resolved +configuration, per-view sample counts/fractions, and the fixed-case videos in the private +`Multi_WAM` project. Compact +`step-*_cloud.gif` copies are uploaded because SwanLab video media currently requires GIF; the MP4 +files remain the canonical local visualizations. Cloud GIFs default to 2 FPS and a 384-pixel +maximum side to reduce upload time without changing local reconstruction evidence. +`$OUTPUT_DIR/swanlab_run_id.txt` makes checkpoint resumes continue the same cloud experiment. + +The optional original DINO baseline uses a frozen **DINOv3-L/16** encoder whose weights are gated by Meta. Download +`dinov3_vitl16_pretrain_lvd1689m-8aa4cbdd.pth` from the +[DINOv3 page](https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/) and set +`RS_DINO_WEIGHTS_DIR=/path/to/weights`. World-model training and inference don't need it. + +### Evaluation + +```bash +python scripts/eval_world_model_offline.py /path/to/checkpoint-1000/checkpoint.pth +``` + +### Joint World + Action fine-tuning (no caches) + +The released World-v12 and Action-v13 models can be fine-tuned end to end while keeping Qwen and +the codec frozen. RGB, Qwen features, codec latents, predicted futures, and both supervised losses +are computed online; only lightweight dataset manifests are created: + +```bash +bash scripts/launch_joint_world_action.sh /path/to/RoboTwin2.0 +``` + +See [docs/joint_world_action_online.md](docs/joint_world_action_online.md) for the gradient paths, +loss definition, checkpoint behavior, and optional overrides. + +### License + +Apache License 2.0 — see [LICENSE](LICENSE). diff --git a/release-20261107/source/workspace_joint/mira/THIRD_PARTY_LOCK.md b/release-20261107/source/workspace_joint/mira/THIRD_PARTY_LOCK.md new file mode 100644 index 0000000000000000000000000000000000000000..882f5d2bb1e3b2992c2753c81c28d392fc44ca3e --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/THIRD_PARTY_LOCK.md @@ -0,0 +1,23 @@ +# Stage-W third-party evidence lock + +Audited on 2026-07-18. These revisions are evidence and interface references. Stage W does not use +an external world-model checkpoint; its one external runtime weight is the frozen text encoder below. + +| Project | Revision | Role | +|---|---|---| +| MIRA | `db25448391d42547161673a77950a1154d8b5f1f` | Base flow, attention, RoPE, optimization evidence | +| LaWAM | `1add20a376126eacab02f19a62d726072a322cae` | Deferred future-to-action interface only | +| Fast-WAM | `45d8e1458921d83f8ad6cf9ce993d371208dabd0` | UMT5 cache and RoboTwin three-camera reference | +| RoboTwin 2.0 | `c3ddfa8b97d5519efa828b075999bd0006778e5e` | Raw schema and simulator semantics | + +Frozen text encoder: + +- repository: `Wan-AI/Wan2.2-TI2V-5B` +- revision: `921dbaf3f1674a56f47e83fb80a34bac8a8f203e` +- file: `models_t5_umt5-xxl-enc-bf16.pth` +- tokenizer: `google/umt5-xxl/` from the same revision +- workspace location: `../models/wan-umt5-xxl/` (downloaded with proxy variables unset) +- encoder SHA-256: `7cace0da2b446bbbbc57d031ab6cf163a3d59b366da94e5afe36745b746fd81d` + +The local preprocessing script records content SHA-256 values in every text-cache namespace. The +codec checkpoint SHA-256 similarly namespaces every latent cache. diff --git a/release-20261107/source/workspace_joint/mira/configs/README.md b/release-20261107/source/workspace_joint/mira/configs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..291ac25d5a582e93c2fbace6a0e5e8f588750e49 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/README.md @@ -0,0 +1,90 @@ +# Hydra configs + +Hydra YAML configuration for training and inference. Entry-point scripts under `scripts/` load +these via `@hydra.main(config_path="../configs")`, so any key can be overridden on the command line +as `key=value`. + +``` +configs/ + train_codec.yaml # codec training (RAEv2 temporal-downsampling) + train_world_model.yaml # latent world-model training + train_bihub_wam_world.yaml # RoboTwin three-view 1.397B BiHub world model + train_bihub_wam_world_smoke.yaml # exact-architecture local 8-GPU smoke + eval_world_model.yaml # offline world-model evaluation + model/ # model architectures (codec, latent world model, multiplayer wrapper) + dataset/ # dataset source (train/test splits, n_players, target fps) + actions/ # action vocabulary (9-key DEFAULT_RL_KEYS, target fps) +``` + +## Entry-point configs + +- **`train_codec.yaml`** composes `model: lingbot_raev2_codec_tdown` and + `dataset: robotwin2`, plus the `run`, `swanlab`, `wandb`, `dataloader`, `validation`, + `visualization`, and `optim` blocks for codec reconstruction training. SwanLab is the default + tracker (`project: Multi_WAM`); W&B remains disabled by default for compatibility with the + original path. Override `model=raev2_codec_tdown` for the original DINO baseline. +- **`train_world_model.yaml`** composes `model: latent_world_model` and `dataset: rocket_league`, + and adds a `world_model_metrics` block (rollout DINO/latent drift and Frechet curves) run every + `validation.downstream_val_every`. +- **`eval_world_model.yaml`** is the offline-evaluation entry point. It carries only the + `world_model_metrics` block; the checkpoint supplies its own model and dataset config, so this + file just configures how the eval is run (set `checkpoint` and `output_dir` at eval time). +- **`train_bihub_wam_world.yaml`** is the world-only RoboTwin run: 30k role-balanced + single-view steps followed by 120k full-BiHub steps, FSDP2 full shard, deterministic validation, + DCP/EMA recovery, local decoded fixed cases, and SwanLab `Multi_WAM` scalar logging. +- **`train_bihub_wam_world_smoke.yaml`** uses the exact 1.397B model for a local two-step 8-GPU + integration gate. Cloud logging, visualization, and checkpoint writes are disabled for this + disposable test; its output is removed after validation. + +## `model/` + +- **`lingbot_raev2_codec_tdown.yaml`** — the workspace default: RAEv2 with a frozen local + LingBot-Vision-Large/16 backbone, seven-layer aggregation, and LingBot feature consistency. +- **`raev2_codec_tdown.yaml`** — original MIRA RAEv2 codec with a frozen DINOv3-L/16 + backbone with layer aggregation and a strided-conv bottleneck feeding a ViT video decoder, with + the L1 + LPIPS + DINO-latent-consistency loss weights. +- **`latent_world_model.yaml`** — single-player latent world model: a frozen codec (loaded from + `codec_checkpoint`) plus an action-conditioned flow-matching diffusion transformer over the + codec's latent grid. +- **`bihub_world_1b.yaml`** — current formal model: MIRA's released 1B backbone geometry (2048 + width, 16 blocks, 16 query and 4 KV heads) plus the three-view Hub and shared two-arm + state/instruction encoder, totaling 1.397B trainable parameters. +- **`bihub_world_5b.yaml`** — archived 5.272B predecessor retained for reproducibility only. +- **`bihub_world_smoke.yaml`** — structurally isomorphic small BiHub used only for pipeline tests. +- **`multi_wrapper_world_model.yaml`** — multiplayer world model: an inner `LatentWorldModel` that + processes `n_players` per-player clips tiled into one vertically-stacked frame. A single-player + checkpoint warm-starts into it via `run.finetune_from`. +- **`latent_world_model/1b.yaml`** — the 1B-parameter transformer size (hidden dim, heads, layers), + selected by the package-override `latent_world_model@architecture.config: 1b`. + +## `dataset/` and `actions/` + +`dataset/robotwin2.yaml` streams aligned head/left/right JPEG observations directly from the +downloaded RoboTwin zip/HDF5 episodes. It points at generated train/validation JSONL manifests and +supports task, robot, and clean/randomized filtering. `actions/none.yaml` supplies empty aligned +action tensors because codec training is video-only. `scripts/train_robotwin_codec.sh` derives +cached clip-compatible manifests for the fixed 40-frame, 30-to-20 FPS sampling rule before +launching distributed training, so known short or malformed episodes are removed before workers +begin decoding training batches. + +`dataset/rocket_league.yaml` points `train_index`/`test_index` at the local split directories (or +fetches them from the Hub) and sets `n_players` (1 for the codec, overridden to 4 for the +multiplayer world model) and `target_fps`. It pulls in the action vocabulary with +`/actions@actions: rocket_league`. + +`actions/rocket_league.yaml` lists the 9-key release vocabulary (`DEFAULT_RL_KEYS`) and the action +sample rate `target_fps`. + +## Interpolation + +Configs use Hydra/OmegaConf `${...}` interpolation to keep shared values in one place: + +- `actions: ${dataset.actions}` lifts the dataset's action vocabulary to the top level for the + loader. +- the top-level `run.compile` toggle threads into the codec's DINO compilation + (`compile_dino: ${run.compile}`) and into the world-model metrics block (`compile: ${run.compile}`). +- the codec decoder reads encoder values it must match (e.g. `latent_dim: ${..encoder.latent_dim}`, + `bottleneck.stride: ${...encoder.bottleneck.stride}`). + +The world-model architecture size is selected via package-override syntax +(`latent_world_model@architecture.config`). diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v10_h1_50/base.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v10_h1_50/base.yaml new file mode 100644 index 0000000000000000000000000000000000000000..105fa2a451ea869e866cac0c24d93acbdf271b58 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v10_h1_50/base.yaml @@ -0,0 +1,99 @@ +extends: ../action_v6/base.yaml + +experiment: + name: robotwin_bihub_wam_v10_action + version: v10.0-action-h1-50 + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v10_action_h1_50 + artifact_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v10 + code_identity: 817aa8c1129d4c5d6eb1ee5bbc43141a534cdf30549557e3001ca556f0412e0d + +artifacts: + world_checkpoint: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v10_h1_50_high_lr/main-checkpoint-20000 + world_checkpoint_sha256: d0d815eacd8d9fd5508b348f9453fb921f8e961d926624ca21ad7777622d5fdc + world_branch: online + world_config: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/mira/configs/world_v10_h1_50/train.yaml + world_config_sha256: 42bbc3b8a5ea2e4186ee709b868592198337ba44cbf4922017cdf38ba2ea1dcf + world_validation_report: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v10_h1_50_high_lr/main-checkpoint-20000/trainer_state.json + world_validation_report_sha256: 85a00f6a10c0c683ced49a32b59e833c450b5fa8590b0a9fa9a1b25d113aecbd + world_selection_report: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v10/world/selected_world_for_action.json + state_encoder_ema: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v10/world/state_encoder_online.safetensors + state_encoder_ema_sha256: 8bca5e9e85d936ca7305a9273356ba6fbb72adc98cd2c6682198b6e9e513e0a4 + qwen_hidden_cache_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v7/qwen_hidden_cache + qwen_hidden_cache_identity: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v7/qwen_hidden_cache/qwen_hidden_cache_identity.json + +data: + history_lengths: [1, 3, 6, 10] + history_probabilities: [0.5, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666] + h1_episode_start_only: true + +predicted_future_cache: + root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v10/predicted_future/d0d815eacd8d9fd5 + identity_file: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v10/predicted_future/d0d815eacd8d9fd5/predicted_future_cache_identity.json + identity_sha256: populated_after_transactional_finalize + train_fraction_per_episode: 0.0 + samples_per_window: 1 + dtype: bfloat16 + shard_rows: 2048 + seed_namespace: action-v10-h1-50-world20k + train_rows_per_stratum_history: 256 + val_rows_per_stratum_history: 16 + +training: + protocol: h1_50_gt10k_pred20k + steps: 30000 + global_batch: 512 + micro_batch_per_gpu: 4 + grad_accumulation: 16 + expected_world_size: 8 + strategy: fsdp2_full_shard + optimizer: adamw + betas: [0.9, 0.95] + eps: 1.0e-8 + peak_lr: 1.0e-4 + min_lr: 1.0e-6 + weight_decay: 0.01 + warmup_steps: 5000 + scheduler: cosine + grad_clip: 1.0 + precision: bfloat16 + flow_compute_dtype: float32 + activation_checkpointing: true + ema_decay: 0.0 + log_every: 20 + light_val_every: 2500 + full_val_every: 5000 + save_every: 5000 + predicted_future_curriculum: + - {start: 0, end: 10000, start_p: 0.0, end_p: 0.0} + - {start: 10000, end: 30000, start_p: 1.0, end_p: 1.0} + +checkpoint: + keep_last_recovery: 2 + preserve_steps: [10000, 15000, 20000, 25000, 30000] + auto_resume: true + resume_from: null + initialize_from_ema: null + initialize_from_online: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v6_action_continue100k/action-checkpoint-74559 + atomic: true + +validation: + enabled: false + fixed_seed: 2026 + light_batches: 16 + full_batches: 16 + save_cases: 6 + quick_enabled: true + quick_every: 2500 + quick_batches: 16 + quick_save_cases: 6 + +logging: + swanlab_enabled: true + swanlab_project: multi-wam + swanlab_experiment_name: RoboTwin-BiHub-WAM-v10-Action-H1-50-GT10k-Pred20k + swanlab_token_file: /public/interns/haocheng/Oranger/project/multi_wam/z_tmp/swanlab_token.txt + +runtime: + phase: training + mode: formal + max_steps: null diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v10_h1_50/smoke_gt.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v10_h1_50/smoke_gt.yaml new file mode 100644 index 0000000000000000000000000000000000000000..844090cf09966319deed849676955b3a609bb78d --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v10_h1_50/smoke_gt.yaml @@ -0,0 +1,11 @@ +extends: base.yaml + +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v10_action_h1_50_smoke + +validation: + quick_enabled: false + +runtime: + mode: gate + max_steps: 2 diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v10_h1_50/train_gt10k.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v10_h1_50/train_gt10k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..921a358c41a3e1d6ee89aea1be149a61778c3bcc --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v10_h1_50/train_gt10k.yaml @@ -0,0 +1,7 @@ +extends: base.yaml + +validation: + quick_enabled: false + +runtime: + max_steps: 10000 diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v10_h1_50/train_pred10k_from4139.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v10_h1_50/train_pred10k_from4139.yaml new file mode 100644 index 0000000000000000000000000000000000000000..99f4e998dc052d7de1a4b077b12c7a7b97bd6b0e --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v10_h1_50/train_pred10k_from4139.yaml @@ -0,0 +1,20 @@ +extends: base.yaml + +training: + steps: 14139 + predicted_future_curriculum: + - {start: 0, end: 4139, start_p: 0.0, end_p: 0.0} + - {start: 4139, end: 14139, start_p: 1.0, end_p: 1.0} + +checkpoint: + preserve_steps: [4139, 6639, 9139, 11639, 14139] + resume_from: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v10_action_h1_50/action-checkpoint-4139 + +validation: + quick_enabled: true + quick_every: 2500 + quick_batches: 16 + quick_save_cases: 6 + +runtime: + max_steps: null diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v10_h1_50/train_pred20k.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v10_h1_50/train_pred20k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..785714de1723cb5408fc438bf959701fecee8427 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v10_h1_50/train_pred20k.yaml @@ -0,0 +1 @@ +extends: base.yaml diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v11_pred8k/base.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v11_pred8k/base.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2f604d3b94cd5bd075d19b9ce48a7e648439c393 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v11_pred8k/base.yaml @@ -0,0 +1,92 @@ +extends: ../action_v10_h1_50/base.yaml + +experiment: + name: robotwin_bihub_wam_v11_action + version: v11.0-action-h1-50-pred8k + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v11_action_pred8k + artifact_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v11 + code_identity: 5e0ee9797dbf4e8905844dc5642b331bb23382b830594e5c70fccd23a2ebea04 + +artifacts: + world_checkpoint: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v11_continue30k_liftpot/main-checkpoint-50000 + world_checkpoint_sha256: a2ba64cfa0ec06306ab2ff47525751fbe2c9b6f62f008c0485aafef50bcc2ea9 + world_branch: online + world_config: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/mira/configs/world_v11_continue30k/train.yaml + world_config_sha256: 42bbc3b8a5ea2e4186ee709b868592198337ba44cbf4922017cdf38ba2ea1dcf + world_validation_report: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v11_continue30k_liftpot/main-checkpoint-50000/trainer_state.json + world_validation_report_sha256: e95d4f84e221c0c78ce484d817c8084b91c5cd32ca05ad06adb4a5603a0d4fb4 + world_selection_report: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v11/world/selected_world_for_action.json + state_encoder_ema: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v11/world/state_encoder_online.safetensors + state_encoder_ema_sha256: 948ad08e1af55abdd11bdc2cc36e416ae299bb99fecce2395f1fc19bef0ad35e + supplemental_case_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/mira/configs/action_v11_pred8k/supplemental_lift_pot_case.json + +predicted_future_cache: + root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v11/predicted_future/a2ba64cfa0ec0630 + identity_file: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v11/predicted_future/a2ba64cfa0ec0630/predicted_future_cache_identity.json + identity_sha256: populated_after_transactional_finalize + train_fraction_per_episode: 0.0 + samples_per_window: 1 + dtype: bfloat16 + shard_rows: 2048 + seed_namespace: action-v11-h1-50-world50k-pred8k + train_rows_per_stratum_history: 128 + val_rows_per_stratum_history: 16 + +training: + protocol: h1_50_pred8k_world_v11 + steps: 8000 + global_batch: 512 + micro_batch_per_gpu: 4 + grad_accumulation: 16 + expected_world_size: 8 + strategy: fsdp2_full_shard + optimizer: adamw + betas: [0.9, 0.95] + eps: 1.0e-8 + peak_lr: 3.0e-5 + min_lr: 1.0e-6 + weight_decay: 0.01 + warmup_steps: 500 + scheduler: cosine + grad_clip: 1.0 + precision: bfloat16 + flow_compute_dtype: float32 + activation_checkpointing: true + ema_decay: 0.0 + log_every: 20 + light_val_every: 2000 + full_val_every: 4000 + save_every: 2000 + predicted_future_curriculum: + - {start: 0, end: 8000, start_p: 1.0, end_p: 1.0} + +checkpoint: + keep_last_recovery: 2 + preserve_steps: [2000, 4000, 6000, 8000] + auto_resume: true + resume_from: null + initialize_from_ema: null + initialize_from_online: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v10_action_h1_50/action-checkpoint-12452 + atomic: true + +validation: + enabled: false + fixed_seed: 2026 + light_batches: 8 + full_batches: 8 + save_cases: 6 + quick_enabled: true + quick_every: 2000 + quick_batches: 8 + quick_save_cases: 6 + +logging: + swanlab_enabled: true + swanlab_project: multi-wam + swanlab_experiment_name: RoboTwin-BiHub-WAM-v11-Action-Pred8k-World50k-LiftPot + swanlab_token_file: /public/interns/haocheng/Oranger/project/multi_wam/z_tmp/swanlab_token.txt + +runtime: + phase: training + mode: formal + max_steps: null diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v11_pred8k/smoke.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v11_pred8k/smoke.yaml new file mode 100644 index 0000000000000000000000000000000000000000..585920502ea8234295045b4dfd9f3d5afda3748d --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v11_pred8k/smoke.yaml @@ -0,0 +1,7 @@ +extends: base.yaml + +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v11_action_pred8k_smoke + +runtime: + max_steps: 2 diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v11_pred8k/supplemental_lift_pot_case.json b/release-20261107/source/workspace_joint/mira/configs/action_v11_pred8k/supplemental_lift_pot_case.json new file mode 100644 index 0000000000000000000000000000000000000000..63c14ad4bdf7ac50fc0405455a816375225d5cba --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v11_pred8k/supplemental_lift_pot_case.json @@ -0,0 +1,37 @@ +{ + "format_version": 1, + "contract": "robotwin-lift-pot-eval-evidence-to-expert-action-supervision-v1", + "reason": "The selected eval rollout failed but contains only rendered MP4 frames. It has no synchronized three-view latent stream or expert action targets, so it is retained as failure evidence while the same RoboTwin task's formal clean expert episode supplies state/action supervision.", + "eval_evidence": { + "root": "../vendor/RoboTwin-official-eval/eval_result/lift_pot", + "policy": "robotwin_bihub_wam_v10_world20k_action10k_online", + "instruction_type": "unseen", + "success_rate": 0.0, + "episode0_video_sha256": "f1b7add26860ee24bbf1c99b7126dbfb23fe5a2732dedbcb353c1d148cde98aa", + "episode1_video_sha256": "794db501b94986eb208ab17ce40f43bc8eac6c447ac0275f7200d8a54fc4d537" + }, + "sample": { + "split": "train", + "task": "lift_pot", + "domain": "clean", + "episode": 0, + "episode_sha256": "0189773017ecb95c0037b447a356e4645c370b1320a630c7b1264423fbaa14c7", + "base_global": 339046, + "expanded_index": 1356184, + "latent_start": 0, + "history_length": 1, + "current_latent": 0, + "state_valid_steps": 2, + "action_start_20hz": 1, + "action_horizon": 20, + "future_source": "world_v11_step50000_predicted" + }, + "replay": { + "replacement_global_slot": 0, + "rows_per_global_batch": 1, + "global_batch": 512, + "global_sample_fraction": 0.001953125, + "expected_exposures_over_8000_steps": 8000, + "preserves_h1_50_mix": true + } +} diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v11_pred8k/train.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v11_pred8k/train.yaml new file mode 100644 index 0000000000000000000000000000000000000000..785714de1723cb5408fc438bf959701fecee8427 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v11_pred8k/train.yaml @@ -0,0 +1 @@ +extends: base.yaml diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v12_epoch/base.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v12_epoch/base.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3adab23968403d7fa5f224742b0bb882f04163a4 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v12_epoch/base.yaml @@ -0,0 +1,106 @@ +extends: ../action_v6/base.yaml + +experiment: + name: robotwin_bihub_wam_v12_action + version: v12.0-action-eval-aligned-epoch + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v12_action_eval_aligned_epoch + artifact_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v12 + code_identity: 449a5671fa2d68ab1941314fa6613e1f48f7d08599367801c212d10ec776e7ad + +artifacts: + world_checkpoint: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v12_largebatch_remaining/main-checkpoint-25066 + world_checkpoint_sha256: 4c943450900312010140241b300b44a0249551c177cdb7f068a998fefabb6530 + world_branch: online + world_config: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/mira/configs/world_v12_largebatch_remaining/train.yaml + world_config_sha256: 42bbc3b8a5ea2e4186ee709b868592198337ba44cbf4922017cdf38ba2ea1dcf + world_validation_report: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v12_largebatch_remaining/main-checkpoint-25066/trainer_state.json + world_validation_report_sha256: 708bd9c254a78b710feba814bb65718730bb49aa288a56e7c8d68cfd68840ca7 + world_selection_report: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v12/world/selected_world_for_action.json + state_encoder_ema: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v12/world/state_encoder_online.safetensors + state_encoder_ema_sha256: b9e015d02a0de20c5c84dd80dddc1e58832ecf1b21d46943035943128e118679 + qwen_hidden_cache_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v7/qwen_hidden_cache + qwen_hidden_cache_identity: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v7/qwen_hidden_cache/qwen_hidden_cache_identity.json + supplemental_case_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/mira/configs/action_v11_pred8k/supplemental_lift_pot_case.json + +data: + history_lengths: [1, 3, 6, 10] + history_probabilities: [0.25, 0.25, 0.25, 0.25] + h1_episode_start_only: true + episode_start_only_histories: [1, 3, 6] + h10_all_legal_starts: true + epoch_h10_windows: 1472828 + num_workers: 2 + episode_cache_size: 8 + +predicted_future_cache: + root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v12/predicted_future/4c94345090031201 + identity_file: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v12/predicted_future/4c94345090031201/predicted_future_cache_identity.json + identity_sha256: populated_after_transactional_finalize + train_fraction_per_episode: 1.0 + samples_per_window: 1 + dtype: bfloat16 + shard_rows: 8192 + seed_namespace: action-v12-eval-aligned-world25066-full + train_rows_per_stratum_history: 0 + val_rows_per_stratum_history: 0 + full_eval_aligned: true + max_rows_per_history: 0 + +training: + protocol: eval_aligned_epoch_world_v12 + steps: 5754 + global_batch: 1024 + micro_batch_per_gpu: 128 + grad_accumulation: 1 + expected_world_size: 8 + strategy: fsdp2_full_shard + optimizer: adamw + betas: [0.9, 0.95] + eps: 1.0e-8 + peak_lr: 1.0e-4 + min_lr: 1.0e-6 + weight_decay: 0.01 + warmup_steps: 300 + scheduler: cosine + grad_clip: 1.0 + precision: bfloat16 + flow_compute_dtype: float32 + activation_checkpointing: true + ema_decay: 0.0 + log_every: 20 + light_val_every: 1250 + full_val_every: 5754 + save_every: 1250 + predicted_future_curriculum: + - {start: 0, end: 5754, start_p: 1.0, end_p: 1.0} + +checkpoint: + keep_last_recovery: 2 + preserve_steps: [1250, 2500, 3750, 5000, 5754] + auto_resume: true + resume_from: null + initialize_from_ema: null + initialize_from_online: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v11_action_pred8k/action-checkpoint-8000 + atomic: true + +validation: + enabled: false + fixed_seed: 2026 + light_batches: 8 + full_batches: 8 + save_cases: 6 + quick_enabled: true + quick_every: 1250 + quick_batches: 8 + quick_save_cases: 6 + +logging: + swanlab_enabled: true + swanlab_project: multi-wam + swanlab_experiment_name: RoboTwin-BiHub-WAM-v12-Action-EvalAligned-OneEpoch + swanlab_token_file: /public/interns/haocheng/Oranger/project/multi_wam/z_tmp/swanlab_token.txt + +runtime: + phase: training + mode: formal + max_steps: null diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v12_epoch/cache_smoke96.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v12_epoch/cache_smoke96.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6d1bb85f1ee5fb6c0ba4068b0872058386610a09 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v12_epoch/cache_smoke96.yaml @@ -0,0 +1,14 @@ +extends: base.yaml + +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v12_action_eval_aligned_epoch_cache_smoke96 + artifact_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v12/cache_smoke96 + +predicted_future_cache: + root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v12/cache_smoke96/predicted_future/4c94345090031201 + identity_file: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v12/cache_smoke96/predicted_future/4c94345090031201/predicted_future_cache_identity.json + max_rows_per_history: 96 + +runtime: + mode: gate + max_steps: 2 diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v12_epoch/smoke.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v12_epoch/smoke.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2c6ecf2a993ed56e3620ee3dfb331f72be02c75b --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v12_epoch/smoke.yaml @@ -0,0 +1,18 @@ +extends: base.yaml + +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v12_action_eval_aligned_epoch_smoke_bs128 + artifact_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v12/smoke + +predicted_future_cache: + root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v12/smoke/predicted_future/4c94345090031201 + identity_file: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v12/smoke/predicted_future/4c94345090031201/predicted_future_cache_identity.json + max_rows_per_history: 64 + +validation: + quick_batches: 2 + quick_save_cases: 2 + +runtime: + mode: gate + max_steps: 2 diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v12_epoch/train.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v12_epoch/train.yaml new file mode 100644 index 0000000000000000000000000000000000000000..785714de1723cb5408fc438bf959701fecee8427 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v12_epoch/train.yaml @@ -0,0 +1 @@ +extends: base.yaml diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v13_continue4epoch/base.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v13_continue4epoch/base.yaml new file mode 100644 index 0000000000000000000000000000000000000000..60bc731cab72f2d894d03d096d85bff7641fd806 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v13_continue4epoch/base.yaml @@ -0,0 +1,41 @@ +extends: ../action_v12_epoch/base.yaml + +experiment: + name: robotwin_bihub_wam_v13_action + version: v13.0-action-eval-aligned-continue4epoch + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v13_action_eval_aligned_continue4epoch + artifact_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v13 + code_identity: 380d6b77855843b290698a3567183f0591425f36b5ee98cd530c2177ce712594 + +data: + sampler_step_offset: 5754 + +predicted_future_cache: + identity_sha256: b49582be5475f4c18014fed801fbc5349574e5ce60be01c9506d3557d32f5694 + +training: + protocol: eval_aligned_continue4_world_v12 + steps: 23016 + micro_batch_per_gpu: 128 + grad_accumulation: 1 + activation_checkpoint_blocks: 7 + peak_lr: 5.0e-5 + min_lr: 1.0e-6 + warmup_steps: 1200 + light_val_every: 5754 + full_val_every: 23016 + save_every: 5754 + predicted_future_curriculum: + - {start: 0, end: 23016, start_p: 1.0, end_p: 1.0} + +checkpoint: + preserve_steps: [5754, 11508, 17262, 23016] + resume_from: null + initialize_from_ema: null + initialize_from_online: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v12_action_eval_aligned_epoch/action-checkpoint-5754 + +validation: + quick_every: 5754 + +logging: + swanlab_experiment_name: RoboTwin-BiHub-WAM-v13-Action-EvalAligned-Continue4Epoch diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v13_continue4epoch/perf_smoke.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v13_continue4epoch/perf_smoke.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cd63523f51b0f7469626e6b1063b46d5df35ff6d --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v13_continue4epoch/perf_smoke.yaml @@ -0,0 +1,13 @@ +extends: base.yaml + +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v13_action_eval_aligned_continue4epoch_perf_smoke + artifact_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v13/perf_smoke + +validation: + quick_batches: 2 + quick_save_cases: 2 + +runtime: + mode: gate + max_steps: 2 diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v13_continue4epoch/perf_smoke4.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v13_continue4epoch/perf_smoke4.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3d75c3542379a4d0cceef83d2b070547434e19de --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v13_continue4epoch/perf_smoke4.yaml @@ -0,0 +1,13 @@ +extends: base.yaml + +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v13_action_eval_aligned_continue4epoch_perf_smoke4 + artifact_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v13/perf_smoke4 + +validation: + quick_batches: 2 + quick_save_cases: 2 + +runtime: + mode: gate + max_steps: 2 diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v13_continue4epoch/smoke.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v13_continue4epoch/smoke.yaml new file mode 100644 index 0000000000000000000000000000000000000000..414db32395cf628055d05fb30b7601ba6402b2d6 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v13_continue4epoch/smoke.yaml @@ -0,0 +1,17 @@ +extends: base.yaml + +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v13_action_eval_aligned_continue4epoch_smoke + artifact_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v13/smoke + +validation: + quick_batches: 2 + quick_save_cases: 2 + +training: + micro_batch_per_gpu: 32 + grad_accumulation: 4 + +runtime: + mode: gate + max_steps: 2 diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v13_continue4epoch/train.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v13_continue4epoch/train.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9442950c1c0a8b4053801e2078744932b9e419b4 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v13_continue4epoch/train.yaml @@ -0,0 +1,2 @@ +extends: base.yaml + diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v6/base.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v6/base.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cac8239c1eb7a8b27795388386bd1a6eab1147f3 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v6/base.yaml @@ -0,0 +1,174 @@ +experiment: + name: robotwin_bihub_wam_v6_action + version: v6.0-action + seed: 2026 + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v6_action + artifact_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v6 + code_identity: 641dccaf6ece1b3c65f690220b11c36478da6e74cd5e4dadacaba28f04733ae9 + +artifacts: + codec_checkpoint: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/mira_robotwin_codec/checkpoint-125000/checkpoint.pth + codec_sha256: c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615 + anchor_identity: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/anchor_cache/anchor_cache_identity.json + anchor_identity_sha256: 74823fd7d7a8490c9b57d0c0cb9833222469c0670ca6fa3bd06326e941298826 + world_checkpoint: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v6/main-checkpoint-97314 + world_checkpoint_sha256: 08f4a3687417b2a48133feb0cb4e12c249b0969d8936e1a96b3b887b24b10df3 + world_branch: ema + world_config: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/mira/configs/world_v6/train.yaml + world_config_sha256: 9e5375dc7603f8bd0945dfc9c999a9ed16dd40cc2a340fbaffcdffc43867a24b + world_validation_report: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v6_eval/fixed_evaluation.json + world_validation_report_sha256: 7e5f8ca6be696f8fe28eaef1726493a6892492726cd08c3832b43b369d428e8e + world_selection_report: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v6/world/selected_world_for_action.json + state_encoder_ema: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v6/world/state_encoder_ema.safetensors + state_encoder_ema_sha256: 5b39daab9abe76912ac2e9af77bf8360468542c65bdd1e93b6074d9ee383757d + state_stats: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/datasets/RoboTwin2.0/mira_wam_aloha/dataset_stats.json + state_stats_sha256: 636e4eca955419f1aeaa3df5f3350b0b39da389849f55ca5d79ff45bc6dc11c4 + train_source_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/latent_cache/c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615/manifest_train.jsonl + val_source_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/latent_cache/c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615/manifest_val.jsonl + train_window_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/windows/train.jsonl + train_window_manifest_sha256: f756dcf7a6afe311e2d176550b1accb7a81c07da008ade9e780e3b8d340c5a63 + validation_window_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/windows/val.jsonl + validation_window_manifest_sha256: d3067890991717472fbd4857f022d2a50a58b9b0ff51772c4e64f949c3e695dd + train_window_index: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/windows/train.source_index.i64 + validation_window_index: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/windows/val.source_index.i64 + split_identity: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/windows/summary.json + +data: + tasks: 50 + view_order: [left, global, right] + arm_order: [left, right] + latent_shape: [32, 9, 12] + context_latents: 10 + future_latents: 10 + latent_fps: 10 + state_steps: 20 + action_steps: 20 + action_fps: 20 + state_source_field: joint_action/vector + state_semantics: simulator_drive_target_not_measured_qpos + action_semantics: next_simulator_drive_target_absolute_qpos + action_dim_per_arm: 7 + task_uniform: true + clean_probability: 0.5 + num_workers: 2 + episode_cache_size: 4 + action_stats: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v6/statistics/action_stats.json + action_stats_sha256: 7ba3ffbbab42c49155fde02609fbd10a048b98fc910d2290ca7880f026b9b326 + delta_stats: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v6/statistics/delta_stats.json + delta_stats_sha256: ad8c9e08540333a3fcf2f637b847f63eef70caac5e87ca27473a04b30fd76250 + +world_inference: + trainable: false + sampler: linear_quadratic_euler + steps: 10 + decoder_loaded: false + latent_mean: 0.024823864160431405 + latent_std: 1.9595992324017892 + +predicted_future_cache: + root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v6/predicted_future/08f4a3687417b2a48 + identity_file: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v6/predicted_future/08f4a3687417b2a48/predicted_future_cache_identity.json + identity_sha256: c89ef50a78e6dbda11500aba9b2f9ee3078823fe1f2f3ee432f7d27473ce12f3 + train_fraction_per_episode: 0.20 + samples_per_window: 1 + dtype: bfloat16 + shard_rows: 2048 + seed_namespace: action-pred-v1 + +transition: + width: 1024 + queries_per_view_interval: 4 + qformer_layers: 2 + heads: 16 + head_dim: 64 + ffn_hidden: 4096 + dropout: 0.0 + qk_norm: true + delta_normalization: train_gt_rms_per_view_horizon_channel + topology: sequential_global_gather_local_broadcast + residual_gate_init: 0.1 + +action: + horizon: 20 + width: 1024 + layers: 8 + heads: 16 + head_dim: 64 + ffn_hidden: 4096 + dropout: 0.0 + qk_norm: true + local_weights_shared: true + global_registers: 20 + direct_left_right_attention: false + monotonic_sigma: 0.10 + flow_time_distribution: logit_normal + flow_time_logit_mean: 0.0 + flow_time_logit_std: 1.0 + loss: masked_action_flow_mse_only + sampler: euler + sampling_steps: 10 + cfg_scale: 1.0 + execute_steps: 8 + normalized_action_clip: 5.0 + +training: + protocol: preregistered_100k + steps: 100000 + global_batch: 512 + micro_batch_per_gpu: 4 + grad_accumulation: 16 + expected_world_size: 8 + strategy: fsdp2_full_shard + optimizer: adamw + betas: [0.9, 0.95] + eps: 1.0e-8 + peak_lr: 1.0e-4 + min_lr: 1.0e-6 + weight_decay: 0.01 + warmup_steps: 5000 + scheduler: cosine + grad_clip: 1.0 + precision: bfloat16 + flow_compute_dtype: float32 + activation_checkpointing: true + ema_decay: 0.9999 + log_every: 20 + light_val_every: 2500 + full_val_every: 5000 + save_every: 5000 + predicted_future_curriculum: + - {start: 0, end: 10000, start_p: 0.0, end_p: 0.0} + - {start: 10000, end: 40000, start_p: 0.0, end_p: 0.5} + - {start: 40000, end: 80000, start_p: 0.5, end_p: 0.5} + - {start: 80000, end: 90000, start_p: 0.5, end_p: 0.75} + - {start: 90000, end: 100000, start_p: 0.75, end_p: 0.75} + +checkpoint: + keep_last_recovery: 2 + preserve_steps: [50000, 75000, 100000] + auto_resume: true + resume_from: null + atomic: true + +validation: + enabled: true + fixed_seed: 2026 + light_batches: 16 + # ceil(29,668 validation windows / (8 ranks * 4 samples/rank)) + full_batches: 928 + save_cases: 8 + quick_enabled: false + quick_every: 5000 + quick_batches: 16 + quick_save_cases: 4 + +logging: + swanlab_enabled: true + swanlab_project: multi-wam + swanlab_experiment_name: RoboTwin-BiHub-WAM-v6-Action + swanlab_token_file: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/z_oranger/token.txt + +runtime: + phase: training + mode: formal + max_steps: null diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v6/cache.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v6/cache.yaml new file mode 100644 index 0000000000000000000000000000000000000000..365b08532a2fa4958bede9de6ab1225647bea972 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v6/cache.yaml @@ -0,0 +1,4 @@ +extends: base.yaml +runtime: + phase: cache + mode: gate diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v6/canary.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v6/canary.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e28cbabe41eff8912488cb35b85fe92901010606 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v6/canary.yaml @@ -0,0 +1,5 @@ +extends: base.yaml +runtime: + phase: canary + mode: gate + max_steps: 500 diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v6/canary_corrective_v7_round0.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v6/canary_corrective_v7_round0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9ae0bfbd516c7ef100317f8de145b9f0c7c2c877 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v6/canary_corrective_v7_round0.yaml @@ -0,0 +1,13 @@ +extends: train_corrective_v7_round0.yaml + +corrective: + exact_cold_train_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v7/exact_cold_canary100/train/manifest.jsonl + exact_cold_val_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v7/exact_cold_canary/val/manifest.jsonl + +logging: + swanlab_experiment_name: RoboTwin-BiHub-WAM-v7-Action-Corrective-Canary + +runtime: + phase: canary + mode: gate + max_steps: 5 diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v6/overfit64.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v6/overfit64.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2990c45dc437beb13a7094de60e647ff105e2e0f --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v6/overfit64.yaml @@ -0,0 +1,5 @@ +extends: base.yaml +runtime: + phase: overfit64 + mode: gate + max_steps: 3000 diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v6/train.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v6/train.yaml new file mode 100644 index 0000000000000000000000000000000000000000..785714de1723cb5408fc438bf959701fecee8427 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v6/train.yaml @@ -0,0 +1 @@ +extends: base.yaml diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v6/train_compressed22k.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v6/train_compressed22k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8cff3f56b0ae601a86dea0184fcdf8506582e403 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v6/train_compressed22k.yaml @@ -0,0 +1,26 @@ +extends: base.yaml + +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v6_action_compressed22k + +training: + protocol: compressed_22k + steps: 22000 + # Periodic saves are disabled; the audited stage boundaries below trigger saves. + save_every: 1000000 + predicted_future_curriculum: + - {start: 0, end: 10000, start_p: 0.0, end_p: 0.0} + - {start: 10000, end: 13000, start_p: 0.0, end_p: 0.5} + - {start: 13000, end: 16000, start_p: 0.5, end_p: 0.5} + - {start: 16000, end: 19000, start_p: 0.5, end_p: 0.75} + - {start: 19000, end: 22000, start_p: 0.75, end_p: 0.75} + +checkpoint: + preserve_steps: [10000, 13000, 16000, 19000, 22000] + resume_from: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v6_action/action-checkpoint-10000 + +validation: + enabled: false + +logging: + swanlab_experiment_name: RoboTwin-BiHub-WAM-v6-Action-Compressed22k diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v6/train_continue100k.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v6/train_continue100k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2005b2952154ce7fe528393cefda9c37fa8ec4e5 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v6/train_continue100k.yaml @@ -0,0 +1,40 @@ +extends: base.yaml + +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v6_action_continue100k + +training: + protocol: continuation_100k + steps: 100000 + # Preserve the loaded 1e-6 LR for the first resumed update, rewarm to 3e-5 + # over 2k steps, then cosine-decay to 1e-6 at step 100k. + continuation_resume_step: 22000 + continuation_rewarm_steps: 2000 + continuation_peak_lr: 3.0e-5 + light_val_every: 1000000 + full_val_every: 1000000 + save_every: 5000 + predicted_future_curriculum: + - {start: 0, end: 10000, start_p: 0.0, end_p: 0.0} + - {start: 10000, end: 13000, start_p: 0.0, end_p: 0.5} + - {start: 13000, end: 16000, start_p: 0.5, end_p: 0.5} + - {start: 16000, end: 19000, start_p: 0.5, end_p: 0.75} + - {start: 19000, end: 22000, start_p: 0.75, end_p: 0.75} + - {start: 22000, end: 100000, start_p: 0.75, end_p: 0.75} + +checkpoint: + preserve_steps: [30000, 40000, 50000, 60000, 75000, 90000, 100000] + resume_from: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v6_action_compressed22k/action-checkpoint-22000 + +validation: + # Full 29,668-window validation is intentionally kept out of the training + # loop. Every 5k steps, evaluate EMA on a fixed 512-window trajectory panel. + enabled: false + quick_enabled: true + quick_every: 5000 + quick_batches: 16 + quick_save_cases: 4 + +logging: + swanlab_experiment_name: RoboTwin-BiHub-WAM-v6-Action-Continue100k + swanlab_token_file: /public/interns/haocheng/Oranger/project/multi_wam/z_tmp/swanlab_token.txt diff --git a/release-20261107/source/workspace_joint/mira/configs/action_v6/train_corrective_v7_round0.yaml b/release-20261107/source/workspace_joint/mira/configs/action_v6/train_corrective_v7_round0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dfef575edbc93c86f8f1ceeb768a96276d48cb38 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/action_v6/train_corrective_v7_round0.yaml @@ -0,0 +1,57 @@ +extends: base.yaml + +experiment: + name: robotwin_bihub_wam_v7_action + version: v7.0-action-corrective + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v7_action_corrective_round0 + artifact_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v7 + code_identity: 241f2098deebc0cf7d3b5675854bde7bef1985d789f23132d3c5c1846d5cd1be + +action: + # Keep the whole 20-step imitation target primary while adding a deployment- + # prefix/gripper-aware half-objective. + loss: masked_action_flow_mse_execute8_gripper_weighted + +training: + protocol: corrective_v7_round0 + steps: 3000 + peak_lr: 1.0e-5 + min_lr: 1.0e-6 + warmup_steps: 500 + ema_decay: 0.9995 + light_val_every: 1000000 + full_val_every: 1000000 + save_every: 1000 + predicted_future_curriculum: + - {start: 0, end: 3000, start_p: 0.75, end_p: 0.75} + +checkpoint: + preserve_steps: [1000, 2000, 3000] + resume_from: null + initialize_from_ema: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_wam_v6_action_continue100k/action-checkpoint-60000 + +validation: + enabled: false + quick_enabled: true + quick_every: 1000 + quick_batches: 16 + quick_save_cases: 4 + +corrective: + exact_cold_train_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v7/exact_cold/train/manifest.jsonl + exact_cold_val_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v7/exact_cold/val/manifest.jsonl + critical_event_index: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v7/critical_events/train.i64 + critical_event_identity: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_v7/critical_events/train.json + regular_expert_share: 0.5 + exact_cold_share: 0.4 + critical_event_share: 0.1 + regular_predicted_probability: 0.75 + +logging: + swanlab_experiment_name: RoboTwin-BiHub-WAM-v7-Action-Corrective-Round0 + swanlab_token_file: /public/interns/haocheng/Oranger/project/multi_wam/z_tmp/swanlab_token.txt + +runtime: + phase: training + mode: formal + max_steps: null diff --git a/release-20261107/source/workspace_joint/mira/configs/actions/.gitkeep b/release-20261107/source/workspace_joint/mira/configs/actions/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/release-20261107/source/workspace_joint/mira/configs/actions/none.yaml b/release-20261107/source/workspace_joint/mira/configs/actions/none.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5af5c244dafd2fcfcb976c60e9f490799ba8ac10 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/actions/none.yaml @@ -0,0 +1,3 @@ +# Codec-only datasets do not need actions. Empty, aligned tensors preserve the shared batch API. +target_fps: 20 +valid_keys: [] diff --git a/release-20261107/source/workspace_joint/mira/configs/actions/rocket_league.yaml b/release-20261107/source/workspace_joint/mira/configs/actions/rocket_league.yaml new file mode 100644 index 0000000000000000000000000000000000000000..927de54319f449bf657c96a636e02df1ea286086 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/actions/rocket_league.yaml @@ -0,0 +1,17 @@ +# Rocket League keybinds — the 9-key release vocabulary (DEFAULT_RL_KEYS). +# `target_fps` is the action sample rate. The world model runs frames at `video.fps` (20) and +# actions at this rate (20), i.e. one action per video frame (the released default); the encoder +# pools them per latent frame (action_temporal_downsampling = target_fps * codec_temporal_downsampling +# // video.fps = 2 for the single-player td=2 codec, 1 for the multiplayer td=1 codec). Setting this +# above `video.fps` decouples the two rates (e.g. 40 -> 2 actions/video-frame). +target_fps: 20 +valid_keys: + - W # throttle / forward (ground) / pitch down (air) + - A # steer left (ground) / yaw left (air) + - S # reverse / brake (ground) / pitch up (air) + - D # steer right (ground) / yaw right (air) + - Q # air roll left + - E # air roll right + - Space # ball cam (toggle) + - LShiftKey # powerslide (handbrake; doubles as air roll) + - LControlKey # no default RL binding (player-bound) diff --git a/release-20261107/source/workspace_joint/mira/configs/dataset/.gitkeep b/release-20261107/source/workspace_joint/mira/configs/dataset/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/release-20261107/source/workspace_joint/mira/configs/dataset/robotwin2.yaml b/release-20261107/source/workspace_joint/mira/configs/dataset/robotwin2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..74a05f81642ef26184bbccb955416fc56a3755a3 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/dataset/robotwin2.yaml @@ -0,0 +1,20 @@ +# RoboTwin 2.0 codec data, streamed directly from per-task zip archives. +defaults: + - /actions@actions: none + - _self_ + +loader: robotwin2 +root: ${oc.env:ROBOTWIN_DATASET_ROOT,../datasets/RoboTwin2.0} +manifest_dir: ${.root}/mira_manifests +train_manifest: ${.manifest_dir}/train.jsonl +val_manifest: ${.manifest_dir}/val.jsonl + +# Native episodes are 30 FPS. The loader selects aligned source frames for the codec's 20 FPS clips. +source_fps: 30 +target_fps: 20 +n_players: 1 + +# Empty lists mean all 50 tasks, all available robots, and both clean/randomized domains. +tasks: [] +robots: [] +domains: [] diff --git a/release-20261107/source/workspace_joint/mira/configs/dataset/robotwin_wam.yaml b/release-20261107/source/workspace_joint/mira/configs/dataset/robotwin_wam.yaml new file mode 100644 index 0000000000000000000000000000000000000000..30a755532433a5a80822bf512abf157348b738a9 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/dataset/robotwin_wam.yaml @@ -0,0 +1,12 @@ +root: ${oc.env:ROBOTWIN_DATASET_ROOT,../datasets/RoboTwin2.0} +raw_manifest_dir: ${oc.env:MIRA_WAM_RAW_MANIFEST_DIR,../datasets/RoboTwin2.0/mira_wam_aloha} +train_manifest: ${oc.env:MIRA_WAM_TRAIN_MANIFEST,../artifacts/latent_cache/UNRESOLVED/manifest_train.jsonl} +val_manifest: ${oc.env:MIRA_WAM_VAL_MANIFEST,../artifacts/latent_cache/UNRESOLVED/manifest_val.jsonl} +dataset_stats: ${.raw_manifest_dir}/dataset_stats.json +embodiment: aloha-agilex +view_order: [left, global, right] +state_semantics: simulator_drive_target_not_measured_qpos +source_fps: 30 +video_fps: 20 +latent_fps: 10 +clean_probability: 0.5 diff --git a/release-20261107/source/workspace_joint/mira/configs/dataset/robotwin_wam_smoke.yaml b/release-20261107/source/workspace_joint/mira/configs/dataset/robotwin_wam_smoke.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6c7d4fdda61d6cc39b6722b8a072c3f82707b266 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/dataset/robotwin_wam_smoke.yaml @@ -0,0 +1,12 @@ +root: ${oc.env:ROBOTWIN_DATASET_ROOT,../datasets/RoboTwin2.0} +raw_manifest_dir: ${oc.env:MIRA_WAM_RAW_MANIFEST_DIR,../artifacts/wam_smoke/raw_manifest} +train_manifest: ${oc.env:MIRA_WAM_TRAIN_MANIFEST,../artifacts/wam_smoke/cache_manifest_train.jsonl} +val_manifest: ${oc.env:MIRA_WAM_VAL_MANIFEST,../artifacts/wam_smoke/cache_manifest_val.jsonl} +dataset_stats: ${.raw_manifest_dir}/dataset_stats.json +embodiment: aloha-agilex +view_order: [left, global, right] +state_semantics: simulator_drive_target_not_measured_qpos +source_fps: 30 +video_fps: 20 +latent_fps: 10 +clean_probability: 0.5 diff --git a/release-20261107/source/workspace_joint/mira/configs/dataset/rocket_league.yaml b/release-20261107/source/workspace_joint/mira/configs/dataset/rocket_league.yaml new file mode 100644 index 0000000000000000000000000000000000000000..714ca481882f102c7f482a73fd94743afdad18e7 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/dataset/rocket_league.yaml @@ -0,0 +1,22 @@ +# Rocket League dataset. Single-player by default (n_players=1) for the codec; the multiplayer +# world model overrides n_players=4. The data ships separate train/ and test/ splits; point +# train_index/test_index at the local split directories (each holding index.json plus the shards +# it references, flat or in numbered subfolders) +# or fetch them from the Hub via `mira.data.RocketScienceDataset.from_hub(split=...)`. +defaults: + - /actions@actions: rocket_league + - _self_ + +# Local paths to the split directories (or their index.json). Override on the command line, e.g. +# `dataset.train_index=/path/to/train dataset.test_index=/path/to/test`. +train_index: null +test_index: null + +n_players: 1 # 1 for the codec; 4 for the multiplayer world model. +# Default frame rate clips are downsampled to. The training entrypoints override the frame rate +# from the model config (codec: `encoder.video.fps`=20; world model: `video.fps`=20), and the +# world model samples actions at `actions.target_fps` (20). With both rates at 20 this is one +# action per video frame (the released default); the action rate can be decoupled via the knob. +target_fps: 20 +frame_size: null # native decoded size; set to [H, W] to resize decoded frames. +exclude_replays: false # set true for evaluation (drops clips overlapping a goal-replay span). diff --git a/release-20261107/source/workspace_joint/mira/configs/eval_action_head_offline.yaml b/release-20261107/source/workspace_joint/mira/configs/eval_action_head_offline.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ea3f24386407d04368ae8fac12fcb02d69b10f04 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/eval_action_head_offline.yaml @@ -0,0 +1,25 @@ +seed: 2026 +checkpoint: ${oc.env:MIRA_ACTION_EVAL_CHECKPOINT,../outputs/robotwin_joint_action_flow/checkpoint-100000} +branch: ema +output_dir: ${oc.env:MIRA_ACTION_EVAL_OUTPUT,../outputs/robotwin_joint_action_flow_offline_eval} +cases: 256 +action_steps: 10 +visualization_cases: 4 + +distributed: + expected_world_size: 2 + +data: + val_manifest: ${oc.env:MIRA_ACTION_VAL_MANIFEST,../artifacts/action_stage/manifests/val.jsonl} + state_stats: ${oc.env:MIRA_ACTION_STATE_STATS,../datasets/RoboTwin2.0/mira_wam_aloha/dataset_stats.json} + action_stats: ${oc.env:MIRA_ACTION_STATS,../artifacts/action_stage/manifests/action_stats.json} + val_future_cache: ${oc.env:MIRA_ACTION_VAL_FUTURE,../artifacts/action_stage/future_pred10/val} + latent_mean: 0.024823864160431405 + latent_std: 1.9595992324017892 + +hydra: + run: + dir: ${output_dir} + output_subdir: .hydra + job: + chdir: false diff --git a/release-20261107/source/workspace_joint/mira/configs/eval_world_model.yaml b/release-20261107/source/workspace_joint/mira/configs/eval_world_model.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fe15ccf632b86fbdd632b62d32a01b8a2f745934 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/eval_world_model.yaml @@ -0,0 +1,30 @@ +# Offline world-model evaluation entry point: the world-model metrics block only (DINO/latent drift +# + Frechet DINO/Inception curves + per-frame PSNR/LPIPS/SSIM). The checkpoint carries its own model +# and dataset config, so this only configures how the eval is run. Video-only (no audio metrics). +defaults: + - _self_ + +world_model_metrics: + _target_: mira.training.metrics.world_model_metrics.WorldModelMetricsConfig + _convert_: all # pass plain dicts to the Pydantic config, not OmegaConf nodes + # Filled in at eval time (path or W&B URL to the checkpoint, and an output directory). + checkpoint: null + output_dir: null + # Inference (rollout) settings; fields not listed keep their WorldModelInferenceConfig defaults. + inference: + schedule_type: linear + noise_level: 0.0 + num_samples: 2048 + per_device_batch_size: 1 + # 4 s eval on the shipped 4 s (80-frame @ 20 fps) chunks. With temporal_downsampling=2 the eval + # clip is n_context_frames + num_unrolled_frames*2 = 38 + 20*2 = 78 frames (<= 80, even so it + # encodes cleanly): 38 context frames (~2 s) then a 20-latent-frame (~2 s) rollout. 38 is a + # multiple of 2 and stays under both shipped model windows (video.timesteps 40 single / 80 multi). + n_context_frames: 38 + num_unrolled_frames: 20 + drift_metric_frames: 20 + fdd_slice_frames: 10 # per-slice Frechet width -> 20/10 = 2 slices (at 10, 20 latent frames) + eval_temporal_downsampling: null + compile: false + dino_max_chunk_size: 128 # max frames per DINO forward pass, reduces peak memory + num_viz_samples: 8 # how many eval samples to visualize (logged to W&B) diff --git a/release-20261107/source/workspace_joint/mira/configs/minieval/heldout_v1.json b/release-20261107/source/workspace_joint/mira/configs/minieval/heldout_v1.json new file mode 100644 index 0000000000000000000000000000000000000000..d4aa152dfdc5d79c3d570bcaf7ce7c31c35a3089 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/minieval/heldout_v1.json @@ -0,0 +1,31 @@ +{ + "name": "heldout_v1", + "purpose": "Checkpoint and ablation selection on held-out simulator seeds. Never use the formal test seeds (100000+) for selection.", + "seed_start": 300000, + "test_num": 30, + "strict_eval": true, + "domains": ["demo_clean", "demo_randomized"], + "tasks": { + "gap": [ + "blocks_ranking_rgb", + "blocks_ranking_size", + "hanging_mug", + "handover_block", + "move_stapler_pad", + "open_microwave", + "place_empty_cup", + "stack_blocks_three", + "stamp_seal", + "turn_switch" + ], + "control": [ + "dump_bin_bigbin", + "open_laptop", + "place_burger_fries", + "place_object_stand", + "place_shoe", + "press_stapler" + ] + }, + "selection_note": "Gap tasks have the largest shortfall of step 6563 against published Fast-WAM per-task results; controls score 79-95% and detect regressions. Seeds 300000+ are disjoint from the formal 100000+ range, so selection does not touch reported test episodes." +} diff --git a/release-20261107/source/workspace_joint/mira/configs/model/.gitkeep b/release-20261107/source/workspace_joint/mira/configs/model/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/release-20261107/source/workspace_joint/mira/configs/model/action_joint_flow.yaml b/release-20261107/source/workspace_joint/mira/configs/model/action_joint_flow.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3bac337860c1a26bc3ec8f02ec4f0bb8706bd222 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/model/action_joint_flow.yaml @@ -0,0 +1,22 @@ +latent_dim: 32 +text_dim: 4096 +state_dim: 512 +hidden_dim: 1024 +layers: 16 +heads: 16 +kv_heads: 16 +ffn_dim: 4096 +action_dim: 14 +horizon: 20 +current_height: 9 +current_width: 12 +future_steps: 10 +future_height: 3 +future_width: 4 +future_drop_prob: 0.10 +activation_checkpointing: true +noise_repeats: 2 +inference_steps: 10 +flow_beta_alpha: 1.5 +flow_beta_beta: 1.0 +flow_time_scale: 0.999 diff --git a/release-20261107/source/workspace_joint/mira/configs/model/bihub_world_1b.yaml b/release-20261107/source/workspace_joint/mira/configs/model/bihub_world_1b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1d492de777f55028826ba4efd9af256ffcd8a036 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/model/bihub_world_1b.yaml @@ -0,0 +1,27 @@ +# MIRA's released 1B backbone geometry, adapted to the three-view BiHub conditioning stack. +# The added text/state/Hub modules make the exact trainable total about 1.397B. +latent_dim: 32 +latent_height: 9 +latent_width: 12 +context_latents: 10 +future_latents: 10 +text_dim: 4096 +hidden_dim: 2048 +layers: 16 +heads: 16 +kv_heads: 4 +temporal_layers: [0, 4, 8, 12, 15] +attention_gating: true +qk_norm: layernorm +register_tokens: 0 +activation_checkpointing: true +clean_past: false +direct_left_right: false +latent_mean: 0.024823864160431405 +latent_std: 1.9595992324017892 +state: + hidden_dim: 512 + layers: 2 + heads: 8 + text_kv_heads: 4 + use_action_history: false diff --git a/release-20261107/source/workspace_joint/mira/configs/model/bihub_world_5b.yaml b/release-20261107/source/workspace_joint/mira/configs/model/bihub_world_5b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ad97e6519f29919e4326cc467b15185110becd07 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/model/bihub_world_5b.yaml @@ -0,0 +1,27 @@ +# MIRA Table-11 5B-base dimensions. Conditioning modules make the exact total differ from 5.0B. +latent_dim: 32 +latent_height: 9 +latent_width: 12 +context_latents: 10 +future_latents: 10 +text_dim: 4096 +hidden_dim: 4096 +layers: 16 +heads: 32 +kv_heads: 8 +temporal_layers: [0, 4, 8, 12, 15] +attention_gating: true +qk_norm: layernorm +register_tokens: 0 +activation_checkpointing: true +clean_past: false +direct_left_right: false +latent_mean: 0.024823864160431405 +latent_std: 1.9595992324017892 +state: + hidden_dim: 512 + layers: 2 + heads: 8 + text_kv_heads: 4 + # RoboTwin's cached next target makes previous action nearly duplicate current target state. + use_action_history: false diff --git a/release-20261107/source/workspace_joint/mira/configs/model/bihub_world_smoke.yaml b/release-20261107/source/workspace_joint/mira/configs/model/bihub_world_smoke.yaml new file mode 100644 index 0000000000000000000000000000000000000000..183a41faf7d089ce73826c16737070e6ddce69fa --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/model/bihub_world_smoke.yaml @@ -0,0 +1,26 @@ +# Isomorphic debug profile: same views, graph, state/text paths, flow loss, FSDP2 and checkpoint path. +latent_dim: 32 +latent_height: 9 +latent_width: 12 +context_latents: 10 +future_latents: 10 +text_dim: 4096 +hidden_dim: 128 +layers: 2 +heads: 4 +kv_heads: 2 +temporal_layers: [0, 1] +attention_gating: true +qk_norm: layernorm +register_tokens: 0 +activation_checkpointing: true +clean_past: false +direct_left_right: false +latent_mean: 0.024823864160431405 +latent_std: 1.9595992324017892 +state: + hidden_dim: 64 + layers: 1 + heads: 4 + text_kv_heads: 2 + use_action_history: false diff --git a/release-20261107/source/workspace_joint/mira/configs/model/latent_world_model.yaml b/release-20261107/source/workspace_joint/mira/configs/model/latent_world_model.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4c6005389a62b2095f96680355558c1222279ee1 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/model/latent_world_model.yaml @@ -0,0 +1,56 @@ +# Latent world model: a frozen RAEv2 codec plus an action-conditioned flow-matching diffusion +# transformer over the codec's latent grid. The codec is loaded frozen from `codec_checkpoint`; its +# latent dimension and temporal/spatial downsampling factors are read from it, not configured here. +# The architecture size is selected via package-override (`latent_world_model@architecture.config`). +defaults: + - latent_world_model@architecture.config: 1b + +architecture: + _target_: mira.world_model.latent_world_model.LatentWorldModel + _convert_: all # pass plain dicts to the Pydantic config, not OmegaConf nodes + + config: + _target_: mira.world_model.config.LatentWorldModelConfig + + # The action vocabulary travels with the dataset. + actions: ${dataset.actions} + + video: + _target_: mira.ml.image_config.ImageConfig + height: 288 + width: 512 + channels: 3 + timesteps: 40 + # Frame rate the world model sees. With actions at 20fps and codec temporal_downsampling=2, + # this yields action_temporal_downsampling = 20*2//20 = 2 and actions_per_video_frame = + # 20//20 = 1 (one action per video frame, matching every trained checkpoint). The additive + # actions.target_fps knob can decouple the two rates, but the released default is 1:1. + fps: 20 + + # Path or W&B URL to the frozen codec checkpoint; required at train/eval time (override on the + # command line). null is a placeholder so the config composes without a checkpoint. + codec_checkpoint: null + # Estimated during codec training and saved in the codec checkpoint, so null here for new codecs. + latent_mean_std: null + + patch_size: 1 + n_register_tokens: 0 + attention_gating: true + + n_context_frames: 39 # only used during inference + dropout_action_prob: 0.1 + learned_temporal_pool: true + causal: true + use_codec_posterior_mean: true + activation_checkpointing: false + # AdaLN conditioning on the attention sublayers as well as the MLP. + ada_attn_ln: true + # PSD-M self-distillation. Two mutually-exclusive ways to mix it in (both 0 = disabled): + # psd_loss_prob: STOCHASTIC, add the (unweighted) PSD loss on a fraction of steps. + # psd_weight: DETERMINISTIC, add psd_weight * loss_psd every step. + # See https://arxiv.org/abs/2505.18825 and https://arxiv.org/abs/2410.12557 + psd_loss_prob: 0.0 + psd_weight: 0.0 + # Condition each denoising step on the clean latents of the previous frames (avoids the + # train/inference mismatch in diffusion forcing). + use_clean_past: true diff --git a/release-20261107/source/workspace_joint/mira/configs/model/latent_world_model/1b.yaml b/release-20261107/source/workspace_joint/mira/configs/model/latent_world_model/1b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a4358064492013246b2210406db3c2794880e33c --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/model/latent_world_model/1b.yaml @@ -0,0 +1,7 @@ +# 1B-parameter latent world model: transformer dimensions overlaid onto LatentWorldModelConfig via +# the `latent_world_model@architecture.config: 1b` package override. +hidden_dim: 2048 +n_head: 16 +n_kv_head: 4 +n_layers: 16 +time_attention_every: 4 diff --git a/release-20261107/source/workspace_joint/mira/configs/model/lingbot_raev2_codec_tdown.yaml b/release-20261107/source/workspace_joint/mira/configs/model/lingbot_raev2_codec_tdown.yaml new file mode 100644 index 0000000000000000000000000000000000000000..76f6292ea7fdd3bb82392be820ca691166a32fa4 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/model/lingbot_raev2_codec_tdown.yaml @@ -0,0 +1,58 @@ +# RAEv2 codec with 2x temporal downsampling and a frozen LingBot-Vision-Large/16 backbone. +# The LingBot checkpoint is loaded strictly from a local directory/file; no Hub fallback occurs. +# Loss = L1 + LPIPS + normalized LingBot feature consistency, with auto-weight balancing. + +loss: + _target_: mira.codec.CodecLoss + _convert_: all + + weights: + _target_: mira.codec.CodecLossWeights + loss_mae: 1.0 + loss_lpips_perceptual: 1.0 + lpips_perceptual_frame_frac: 0.25 + loss_lingbot_feature_consistency: 1.0 + lingbot_feature_consistency_frame_frac: 0.25 + auto_weight: true + max_auto_weight: 10000 + +############################################################################# +architecture: + _target_: mira.codec.VideoCodec + _convert_: all + + config: + _target_: mira.codec.VideoCodecConfig + encoder: + latent_dim: 32 + backbone_type: lingbot + rae_model: large + backbone_weights_path: ${oc.env:LINGBOT_VISION_MODEL_DIR,../models/lingbot-vision-vit-large} + aggregation_layers: [11, 13, 15, 17, 19, 21, 23] + bottleneck: + stride: 2 + temporal_stride: 2 + noise_tau: 0.0 + compile_backbone: ${run.compile} + video: + height: 288 + # RoboTwin cameras are native 4:3. 288x384 preserves that aspect ratio and remains exactly + # divisible by the codec's 32x spatial downsampling (latent grid 9x12). + width: 384 + channels: 3 + timesteps: 40 + fps: 20 + + decoder: + latent_dim: ${..encoder.latent_dim} + activation_checkpointing: true + bottleneck: + stride: ${...encoder.bottleneck.stride} + vit_width: 1152 + vit_depth: 28 + vit_num_heads: 16 + mlp_dim_multiplier: 4 + qk_norm: layernorm + patch_size: 16 + patch_size_t: 2 + video: ${..encoder.video} diff --git a/release-20261107/source/workspace_joint/mira/configs/model/multi_wrapper_world_model.yaml b/release-20261107/source/workspace_joint/mira/configs/model/multi_wrapper_world_model.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4669f4190d23cc145253b3e7331f547e413862c --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/model/multi_wrapper_world_model.yaml @@ -0,0 +1,76 @@ +# Multiplayer latent world model: an inner LatentWorldModel that processes `n_players` per-player +# clips tiled into one vertically-stacked frame. The frozen codec runs per player at the original +# single-player resolution; the diffusion transformer sees the full tiled grid. Because the +# transformer uses RoPE (resolution-independent), a single-player checkpoint warm-starts into this +# model via `run.finetune_from` -- see MultiWrapperWorldModel.load_state_dict. +# +# The inner architecture size is selected via package-override on the nested wm_config; `1b` mirrors +# the single-player default. Use with `dataset.n_players=4` so the loader emits 4 contiguous, +# player-id-ordered perspectives per group (the consistency check enforces the match). +defaults: + - latent_world_model@architecture.config.wm_config: 1b + +architecture: + _target_: mira.world_model.multi_wrapper_world_model.MultiWrapperWorldModel + _convert_: all # pass plain dicts to the Pydantic config, not OmegaConf nodes + + config: + _target_: mira.world_model.multi_wrapper_world_model.MultiWrapperWorldModelConfig + + n_players: 4 + + wm_config: + _target_: mira.world_model.config.LatentWorldModelConfig + + # The action vocabulary travels with the dataset. + actions: ${dataset.actions} + + video: + _target_: mira.ml.image_config.ImageConfig + # Single-player height; the wrapper multiplies it by n_players for the tiled inner model + # while the codec keeps this original height (it runs per player). + height: 288 + width: 512 + channels: 3 + timesteps: 80 + # Frame rate the world model sees. action_temporal_downsampling = actions.target_fps * + # codec_temporal_downsampling // fps sets how many actions map to each latent frame; with + # 20fps actions and a td=2 codec that is 20*2//20 = 2 actions per latent frame. + fps: 20 + + # Path or W&B URL to the frozen codec checkpoint; required at train/eval time (override on the + # command line). null is a placeholder so the config composes without a checkpoint. + codec_checkpoint: null + # Estimated during codec training and saved in the codec checkpoint, so null here for new codecs. + latent_mean_std: null + + # Fine-tuning from a single-player baseline requires matching the baseline's architecture + # values (patch size, register tokens, attention gating). + patch_size: 1 + n_register_tokens: 0 + attention_gating: true + + n_context_frames: 78 # only used during inference + dropout_action_prob: 0.1 + # Drop each player's actions independently (with dropout_action_prob). On a drop, + # action_subset_drop_prob is the chance only the Q/E/Space/Shift/Ctrl subset is dropped + # (keeping WASD + mouse) rather than the player's whole action stream. + dropout_action_per_player: true + action_subset_drop_prob: 0.5 + learned_temporal_pool: true + causal: true + use_codec_posterior_mean: true + # Recompute transformer-layer activations in the backward pass to fit the larger tiled + # (multi-player) sequence. + activation_checkpointing: true + # AdaLN conditioning on the attention sublayers as well as the MLP. + ada_attn_ln: true + # PSD-M self-distillation. Two mutually-exclusive ways to mix it in (both 0 = disabled): + # psd_loss_prob: STOCHASTIC, add the (unweighted) PSD loss on a fraction of steps. + # psd_weight: DETERMINISTIC, add psd_weight * loss_psd every step. + # See https://arxiv.org/abs/2505.18825 and https://arxiv.org/abs/2410.12557 + psd_loss_prob: 0.0 + psd_weight: 0.0 + # Condition each denoising step on the clean latents of the previous frames (avoids the + # train/inference mismatch in diffusion forcing). + use_clean_past: true diff --git a/release-20261107/source/workspace_joint/mira/configs/model/raev2_codec_tdown.yaml b/release-20261107/source/workspace_joint/mira/configs/model/raev2_codec_tdown.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9917a95d6d1cf60844e4ede5932b7db63608b260 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/model/raev2_codec_tdown.yaml @@ -0,0 +1,55 @@ +# RAEv2 codec with 2x temporal downsampling (40 frames @ 20 fps -> 20 latents @ 10 fps -> +# 40 frames @ 20 fps): a frozen DINOv3-L/16 backbone with layer aggregation and a strided-conv +# bottleneck, feeding a ViT video decoder. Loss = L1 + LPIPS + DINO latent consistency, with +# auto-weight balancing of the perceptual terms against the L1 anchor. + +loss: + _target_: mira.codec.CodecLoss + _convert_: all # pass plain dicts to the Pydantic config, not OmegaConf nodes + + weights: + _target_: mira.codec.CodecLossWeights + loss_mae: 1.0 + loss_lpips_perceptual: 1.0 + lpips_perceptual_frame_frac: 0.25 + loss_dino_latent_consistency: 1.0 + dino_latent_consistency_frame_frac: 0.25 + compile_dino: ${run.compile} + auto_weight: true + +############################################################################# +architecture: + _target_: mira.codec.VideoCodec + _convert_: all # pass plain dicts to the Pydantic config, not OmegaConf nodes + + config: + _target_: mira.codec.VideoCodecConfig + encoder: + latent_dim: 32 + rae_model: dinov3_vitl16 + aggregation_layers: [11, 13, 15, 17, 19, 21, 23] + bottleneck: + stride: 2 + temporal_stride: 2 + noise_tau: 0.0 + compile_dino: ${run.compile} + video: + height: 288 + width: 512 + channels: 3 + timesteps: 40 + fps: 20 + + decoder: + latent_dim: ${..encoder.latent_dim} + activation_checkpointing: true + bottleneck: + stride: ${...encoder.bottleneck.stride} + vit_width: 1152 + vit_depth: 28 + vit_num_heads: 16 + mlp_dim_multiplier: 4 + qk_norm: layernorm + patch_size: 16 + patch_size_t: 2 + video: ${..encoder.video} diff --git a/release-20261107/source/workspace_joint/mira/configs/train_action_head.yaml b/release-20261107/source/workspace_joint/mira/configs/train_action_head.yaml new file mode 100644 index 0000000000000000000000000000000000000000..77bcddc20858bca231b487fb2351c9a972b6527d --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/train_action_head.yaml @@ -0,0 +1,105 @@ +defaults: + - _self_ + - model: action_joint_flow + +run: + seed: 2026 + debug_smoke: false + output_dir: ${oc.env:MIRA_ACTION_OUTPUT_DIR,../outputs/robotwin_joint_action_flow} + continue_from: null + auto_resume: true + # A GT-only warm-up may stop at this completed step while the deterministic + # predicted-future cache is still being generated. Null disables this behavior. + stop_at_step_if_future_incomplete: null + log_every: 100 + early_log_steps: 10 + +upstream: + world_selection: ${oc.env:MIRA_ACTION_WORLD_SELECTION,../artifacts/action_stage/world/world_selection.json} + state_encoder: ${oc.env:MIRA_ACTION_STATE_ENCODER,../artifacts/action_stage/world/selected_state_encoder.pt} + expected_world_params: 1397471023 + expected_view_order: [left, global, right] + +data: + train_manifest: ${oc.env:MIRA_ACTION_TRAIN_MANIFEST,../artifacts/action_stage/manifests/train.jsonl} + val_manifest: ${oc.env:MIRA_ACTION_VAL_MANIFEST,../artifacts/action_stage/manifests/val.jsonl} + state_stats: ${oc.env:MIRA_ACTION_STATE_STATS,../datasets/RoboTwin2.0/mira_wam_aloha/dataset_stats.json} + action_stats: ${oc.env:MIRA_ACTION_STATS,../artifacts/action_stage/manifests/action_stats.json} + train_future_cache: ${oc.env:MIRA_ACTION_TRAIN_FUTURE,../artifacts/action_stage/future_pred10/train} + val_future_cache: ${oc.env:MIRA_ACTION_VAL_FUTURE,../artifacts/action_stage/future_pred10/val} + latent_mean: 0.024823864160431405 + latent_std: 1.9595992324017892 + clean_probability: 0.5 + allow_incomplete_future_cache: false + +training: + scope: action_head_only + steps: 100000 + effective_global_batch: 128 + per_device_batch: 8 + gradient_accumulation_steps: 2 + precision: bf16 + distributed: + strategy: fsdp2_full_shard + expected_world_size: 8 + future_curriculum: + gt_only_until: 5000 + transition_end: 20000 + optimizer: + main_lr: 1.0e-4 + state_copy_lr: 2.0e-5 + betas: [0.9, 0.95] + eps: 1.0e-8 + weight_decay: 1.0e-2 + warmup_steps: 2000 + min_lr: 5.0e-7 + grad_clip: 1.0 + ema_decay: 0.9999 + +dataloader: + num_workers: 4 + prefetch_factor: 2 + +validation: + every: 1000 + batches: 16 + per_device_batch: 1 + sample_batches: 4 + action_steps: 10 + at_end: true + seed: 2026 + +visualization: + every: 5000 + num_cases: 4 + +checkpoint: + every: 5000 + keep_recent: 2 + save_final: true + +swanlab: + project: Multi_WAM + workspace: null + experiment_name: RoboTwin-3View-JointActionFlow + description: Frozen-world three-view joint bimanual 20x14 action-flow training. + job_type: action-head-training + group: robotwin-three-view-action + tags: [action-flow, three-view, BiHub, RoboTwin2, bimanual] + mode: online + public: false + resume: allow + token_file: ${oc.env:SWANLAB_TOKEN_FILE,../z_oranger/token.txt} + capture_console: stderr + system_monitor: false + upload_hardware: true + upload_runtime: true + upload_requirements: false + upload_git: false + +hydra: + run: + dir: ${run.output_dir} + output_subdir: .hydra + job: + chdir: false diff --git a/release-20261107/source/workspace_joint/mira/configs/train_action_head_2gpu.yaml b/release-20261107/source/workspace_joint/mira/configs/train_action_head_2gpu.yaml new file mode 100644 index 0000000000000000000000000000000000000000..41314c6f0ae982862455a067e4ca6e2fa4727251 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/train_action_head_2gpu.yaml @@ -0,0 +1,22 @@ +defaults: + - train_action_head + - _self_ + +# Optimization-equivalent two-GPU layout for coexistence runs. The model, data, +# curriculum, LR schedule, and effective global batch remain identical to the +# eight-GPU formal configuration; only gradient accumulation changes. +run: + output_dir: ${oc.env:MIRA_ACTION_OUTPUT_DIR,../outputs/robotwin_joint_action_flow_2gpu} + +training: + effective_global_batch: 128 + per_device_batch: 8 + gradient_accumulation_steps: 8 + distributed: + strategy: fsdp2_full_shard + expected_world_size: 2 + +swanlab: + experiment_name: RoboTwin-3View-JointActionFlow-2GPU + description: Optimization-equivalent two-GPU coexistence run of the formal Action Head. + tags: [action-flow, three-view, BiHub, RoboTwin2, bimanual, two-gpu] diff --git a/release-20261107/source/workspace_joint/mira/configs/train_action_head_smoke.yaml b/release-20261107/source/workspace_joint/mira/configs/train_action_head_smoke.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9450170bf4999ce32a97e1ec96d5e1130aee8400 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/train_action_head_smoke.yaml @@ -0,0 +1,105 @@ +defaults: + - _self_ + - model: action_joint_flow + +run: + seed: 2026 + debug_smoke: true + output_dir: ${oc.env:MIRA_ACTION_OUTPUT_DIR,../outputs/robotwin_joint_action_flow_smoke} + continue_from: null + auto_resume: false + stop_at_step_if_future_incomplete: null + log_every: 1 + early_log_steps: 3 + +upstream: + world_selection: ${oc.env:MIRA_ACTION_WORLD_SELECTION,../artifacts/action_stage_smoke/world/world_selection.json} + state_encoder: ${oc.env:MIRA_ACTION_STATE_ENCODER,../artifacts/action_stage_smoke/world/selected_state_encoder.pt} + expected_world_params: 1397471023 + expected_view_order: [left, global, right] + +data: + train_manifest: ${oc.env:MIRA_ACTION_TRAIN_MANIFEST,../artifacts/action_stage_smoke/manifests/train.jsonl} + val_manifest: ${oc.env:MIRA_ACTION_VAL_MANIFEST,../artifacts/action_stage_smoke/manifests/val.jsonl} + state_stats: ${oc.env:MIRA_ACTION_STATE_STATS,../datasets/RoboTwin2.0/mira_wam_aloha/dataset_stats.json} + action_stats: ${oc.env:MIRA_ACTION_STATS,../artifacts/action_stage_smoke/manifests/action_stats.json} + train_future_cache: ${oc.env:MIRA_ACTION_TRAIN_FUTURE,../artifacts/action_stage_smoke/future_pred10/train} + val_future_cache: ${oc.env:MIRA_ACTION_VAL_FUTURE,../artifacts/action_stage_smoke/future_pred10/val} + latent_mean: 0.024823864160431405 + latent_std: 1.9595992324017892 + clean_probability: 0.5 + allow_incomplete_future_cache: false + +training: + scope: action_head_only + # Compress the formal curriculum without changing its source-selection logic so the + # smoke covers GT, mixed GT/predicted, and predicted-only training branches. + steps: 6 + effective_global_batch: 2 + per_device_batch: 1 + gradient_accumulation_steps: 1 + precision: bf16 + distributed: + strategy: fsdp2_full_shard + expected_world_size: 2 + future_curriculum: + gt_only_until: 1 + transition_end: 5 + optimizer: + main_lr: 1.0e-4 + state_copy_lr: 2.0e-5 + betas: [0.9, 0.95] + eps: 1.0e-8 + weight_decay: 1.0e-2 + warmup_steps: 5 + min_lr: 5.0e-7 + grad_clip: 1.0 + ema_decay: 0.9999 + +dataloader: + num_workers: 0 + prefetch_factor: 2 + +validation: + every: 6 + batches: 1 + per_device_batch: 1 + sample_batches: 1 + action_steps: 2 + at_end: true + seed: 2026 + +visualization: + every: 6 + num_cases: 1 + +checkpoint: + every: 6 + keep_recent: 1 + save_final: true + +swanlab: + project: Multi_WAM + workspace: null + experiment_name: RoboTwin-3View-JointActionFlow-Smoke + description: Two-GPU coexistence smoke test of the exact formal Action architecture. + job_type: smoke-test + group: robotwin-three-view-action + tags: [action-flow, smoke, two-gpu, coexistence] + mode: disabled + public: false + resume: allow + token_file: ${oc.env:SWANLAB_TOKEN_FILE,../z_oranger/token.txt} + capture_console: none + system_monitor: false + upload_hardware: false + upload_runtime: false + upload_requirements: false + upload_git: false + +hydra: + run: + dir: ${run.output_dir} + output_subdir: .hydra + job: + chdir: false diff --git a/release-20261107/source/workspace_joint/mira/configs/train_bihub_wam_world.yaml b/release-20261107/source/workspace_joint/mira/configs/train_bihub_wam_world.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b07686a90ce6084cc65ffcca9758769393f9421c --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/train_bihub_wam_world.yaml @@ -0,0 +1,94 @@ +defaults: + - _self_ + - model: bihub_world_1b + - dataset: robotwin_wam + +run: + seed: 2026 + debug_smoke: false + output_dir: ${oc.env:MIRA_WAM_OUTPUT_DIR,../outputs/robotwin_3view_world_1b} + continue_from: null + auto_resume: true + log_every: 100 + early_log_steps: 10 + +training: + current_scope: world_only + steps: 150000 + single_view_steps: 30000 + effective_global_batch: 32 + # 8 GPUs x batch 4 x accumulation 1 = 32. This preserves the original optimization batch while + # removing redundant micro-step/FSDP overhead; per-sample curriculum roles remain invariant. + per_device_batch: 4 + gradient_accumulation_steps: 1 + precision: bf16 + distributed: + strategy: fsdp2_full_shard + optimizer: + lr: 1.0e-4 + betas: [0.9, 0.99] + eps: 1.0e-8 + weight_decay: 0.1 + warmup_steps: 1000 + min_lr: 1.0e-6 + grad_clip: 1.0 + ema_decay: 0.999 + +deferred_action: + enabled: false + +dataloader: + num_workers: 4 + prefetch_factor: 2 + +validation: + every: 1000 + batches: 16 + per_device_batch: 1 + at_end: true + seed: 2026 + +visualization: + enabled: true + every: 5000 + num_cases: 4 + case_seed: 2026 + sampling_steps: 10 + # Formal fixed cases are decoded locally. We intentionally do not upload media in-process: + # object-store failures must not stall or terminate training; scalar SwanLab logging continues. + decode_rgb: true + video_fps: 20 + codec_checkpoint: ${oc.env:MIRA_CODEC_CHECKPOINT,../outputs/mira_robotwin_codec/checkpoint-125000/checkpoint.pth} + +checkpoint: + every: 5000 + on_curriculum_switch: true + keep_recent: 2 + save_final: true + +swanlab: + project: Multi_WAM + workspace: null + experiment_name: RoboTwin-3View-WorldModel-1B + description: Three-view RoboTwin world model using the MIRA 1B backbone and frozen LingBot codec latents. + job_type: world-model-training + group: robotwin-three-view-world + tags: [world-model, three-view, BiHub, RoboTwin2, MIRA-1B] + mode: online + public: false + resume: allow + token_file: ${oc.env:SWANLAB_TOKEN_FILE,../z_oranger/token.txt} + # Keep the cloud dashboard compact. Full diagnostics remain in local metrics.jsonl. + capture_console: stderr + system_monitor: false + upload_hardware: true + upload_runtime: true + upload_requirements: false + upload_git: false + +hydra: + run: + dir: ${run.output_dir} + output_subdir: .hydra + job: + chdir: false diff --git a/release-20261107/source/workspace_joint/mira/configs/train_bihub_wam_world_smoke.yaml b/release-20261107/source/workspace_joint/mira/configs/train_bihub_wam_world_smoke.yaml new file mode 100644 index 0000000000000000000000000000000000000000..49703a401b9378b6709be5698f68ea9a4d177e4a --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/train_bihub_wam_world_smoke.yaml @@ -0,0 +1,90 @@ +defaults: + - _self_ + - model: bihub_world_1b + - dataset: robotwin_wam_smoke + +run: + seed: 2026 + debug_smoke: true + output_dir: ${oc.env:MIRA_WAM_OUTPUT_DIR,../outputs/robotwin_3view_world_1b_smoke} + continue_from: null + auto_resume: false + log_every: 1 + early_log_steps: 2 + +training: + current_scope: world_only + steps: 2 + single_view_steps: 1 + effective_global_batch: 32 + per_device_batch: 4 + gradient_accumulation_steps: 1 + precision: bf16 + distributed: + strategy: fsdp2_full_shard + optimizer: + lr: 1.0e-4 + betas: [0.9, 0.99] + eps: 1.0e-8 + weight_decay: 0.1 + warmup_steps: 5 + min_lr: 1.0e-6 + grad_clip: 1.0 + ema_decay: 0.999 + +deferred_action: + enabled: false + +dataloader: + num_workers: 0 + prefetch_factor: 2 + +validation: + every: 2 + batches: 1 + per_device_batch: 1 + at_end: true + seed: 2026 + +visualization: + enabled: false + every: 2 + num_cases: 1 + case_seed: 2026 + sampling_steps: 4 + # Keep the measured smoke peak specific to Stage-W training. Formal runs decode RGB cases. + decode_rgb: false + video_fps: 20 + codec_checkpoint: ${oc.env:MIRA_CODEC_CHECKPOINT,../outputs/mira_robotwin_codec/checkpoint-125000/checkpoint.pth} + +checkpoint: + every: 999999 + on_curriculum_switch: false + keep_recent: 2 + save_final: false + +swanlab: + project: Multi_WAM + workspace: null + experiment_name: RoboTwin-3View-WorldModel-1B-Smoke + description: Local two-step 8-GPU integration check for the exact 1.4B training architecture. + job_type: smoke-test + group: robotwin-three-view-world + tags: [world-model, three-view, BiHub, smoke, 8-GPU, MIRA-1B] + mode: disabled + public: false + resume: allow + token_file: ${oc.env:SWANLAB_TOKEN_FILE,../z_oranger/token.txt} + capture_console: none + system_monitor: false + upload_hardware: false + upload_runtime: false + upload_requirements: false + upload_git: false + +hydra: + run: + dir: ${run.output_dir} + output_subdir: .hydra + job: + chdir: false diff --git a/release-20261107/source/workspace_joint/mira/configs/train_codec.yaml b/release-20261107/source/workspace_joint/mira/configs/train_codec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a2d456cadd6066c3ec7ec72f2c6ca772d6797c07 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/train_codec.yaml @@ -0,0 +1,105 @@ +# Codec training entry point (RAEv2 temporal-downsampling): reconstruction training (video-only) +# with periodic validation, fixed local visualizations, and SwanLab cloud logging. +defaults: + - _self_ + - model: lingbot_raev2_codec_tdown + - dataset: robotwin2 + +# The action vocabulary travels with the dataset; expose it at the top level for the loader. +actions: ${dataset.actions} + +wandb: + entity: null + project: mira-codec + name: lingbot-robotwin-codec + group: null + mode: disabled # retained for compatibility with the original MIRA training path + remove_old_runs: false + +swanlab: + project: Multi_WAM + workspace: null # null uploads to the account that owns the token + experiment_name: lingbot-robotwin-codec + description: LingBot-Vision codec training on aligned RoboTwin2.0 head/left/right views. + job_type: codec-training + group: robotwin2-lingbot + tags: [codec, robotwin2, lingbot-vision, three-view] + mode: online # online, offline, local, or disabled + public: false + resume: allow + token_file: ${oc.env:SWANLAB_TOKEN_FILE,../z_oranger/token.txt} + log_videos: true + # SwanLab currently accepts GIF media. Local visualizations remain full-quality MP4; only the + # uploaded copy is temporally/spatially reduced. + video_fps: 2 + video_max_side: 384 + +run: + seed: 28 + steps: 250_001 + # Per-GPU batch size. The full XL decoder + three-loss LingBot recipe is intentionally started + # conservatively; increase only after observing memory headroom on the target GPU. + batch_size: 1 + checkpoint_every: "5%" + checkpoint_keep_recent: 1 + checkpoint_keep_permanent_every: -1 + # Lightweight terminal + SwanLab scalar logging. Validation, visualization, and checkpoints + # retain their independent, less frequent schedules below. + log_every: 100 + output_dir: "train_robotwin_codec_logs" + # Keep disabled for the first LingBot integration run. Enable with run.compile=true after one + # real-data batch has completed; full-model compilation can otherwise occupy a GPU for a long + # warmup before surfacing data/config errors. + compile: false + # Crash recovery: path or W&B URL to resume the full training state from (continues the step + # counter). Mutually exclusive with finetune_from. + continue_from: null + # Fine-tuning: path or W&B URL to warm-start the weights from; optimizer/scheduler/step start + # fresh. Mutually exclusive with continue_from. + finetune_from: null + # The latent mean/std are tracked with an exponential moving average using this decay. + latents_ema_decay: 0.99 + +dataloader: + num_workers: 4 + shuffle_buffer_size: 100 + archive_mix_size: 32 + prefetch_factor: 2 + +validation: + batch_size: null # null to use the same batch size as training + val_first: true + val_n_samples: 96 + val_every: "2%" + # Fixed RoboTwin cases below replace the old moving/random validation example. + random_visualization: false + +visualization: + enabled: true + first: true + every: "1%" + # A case is one episode/time-window; every saved video contains head/left/right rows. + num_cases: 4 + case_seed: 2026 + output_subdir: visualizations + +optim: + optimizer: + lr: 1e-4 + betas: [0.9, 0.95] + weight_decay: 0.1 + scheduler: + warmup_steps: 1000 + constant_steps: 0 + decay_steps: 249_000 # 0 to disable cosine decay; otherwise ~run.steps - warmup_steps + min_lr: 1e-6 + model_ema_decay: 0.9999 # 0.0 to disable + +# Keep Hydra's resolved config/log metadata with the actual run instead of creating a second +# timestamped `./outputs/` tree in the source repository. +hydra: + run: + dir: ${oc.env:MIRA_HYDRA_RUN_DIR,outputs/${now:%Y-%m-%d}/${now:%H-%M-%S}} + output_subdir: .hydra + job: + chdir: false diff --git a/release-20261107/source/workspace_joint/mira/configs/train_world_model.yaml b/release-20261107/source/workspace_joint/mira/configs/train_world_model.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c387257fe23041767d2547b2c797bca4fb3321f6 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/train_world_model.yaml @@ -0,0 +1,83 @@ +# Latent world-model training entry point. Flow-matching diffusion loss on frozen-codec latents, +# periodic validation loss, and an optional world-model metrics eval (DINO/latent drift + Frechet +# curves) with rollout visualizations (video-only). Data is read through +# `mira.data.training_loader.create_loader`. +defaults: + - _self_ + - model: latent_world_model + - dataset: rocket_league + +# The action vocabulary travels with the dataset; expose it at the top level for the loader. +actions: ${dataset.actions} + +wandb: + entity: null + project: mira-world-model + name: world_model + group: null + mode: online # "disabled" to turn off, "offline" to log locally only + +run: + seed: 28 + steps: 250_001 + batch_size: 1 + checkpoint_every: "10%" + checkpoint_keep_recent: 1 + checkpoint_keep_permanent_every: -1 + log_every: "1%" + output_dir: "train_world_model_logs" + # Opt-in; default off for reproducibility. When true, the codec encoder, diffusion transformer, + # and codec decoder are compiled separately (the forward has data-dependent control flow). + compile: false + # Crash recovery: path or W&B URL to resume the full training state from (continues the step + # counter). Mutually exclusive with finetune_from. + continue_from: null + # Fine-tuning: path or W&B URL to warm-start the weights from; optimizer/scheduler/step start + # fresh. Mutually exclusive with continue_from. + finetune_from: null + +dataloader: + num_workers: 6 + shuffle_buffer_size: 100 + +validation: + batch_size: null # null to use the same batch size as training + val_first: true + val_n_samples: 1024 + val_every: "2%" + downstream_val_every: "10%" # how often to run the world-model metrics eval + +optim: + optimizer: + lr: 1e-4 + betas: [0.9, 0.99] + weight_decay: 0.1 + scheduler: + warmup_steps: 1000 + constant_steps: 0 + decay_steps: 0 # 0 to disable cosine decay + min_lr: 1e-6 + model_ema_decay: 0.9999 # 0.0 to disable + +# World-model rollout metrics, evaluated every `validation.downstream_val_every`. +world_model_metrics: + _target_: mira.training.metrics.world_model_metrics.WorldModelMetricsConfig + _convert_: all # pass plain dicts to the Pydantic config, not OmegaConf nodes + # Inference (rollout) settings; fields not listed keep their WorldModelInferenceConfig defaults. + inference: + schedule_type: linear + noise_level: 0.0 + num_samples: 2048 + per_device_batch_size: ${run.batch_size} + # 4 s eval on the shipped 4 s (80-frame @ 20 fps) chunks. With temporal_downsampling=2 the eval + # clip is n_context_frames + num_unrolled_frames*2 = 38 + 20*2 = 78 frames (<= 80, even so it + # encodes cleanly): 38 context frames (~2 s) then a 20-latent-frame (~2 s) rollout. 38 is a + # multiple of 2 and stays under both shipped model windows (video.timesteps 40 single / 80 multi). + n_context_frames: 38 + num_unrolled_frames: 20 + drift_metric_frames: 20 + fdd_slice_frames: 10 # per-slice Frechet width -> 20/10 = 2 slices (at 10, 20 latent frames) + eval_temporal_downsampling: null + compile: ${run.compile} + dino_max_chunk_size: 128 # max frames per DINO forward pass, reduces peak memory + num_viz_samples: 8 # how many eval samples to visualize (logged to W&B) diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v10_h1_50/base.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v10_h1_50/base.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c03facec7d4212eca86c8cde0c3fa0958e21cdfe --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v10_h1_50/base.yaml @@ -0,0 +1,57 @@ +extends: ../world_v9_episode_start/base.yaml + +experiment: + name: robotwin_bihub_world_v10_h1_50_high_lr + architecture: bihub-world-v10-h1-50-high-lr-online + process_prefix: tagshotx_wv10 + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v10_h1_50_high_lr + artifact_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v10_h1_50 + debug_smoke: false + +artifacts: + source_checkpoint: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v9_episode_start_h1/main-checkpoint-14000 + source_checkpoint_step: 14000 + source_checkpoint_architecture: bihub-world-v9-episode-start-h1-online + +data: + history_probabilities: [0.5, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666] + history_cycle: [1, 1, 1, 3, 6, 10] + h1_episode_start_only: true + +training: + steps: 20000 + initial_step: 0 + warmup_steps: 1000 + full_finetune_from_step: 1 + lr_resampler: 4.0e-5 + lr_condition: 4.0e-5 + lr_world: 3.0e-5 + min_lr_ratio: 0.03333333333333333 + +validation: + every_steps: 500 + fixed_cases: 6 + episode_start_cases: 4 + sample_every_steps: 2000 + fixed_seed: 2026 + sample_steps: 10 + decode_videos: true + +checkpoint: + every_steps: 1000 + keep_last_recovery: 2 + preserve_steps: [5000, 10000, 15000, 20000] + auto_resume: true + +logging: + every_steps: 50 + early_steps: 10 + swanlab_enabled: true + swanlab_project: multi-wam + swanlab_experiment_name: RoboTwin-BiHub-World-v10-H1-50-HighLR-20k + swanlab_token_file: /public/interns/haocheng/Oranger/project/multi_wam/z_tmp/swanlab_token.txt + +runtime: + phase: main + mode: formal + max_steps: null diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v10_h1_50/smoke.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v10_h1_50/smoke.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3b3eacd1eb594e8ef86d10013d985d20be8c4be4 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v10_h1_50/smoke.yaml @@ -0,0 +1,25 @@ +extends: base.yaml + +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/world_v10_h1_50_smoke + debug_smoke: true + +validation: + every_steps: 1 + sample_every_steps: 1 + sample_steps: 2 + decode_videos: false + +checkpoint: + every_steps: 1 + preserve_steps: [1, 2] + auto_resume: false + +logging: + every_steps: 1 + early_steps: 2 + swanlab_enabled: false + +runtime: + mode: smoke + max_steps: 2 diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v10_h1_50/train.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v10_h1_50/train.yaml new file mode 100644 index 0000000000000000000000000000000000000000..785714de1723cb5408fc438bf959701fecee8427 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v10_h1_50/train.yaml @@ -0,0 +1 @@ +extends: base.yaml diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v11_continue30k/base.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v11_continue30k/base.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2328f0eb5556ef8afcc17b8969deb2478273b92f --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v11_continue30k/base.yaml @@ -0,0 +1,60 @@ +extends: ../world_v10_h1_50/base.yaml + +experiment: + name: robotwin_bihub_world_v11_continue30k_liftpot + architecture: bihub-world-v11-h1-50-liftpot-continuation-online + process_prefix: filter_x_wv11 + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v11_continue30k_liftpot + artifact_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v11_continue30k + debug_smoke: false + +artifacts: + source_checkpoint: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v10_h1_50_high_lr/main-checkpoint-20000 + source_checkpoint_step: 20000 + source_checkpoint_architecture: bihub-world-v10-h1-50-high-lr-online + fixed_case_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/mira/configs/world_v11_continue30k/fixed_cases.json + supplemental_case_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/mira/configs/world_v11_continue30k/supplemental_lift_pot_case.json + +data: + history_probabilities: [0.5, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666] + history_cycle: [1, 1, 1, 3, 6, 10] + h1_episode_start_only: true + supplemental_every_steps: 5 + +training: + steps: 50000 + initial_step: 20000 + warmup_steps: 1000 + full_finetune_from_step: 1 + lr_resampler: 4.0e-5 + lr_condition: 4.0e-5 + lr_world: 3.0e-5 + min_lr_ratio: 0.03333333333333333 + +validation: + every_steps: 500 + fixed_cases: 10 + episode_start_cases: 7 + sample_every_steps: 2000 + fixed_seed: 2026 + sample_steps: 10 + decode_videos: true + +checkpoint: + every_steps: 1000 + keep_last_recovery: 2 + preserve_steps: [25000, 30000, 35000, 40000, 45000, 50000] + auto_resume: true + +logging: + every_steps: 50 + early_steps: 10 + swanlab_enabled: true + swanlab_project: multi-wam + swanlab_experiment_name: RoboTwin-BiHub-World-v11-H1-50-LiftPot-20kTo50k + swanlab_token_file: /public/interns/haocheng/Oranger/project/multi_wam/z_tmp/swanlab_token.txt + +runtime: + phase: main + mode: formal + max_steps: null diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v11_continue30k/fixed_cases.json b/release-20261107/source/workspace_joint/mira/configs/world_v11_continue30k/fixed_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..636fb82a106806a01baa3bd74f4fdf6899b2734d --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v11_continue30k/fixed_cases.json @@ -0,0 +1,16 @@ +{ + "format_version": 2, + "contract": "world-v11-ten-fixed-h1-cases-first-seven-episode-start", + "cases": [ + {"case_id": 0, "base_global": 0, "episode_sha256": "669a2a18437552e4fff8289982ac59a62c1115265046d36080ebcc1f304621e8", "latent_start": 0, "task": "adjust_bottle", "domain": "clean", "purpose": "episode_start_h1"}, + {"case_id": 1, "base_global": 4780, "episode_sha256": "ee7c7389d07972a076213e3ffd5beb9c2f89125d3e937d7ea770afd6953cf426", "latent_start": 0, "task": "handover_block", "domain": "randomized", "purpose": "episode_start_h1"}, + {"case_id": 2, "base_global": 11434, "episode_sha256": "63797242ce5b5860cd1f335a4381d795b4d4a151f71ecf414137d2b74992c8d8", "latent_start": 0, "task": "place_a2b_right", "domain": "clean", "purpose": "episode_start_h1"}, + {"case_id": 3, "base_global": 2271, "episode_sha256": "01c42064fbcf0eee5014eaa2142dcb3ccc820dc3d60b3307b7f4cdda657b4c91", "latent_start": 0, "task": "blocks_ranking_size", "domain": "randomized", "purpose": "episode_start_h1"}, + {"case_id": 4, "base_global": 6786, "episode_sha256": "5d6baa4be7e8ba32ecde8c5fe7c371941b02201be43990ac12426408fb3fbf22", "latent_start": 0, "task": "lift_pot", "domain": "clean", "purpose": "episode_start_h1_target_task"}, + {"case_id": 5, "base_global": 8263, "episode_sha256": "dedd97cea397cd56c9e3da6c8b5c22296ffdfe7b6305eeee86821f37f4871d04", "latent_start": 0, "task": "open_laptop", "domain": "clean", "purpose": "episode_start_h1"}, + {"case_id": 6, "base_global": 10856, "episode_sha256": "d12e86d9e69928fe2bf0019a435416b5d082f1a0cd83f8f7bb9bed3b3cf78308", "latent_start": 0, "task": "pick_dual_bottles", "domain": "clean", "purpose": "episode_start_h1"}, + {"case_id": 7, "base_global": 589, "episode_sha256": "d6c12ea7a25502a7403110db4e5bd812c15b64360a5a69554c45d4a55930a161", "latent_start": 66, "task": "blocks_ranking_rgb", "domain": "clean", "purpose": "mid_episode_h1_regression_guard"}, + {"case_id": 8, "base_global": 27271, "episode_sha256": "1f619ecb5791d8ffaaffe47c3fbccc194ea97db0ccdf9006515d4e754ccc77c9", "latent_start": 65, "task": "stack_bowls_three", "domain": "randomized", "purpose": "mid_episode_h1_regression_guard"}, + {"case_id": 9, "base_global": 18339, "episode_sha256": "fd53f2b2194ae0d4b081498250c3283bf45c674fdd088c2dfe86409c9f58975d", "latent_start": 12, "task": "place_phone_stand", "domain": "clean", "purpose": "mid_episode_h1_regression_guard"} + ] +} diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v11_continue30k/smoke.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v11_continue30k/smoke.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d32f05c4ce55c52786132dd3d8df767d75012d5a --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v11_continue30k/smoke.yaml @@ -0,0 +1,25 @@ +extends: base.yaml + +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/world_v11_continue30k_smoke + debug_smoke: true + +validation: + every_steps: 1 + sample_every_steps: 1 + sample_steps: 2 + decode_videos: false + +checkpoint: + every_steps: 1 + preserve_steps: [20001, 20002] + auto_resume: false + +logging: + every_steps: 1 + early_steps: 2 + swanlab_enabled: false + +runtime: + mode: smoke + max_steps: 20002 diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v11_continue30k/supplemental_lift_pot_case.json b/release-20261107/source/workspace_joint/mira/configs/world_v11_continue30k/supplemental_lift_pot_case.json new file mode 100644 index 0000000000000000000000000000000000000000..e5882650d443d08e95f49b7734c9d86adc67970e --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v11_continue30k/supplemental_lift_pot_case.json @@ -0,0 +1,38 @@ +{ + "format_version": 1, + "contract": "robotwin-eval-evidence-to-expert-supervision-v1", + "reason": "The selected lift_pot policy rollout failed, but its MP4 does not contain synchronized three-view latents, robot state, or GT future. Training therefore uses the same benchmark task's formal clean expert episode and never treats policy video pixels as ground truth.", + "eval_evidence": { + "task": "lift_pot", + "instruction_type": "unseen", + "success_rate": 0.0, + "environment_seeds": [1000003, 1000004], + "episode0_video": "../vendor/RoboTwin-official-eval/eval_result/lift_pot/BiHubWAMV10/demo_clean/robotwin_bihub_wam_v10_world20k_action10k_online/2026-08-21_15-50-55_898790/episode0.mp4", + "episode0_video_sha256": "f1b7add26860ee24bbf1c99b7126dbfb23fe5a2732dedbcb353c1d148cde98aa", + "episode1_video": "../vendor/RoboTwin-official-eval/eval_result/lift_pot/BiHubWAMV10/demo_clean/robotwin_bihub_wam_v10_world20k_action10k_online/2026-08-21_15-50-55_898790/episode1.mp4", + "episode1_video_sha256": "794db501b94986eb208ab17ce40f43bc8eac6c447ac0275f7200d8a54fc4d537", + "job_log_sha256": "25e6a1010cc1eb54868ac16bfb6c9f2aa81efc298629fc769209fbf5e20a9fa9" + }, + "sample": { + "split": "train", + "task": "lift_pot", + "domain": "clean", + "episode": 0, + "episode_sha256": "0189773017ecb95c0037b447a356e4645c370b1320a630c7b1264423fbaa14c7", + "cache_sha256": "071e2aabb520a8f17f0e7898336767114bd35ac13ec80cf25f51caceff8f9174", + "base_global": 339046, + "expanded_index": 1356184, + "latent_start": 0, + "history_length": 1, + "context_valid_frames": 1, + "state_valid_steps": 2 + }, + "replay": { + "every_optimizer_steps": 5, + "replacement_global_slot": 0, + "global_batch": 40, + "global_sample_fraction": 0.005, + "expected_exposures_over_30000_steps": 6000, + "preserves_history_mix": true + } +} diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v11_continue30k/train.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v11_continue30k/train.yaml new file mode 100644 index 0000000000000000000000000000000000000000..785714de1723cb5408fc438bf959701fecee8427 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v11_continue30k/train.yaml @@ -0,0 +1 @@ +extends: base.yaml diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v12_eval_aligned_epoch/base.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v12_eval_aligned_epoch/base.yaml new file mode 100644 index 0000000000000000000000000000000000000000..471a412b0c24e1d56e1b6d80c50dabf18bcd3b13 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v12_eval_aligned_epoch/base.yaml @@ -0,0 +1,63 @@ +extends: ../world_v11_continue30k/base.yaml + +experiment: + name: robotwin_bihub_world_v12_eval_aligned_epoch + architecture: bihub-world-v12-eval-aligned-prefix-epoch-online + process_prefix: filter_x_wv12 + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v12_eval_aligned_epoch + artifact_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v12_eval_aligned_epoch + debug_smoke: false + +artifacts: + source_checkpoint: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v11_continue30k_liftpot/main-checkpoint-50000 + source_checkpoint_step: 50000 + source_checkpoint_architecture: bihub-world-v11-h1-50-liftpot-continuation-online + fixed_case_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/mira/configs/world_v12_eval_aligned_epoch/fixed_cases.json + supplemental_case_manifest: null + sampling_contract: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v12_eval_aligned_epoch/cache/sampling_contract.json + +data: + history_probabilities: [0.25, 0.25, 0.25, 0.25] + history_cycle: [1, 3, 6, 10] + h1_episode_start_only: true + episode_start_only_histories: [1, 3, 6] + h10_all_legal_starts: true + supplemental_every_steps: 0 + +training: + steps: 147300 + initial_step: 0 + warmup_steps: 1000 + full_finetune_from_step: 1 + lr_resampler: 4.0e-5 + lr_condition: 4.0e-5 + lr_world: 3.0e-5 + min_lr_ratio: 0.03333333333333333 + +validation: + every_steps: 1000 + fixed_cases: 10 + episode_start_cases: 10 + sample_every_steps: 5000 + fixed_seed: 2026 + sample_steps: 10 + decode_videos: true + +checkpoint: + every_steps: 2500 + keep_last_recovery: 2 + preserve_steps: [25000, 50000, 75000, 100000, 125000, 147300] + auto_resume: true + +logging: + every_steps: 50 + early_steps: 10 + swanlab_enabled: true + swanlab_project: multi-wam + swanlab_experiment_name: RoboTwin-BiHub-World-v12-EvalAligned-EqualH-OneEpoch + swanlab_token_file: /public/interns/haocheng/Oranger/project/multi_wam/z_tmp/swanlab_token.txt + +runtime: + phase: main + mode: formal + max_steps: null diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v12_eval_aligned_epoch/fixed_cases.json b/release-20261107/source/workspace_joint/mira/configs/world_v12_eval_aligned_epoch/fixed_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..b553da116b76a7b425a6afed7def9c519ee610dc --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v12_eval_aligned_epoch/fixed_cases.json @@ -0,0 +1,16 @@ +{ + "format_version": 3, + "contract": "world-v12-ten-distinct-task-episode-start-h1-cases", + "cases": [ + {"case_id": 0, "base_global": 0, "episode_sha256": "669a2a18437552e4fff8289982ac59a62c1115265046d36080ebcc1f304621e8", "latent_start": 0, "task": "adjust_bottle", "domain": "clean", "purpose": "episode_start_h1"}, + {"case_id": 1, "base_global": 4780, "episode_sha256": "ee7c7389d07972a076213e3ffd5beb9c2f89125d3e937d7ea770afd6953cf426", "latent_start": 0, "task": "handover_block", "domain": "randomized", "purpose": "episode_start_h1"}, + {"case_id": 2, "base_global": 11434, "episode_sha256": "63797242ce5b5860cd1f335a4381d795b4d4a151f71ecf414137d2b74992c8d8", "latent_start": 0, "task": "place_a2b_right", "domain": "clean", "purpose": "episode_start_h1"}, + {"case_id": 3, "base_global": 2271, "episode_sha256": "01c42064fbcf0eee5014eaa2142dcb3ccc820dc3d60b3307b7f4cdda657b4c91", "latent_start": 0, "task": "blocks_ranking_size", "domain": "randomized", "purpose": "episode_start_h1"}, + {"case_id": 4, "base_global": 6786, "episode_sha256": "5d6baa4be7e8ba32ecde8c5fe7c371941b02201be43990ac12426408fb3fbf22", "latent_start": 0, "task": "lift_pot", "domain": "clean", "purpose": "episode_start_h1_target_task"}, + {"case_id": 5, "base_global": 8263, "episode_sha256": "dedd97cea397cd56c9e3da6c8b5c22296ffdfe7b6305eeee86821f37f4871d04", "latent_start": 0, "task": "open_laptop", "domain": "clean", "purpose": "episode_start_h1"}, + {"case_id": 6, "base_global": 10856, "episode_sha256": "d12e86d9e69928fe2bf0019a435416b5d082f1a0cd83f8f7bb9bed3b3cf78308", "latent_start": 0, "task": "pick_dual_bottles", "domain": "clean", "purpose": "episode_start_h1"}, + {"case_id": 7, "base_global": 523, "episode_sha256": "d6c12ea7a25502a7403110db4e5bd812c15b64360a5a69554c45d4a55930a161", "latent_start": 0, "task": "blocks_ranking_rgb", "domain": "clean", "purpose": "episode_start_h1"}, + {"case_id": 8, "base_global": 27206, "episode_sha256": "1f619ecb5791d8ffaaffe47c3fbccc194ea97db0ccdf9006515d4e754ccc77c9", "latent_start": 0, "task": "stack_bowls_three", "domain": "randomized", "purpose": "episode_start_h1"}, + {"case_id": 9, "base_global": 18327, "episode_sha256": "fd53f2b2194ae0d4b081498250c3283bf45c674fdd088c2dfe86409c9f58975d", "latent_start": 0, "task": "place_phone_stand", "domain": "clean", "purpose": "episode_start_h1"} + ] +} diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v12_eval_aligned_epoch/smoke.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v12_eval_aligned_epoch/smoke.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1d725713536d41febc92239ec2b97ad3378ae4a3 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v12_eval_aligned_epoch/smoke.yaml @@ -0,0 +1,25 @@ +extends: base.yaml + +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/world_v12_eval_aligned_epoch_smoke + debug_smoke: true + +validation: + every_steps: 1 + sample_every_steps: 1 + sample_steps: 2 + decode_videos: false + +checkpoint: + every_steps: 1 + preserve_steps: [1, 2] + auto_resume: false + +logging: + every_steps: 1 + early_steps: 2 + swanlab_enabled: false + +runtime: + mode: smoke + max_steps: 2 diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v12_eval_aligned_epoch/train.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v12_eval_aligned_epoch/train.yaml new file mode 100644 index 0000000000000000000000000000000000000000..785714de1723cb5408fc438bf959701fecee8427 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v12_eval_aligned_epoch/train.yaml @@ -0,0 +1 @@ +extends: base.yaml diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v12_four_gpu_remaining/base.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v12_four_gpu_remaining/base.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d78e896c49a0226ebd12d3a5e3b4d1130f98b3e9 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v12_four_gpu_remaining/base.yaml @@ -0,0 +1,64 @@ +extends: ../world_v12_eval_aligned_epoch/base.yaml + +experiment: + name: robotwin_bihub_world_v12_four_gpu_remaining + architecture: bihub-world-v12-largebatch-remaining-four-gpu-online + process_prefix: world_v12 + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v12_four_gpu_remaining + artifact_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v12_four_gpu_remaining + debug_smoke: false + +artifacts: + source_checkpoint: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v12_largebatch_remaining/main-checkpoint-12204 + source_checkpoint_step: 12204 + source_checkpoint_architecture: bihub-world-v12-largebatch-remaining-online + import_source_optimizer_state: true + +data: + stratum_start_ordinal: 958380 + epoch_total_draws: 5891312 + +distributed: + strategy: fsdp2_full_shard + world_size: 4 + per_device_batch: 40 + gradient_accumulation_steps: 1 + effective_global_batch: 160 + +training: + steps: 12862 + initial_step: 0 + warmup_steps: 1 + full_finetune_from_step: 1 + lr_resampler: 1.679437676569468e-5 + lr_condition: 1.679437676569468e-5 + lr_world: 1.2609196613221246e-5 + min_lr_ratio: 0.0621239685097762 + +validation: + every_steps: 500 + fixed_cases: 10 + episode_start_cases: 10 + sample_every_steps: 1000 + fixed_seed: 2026 + sample_steps: 10 + decode_videos: true + +checkpoint: + every_steps: 1000 + keep_last_recovery: 2 + preserve_steps: [5000, 10000, 12862] + auto_resume: true + +logging: + every_steps: 25 + early_steps: 10 + swanlab_enabled: true + swanlab_project: multi-wam + swanlab_experiment_name: RoboTwin-BiHub-World-v12-4GPU-RemainingEpoch + swanlab_token_file: /public/interns/haocheng/Oranger/project/multi_wam/z_tmp/swanlab_token.txt + +runtime: + phase: main + mode: formal + max_steps: null diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v12_four_gpu_remaining/smoke.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v12_four_gpu_remaining/smoke.yaml new file mode 100644 index 0000000000000000000000000000000000000000..53319e8147fc10fc878d60210877cf0fc0a66e8a --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v12_four_gpu_remaining/smoke.yaml @@ -0,0 +1,25 @@ +extends: base.yaml + +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/world_v12_four_gpu_remaining_smoke + debug_smoke: true + +validation: + every_steps: 100 + sample_every_steps: 100 + sample_steps: 2 + decode_videos: false + +checkpoint: + every_steps: 2 + preserve_steps: [2] + auto_resume: false + +logging: + every_steps: 1 + early_steps: 2 + swanlab_enabled: false + +runtime: + mode: smoke + max_steps: 2 diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v12_four_gpu_remaining/train.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v12_four_gpu_remaining/train.yaml new file mode 100644 index 0000000000000000000000000000000000000000..785714de1723cb5408fc438bf959701fecee8427 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v12_four_gpu_remaining/train.yaml @@ -0,0 +1 @@ +extends: base.yaml diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v12_largebatch_remaining/base.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v12_largebatch_remaining/base.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7301c9af68bed69d77d38a2489e573250b617928 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v12_largebatch_remaining/base.yaml @@ -0,0 +1,63 @@ +extends: ../world_v12_eval_aligned_epoch/base.yaml + +experiment: + name: robotwin_bihub_world_v12_largebatch_remaining + architecture: bihub-world-v12-largebatch-remaining-online + process_prefix: filter_x_wv12b + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v12_largebatch_remaining + artifact_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v12_largebatch_remaining + debug_smoke: false + +artifacts: + source_checkpoint: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v12_eval_aligned_epoch/main-checkpoint-47022 + source_checkpoint_step: 47022 + source_checkpoint_architecture: bihub-world-v12-eval-aligned-prefix-epoch-online + import_source_optimizer_state: true + +data: + stratum_start_ordinal: 470220 + epoch_total_draws: 5891312 + +distributed: + strategy: ddp + per_device_batch: 20 + gradient_accumulation_steps: 1 + effective_global_batch: 160 + +training: + steps: 25066 + initial_step: 0 + warmup_steps: 1 + full_finetune_from_step: 1 + lr_resampler: 3.13e-5 + lr_condition: 3.13e-5 + lr_world: 2.35e-5 + min_lr_ratio: 0.03333333333333333 + +validation: + every_steps: 500 + fixed_cases: 10 + episode_start_cases: 10 + sample_every_steps: 1000 + fixed_seed: 2026 + sample_steps: 10 + decode_videos: true + +checkpoint: + every_steps: 1000 + keep_last_recovery: 2 + preserve_steps: [5000, 10000, 15000, 20000, 25066] + auto_resume: true + +logging: + every_steps: 25 + early_steps: 10 + swanlab_enabled: true + swanlab_project: multi-wam + swanlab_experiment_name: RoboTwin-BiHub-World-v12-LargeBatch-RemainingEpoch + swanlab_token_file: /public/interns/haocheng/Oranger/project/multi_wam/z_tmp/swanlab_token.txt + +runtime: + phase: main + mode: formal + max_steps: null diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v12_largebatch_remaining/long_smoke.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v12_largebatch_remaining/long_smoke.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3bf81daecca9c2d7c26d3532d54db5f2a524ca08 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v12_largebatch_remaining/long_smoke.yaml @@ -0,0 +1,26 @@ +extends: base.yaml + +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/world_v12_largebatch_remaining_long_smoke + process_prefix: filter_x_wv12q + debug_smoke: true + +validation: + every_steps: 100 + sample_every_steps: 100 + sample_steps: 2 + decode_videos: false + +checkpoint: + every_steps: 100 + preserve_steps: [10] + auto_resume: false + +logging: + every_steps: 1 + early_steps: 10 + swanlab_enabled: false + +runtime: + mode: smoke + max_steps: 10 diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v12_largebatch_remaining/smoke.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v12_largebatch_remaining/smoke.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7e83aacd0f820227bb6f6f3dc91a07a5281ba1ca --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v12_largebatch_remaining/smoke.yaml @@ -0,0 +1,26 @@ +extends: base.yaml + +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/world_v12_largebatch_remaining_smoke + process_prefix: filter_x_wv12p + debug_smoke: true + +validation: + every_steps: 100 + sample_every_steps: 100 + sample_steps: 2 + decode_videos: false + +checkpoint: + every_steps: 2 + preserve_steps: [2] + auto_resume: false + +logging: + every_steps: 1 + early_steps: 2 + swanlab_enabled: false + +runtime: + mode: smoke + max_steps: 2 diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v12_largebatch_remaining/train.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v12_largebatch_remaining/train.yaml new file mode 100644 index 0000000000000000000000000000000000000000..785714de1723cb5408fc438bf959701fecee8427 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v12_largebatch_remaining/train.yaml @@ -0,0 +1 @@ +extends: base.yaml diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v6/base.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v6/base.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d952cbdc63a262888f2591cd8dbbbbd88d42dba4 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v6/base.yaml @@ -0,0 +1,154 @@ +experiment: + name: robotwin_bihub_world_v6 + seed: 2026 + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v6_bootstrap + artifact_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6 + debug_smoke: false + +artifacts: + codec_checkpoint: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/mira_robotwin_codec/checkpoint-125000/checkpoint.pth + codec_sha256: c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615 + codec_config_sha256: 62eef9277469b198f8aac7eaba1f1c9101701e65d51648a89dc922dcdadf17c1 + latent_cache_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/latent_cache/c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615 + train_source_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/latent_cache/c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615/manifest_train.jsonl + val_source_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/latent_cache/c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615/manifest_val.jsonl + dataset_stats: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/datasets/RoboTwin2.0/mira_wam_aloha/dataset_stats.json + raw_dataset_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/datasets/RoboTwin2.0 + extracted_rgb_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/extracted_rgb_episodes + train_window_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/windows/train.jsonl + val_window_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/windows/val.jsonl + train_window_index: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/windows/train.source_index.i64 + val_window_index: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/windows/val.source_index.i64 + train_window_locator: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/windows/train.locators.i64 + val_window_locator: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/windows/val.locators.i64 + window_summary: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/windows/summary.json + source_checkpoint: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_3view_world_1b/checkpoint-80000 + source_selection_import: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/action_stage/world/world_selection.json + source_selection: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/source/v5_source_selection.json + migration_weights: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/migration/world_v6_initialized.safetensors + migration_report: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/migration/migration_report.json + qwen_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/models/Qwen3-VL-2B-Instruct + qwen_identity: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/identities/qwen_identity.json + resampler_selection: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/bootstrap/anchor_selection.json + anchor_cache_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/anchor_cache + anchor_cache_identity: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/anchor_cache/anchor_cache_identity.json + main_checkpoint_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v6 + +qwen: + repo: Qwen/Qwen3-VL-2B-Instruct + revision: 89644892e4d85e24eaac8bacfd4f463576704203 + dtype: bfloat16 + attention_implementation: sdpa + image_height: 288 + image_width: 384 + prompt_version: bihub-v6-role-v1 + add_generation_prompt: false + frozen: true + +data: + view_order: [left, global, right] + source_fps: 30 + video_fps: 20 + latent_fps: 10 + clean_probability: 0.5 + num_workers: 2 + prefetch_factor: 2 + episode_cache_size: 4 + +model: + latent_dim: 32 + latent_height: 9 + latent_width: 12 + context_latents: 10 + future_latents: 10 + hidden_size: 2048 + layers: 16 + query_heads: 16 + kv_heads: 4 + temporal_layers: [0, 4, 8, 12, 15] + attention_gating: true + qk_norm: layernorm + activation_checkpointing: true + latent_mean: 0.024823864160431405 + latent_std: 1.9595992324017892 + anchor: + qwen_hidden_size: 2048 + queries_per_view: 8 + width: 512 + heads: 8 + ffn_hidden: 2048 + layers: 1 + dropout: 0.0 + gate_init: 0.1 + history: + frames: 4 + pool_height: 3 + pool_width: 4 + width: 512 + heads: 8 + state: + hidden_size: 512 + layers: 2 + heads: 8 + history_steps: 20 + source_semantics: simulator_drive_target_not_measured_qpos + +distributed: + strategy: fsdp2_full_shard + per_device_batch: 1 + gradient_accumulation_steps: 4 + effective_global_batch: 32 + precision: bf16 + +optimizer: + betas: [0.9, 0.99] + eps: 1.0e-8 + weight_decay: 0.1 + grad_clip: 1.0 + ema_decay: 0.9999 + +bootstrap: + steps: 5000 + warmup_steps: 500 + lr_resampler: 2.0e-4 + lr_hhr_world_cross: 1.0e-4 + lr_state_adapter: 5.0e-5 + preserve_steps: [1000, 3000, 5000] + +training: + steps: 100000 + warmup_steps: 2000 + inherited_unfreeze_step: 2000 + inherited_unfreeze_ramp: 500 + lr_new: 1.0e-4 + lr_inherited: 2.0e-5 + min_lr_new: 1.0e-6 + min_lr_inherited: 2.0e-7 + +validation: + every_steps: 1000 + sample_every_steps: 5000 + fixed_seed: 2026 + batches: 16 + interventions: true + +checkpoint: + every_steps: 5000 + keep_last_recovery: 2 + preserve_steps: [80000, 90000, 100000] + atomic: true + auto_resume: true + +logging: + every_steps: 100 + early_steps: 10 + swanlab_enabled: true + swanlab_project: multi-wam + swanlab_experiment_name: RoboTwin-BiHub-World-v6-Bootstrap + swanlab_token_file: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/z_oranger/token.txt + +runtime: + phase: bootstrap + mode: formal + max_steps: null + max_windows_per_split: null diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v6/bootstrap.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v6/bootstrap.yaml new file mode 100644 index 0000000000000000000000000000000000000000..785714de1723cb5408fc438bf959701fecee8427 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v6/bootstrap.yaml @@ -0,0 +1 @@ +extends: base.yaml diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v6/cache.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v6/cache.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c62fd88d44e3f1acd216d6182591411c954dcf3f --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v6/cache.yaml @@ -0,0 +1,7 @@ +extends: base.yaml +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v6_cache +logging: + swanlab_enabled: false +runtime: + phase: cache diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v6/canary_bootstrap.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v6/canary_bootstrap.yaml new file mode 100644 index 0000000000000000000000000000000000000000..61144170042fdb36dee7003681e6bd9dabdfb8d0 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v6/canary_bootstrap.yaml @@ -0,0 +1,13 @@ +extends: bootstrap.yaml +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/world_v6_gates/bootstrap_canary200 +runtime: + phase: bootstrap + mode: canary + max_steps: 200 +bootstrap: + preserve_steps: [100, 200] +checkpoint: + every_steps: 100 +logging: + swanlab_enabled: false diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v6/canary_train.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v6/canary_train.yaml new file mode 100644 index 0000000000000000000000000000000000000000..85303f4863fe78ea0be928378044d552a040db86 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v6/canary_train.yaml @@ -0,0 +1,12 @@ +extends: train.yaml +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/world_v6_gates/main_canary200 +runtime: + phase: main + mode: canary + max_steps: 200 +checkpoint: + every_steps: 100 + preserve_steps: [100, 200] +logging: + swanlab_enabled: false diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v6/eval.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v6/eval.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b68d6ab55032b755e60397f8ded6f5c9d50d8a34 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v6/eval.yaml @@ -0,0 +1,11 @@ +extends: train.yaml +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v6_eval +distributed: + per_device_batch: 1 + gradient_accumulation_steps: 4 + effective_global_batch: 32 +logging: + swanlab_enabled: false +runtime: + phase: eval diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v6/overfit64.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v6/overfit64.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c22090de91c442d9dd90d84088031afd4e98041d --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v6/overfit64.yaml @@ -0,0 +1,31 @@ +extends: bootstrap.yaml +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/world_v6_gates/overfit64 + artifact_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6_overfit64 + debug_smoke: true +artifacts: + extracted_rgb_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6_overfit64/extracted_rgb_episodes + train_window_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6_overfit64/windows/train.jsonl + val_window_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6_overfit64/windows/val.jsonl + train_window_index: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6_overfit64/windows/train.source_index.i64 + val_window_index: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6_overfit64/windows/val.source_index.i64 + train_window_locator: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6_overfit64/windows/train.locators.i64 + val_window_locator: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6_overfit64/windows/val.locators.i64 + window_summary: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6_overfit64/windows/summary.json +distributed: + per_device_batch: 1 + gradient_accumulation_steps: 4 + effective_global_batch: 32 +bootstrap: + steps: 3000 + preserve_steps: [1000, 3000] +checkpoint: + every_steps: 1000 + preserve_steps: [1000, 3000] +logging: + swanlab_enabled: false +runtime: + phase: bootstrap + mode: overfit64 + max_steps: 3000 + max_windows_per_split: 64 diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v6/smoke_base.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v6/smoke_base.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f8cbd82485bf2f9e07fba537c28a0e2cdbf9496b --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v6/smoke_base.yaml @@ -0,0 +1,51 @@ +extends: base.yaml +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/world_v6_smoke/bootstrap + artifact_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6_smoke + debug_smoke: true +artifacts: + main_checkpoint_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/world_v6_smoke/main + extracted_rgb_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6_smoke/extracted_rgb_episodes + train_window_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6_smoke/windows/train.jsonl + val_window_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6_smoke/windows/val.jsonl + train_window_index: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6_smoke/windows/train.source_index.i64 + val_window_index: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6_smoke/windows/val.source_index.i64 + train_window_locator: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6_smoke/windows/train.locators.i64 + val_window_locator: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6_smoke/windows/val.locators.i64 + window_summary: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6_smoke/windows/summary.json + resampler_selection: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6_smoke/bootstrap/anchor_selection.json + anchor_cache_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6_smoke/anchor_cache + anchor_cache_identity: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6_smoke/anchor_cache/anchor_cache_identity.json +data: + num_workers: 0 + episode_cache_size: 2 +distributed: + per_device_batch: 1 + gradient_accumulation_steps: 1 + effective_global_batch: 2 +bootstrap: + steps: 1 + warmup_steps: 1 + preserve_steps: [1] +training: + steps: 1 + warmup_steps: 1 + inherited_unfreeze_step: 0 + inherited_unfreeze_ramp: 1 +validation: + every_steps: 1 + sample_every_steps: 1 + batches: 1 +checkpoint: + every_steps: 1 + keep_last_recovery: 1 + preserve_steps: [1] +logging: + every_steps: 1 + early_steps: 1 + swanlab_enabled: false +runtime: + phase: bootstrap + mode: smoke + max_steps: 1 + max_windows_per_split: 8 diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v6/smoke_bootstrap.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v6/smoke_bootstrap.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e5191e4ee88e8cebaef15e97c7db9d20cb02bf3b --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v6/smoke_bootstrap.yaml @@ -0,0 +1 @@ +extends: smoke_base.yaml diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v6/smoke_cache.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v6/smoke_cache.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c12e28f67078b182a7c6af299e5738b73e6dfff9 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v6/smoke_cache.yaml @@ -0,0 +1,5 @@ +extends: smoke_base.yaml +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/world_v6_smoke/cache +runtime: + phase: cache diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v6/smoke_eval.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v6/smoke_eval.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a034b9e78e69727c71e0232917efb89d7e6be018 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v6/smoke_eval.yaml @@ -0,0 +1,5 @@ +extends: smoke_train.yaml +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/world_v6_smoke/eval +runtime: + phase: eval diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v6/smoke_train.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v6/smoke_train.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a519848f277c9f48869daa5192818555a4eece2d --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v6/smoke_train.yaml @@ -0,0 +1,5 @@ +extends: smoke_base.yaml +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/world_v6_smoke/main +runtime: + phase: main diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v6/train.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v6/train.yaml new file mode 100644 index 0000000000000000000000000000000000000000..76b62a42424fa93110fb88dcd6b51ca5ceeb51be --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v6/train.yaml @@ -0,0 +1,11 @@ +extends: base.yaml +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v6 +distributed: + per_device_batch: 4 + gradient_accumulation_steps: 1 + effective_global_batch: 32 +logging: + swanlab_experiment_name: RoboTwin-BiHub-World-v6-Main +runtime: + phase: main diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v7/base.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v7/base.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4274d9d8e4cafc0adfdab27ddad32078ca323a58 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v7/base.yaml @@ -0,0 +1,116 @@ +experiment: + name: robotwin_bihub_world_v7_short_history + seed: 2026 + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v7_short_history + artifact_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v7 + debug_smoke: false + +artifacts: + codec_checkpoint: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/mira_robotwin_codec/checkpoint-125000/checkpoint.pth + codec_sha256: c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615 + train_source_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/latent_cache/c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615/manifest_train.jsonl + val_source_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/latent_cache/c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615/manifest_val.jsonl + dataset_stats: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/datasets/RoboTwin2.0/mira_wam_aloha/dataset_stats.json + qwen_identity: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/identities/qwen_identity.json + qwen_hidden_cache_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v7/qwen_hidden_cache + qwen_hidden_cache_identity: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v7/qwen_hidden_cache/qwen_hidden_cache_identity.json + v6_system_weights: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/bootstrap/bootstrap_system_ema.safetensors + v6_resampler_selection: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/bootstrap/anchor_selection.json + v6_checkpoint: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v6/main-checkpoint-97314 + +data: + view_order: [left, global, right] + history_lengths: [1, 3, 6, 10] + clean_probability: 0.5 + num_workers: 0 + prefetch_factor: 2 + episode_cache_size: 4 + mapping_cache_size: 64 + +model: + latent_dim: 32 + latent_height: 9 + latent_width: 12 + context_latents: 10 + future_latents: 10 + hidden_size: 2048 + layers: 16 + query_heads: 16 + kv_heads: 4 + temporal_layers: [0, 4, 8, 12, 15] + attention_gating: true + qk_norm: layernorm + activation_checkpointing: true + latent_mean: 0.024823864160431405 + latent_std: 1.9595992324017892 + anchor: + qwen_hidden_size: 2048 + queries_per_view: 8 + width: 512 + heads: 8 + ffn_hidden: 2048 + layers: 1 + dropout: 0.0 + gate_init: 0.1 + history: + frames: 4 + pool_height: 3 + pool_width: 4 + width: 512 + heads: 8 + state: + hidden_size: 512 + layers: 2 + heads: 8 + history_steps: 20 + source_semantics: simulator_drive_target_not_measured_qpos + +distributed: + strategy: fsdp2_full_shard + per_device_batch: 4 + gradient_accumulation_steps: 1 + effective_global_batch: 32 + precision: bf16 + +optimizer: + betas: [0.9, 0.99] + eps: 1.0e-8 + weight_decay: 0.1 + grad_clip: 1.0 + ema_decay: 0.9999 + +training: + steps: 25000 + warmup_steps: 500 + adapter_only_steps: 1500 + world_unfreeze_ramp: 500 + lr_resampler: 2.0e-5 + lr_condition: 1.0e-5 + lr_world: 2.0e-6 + min_lr_ratio: 0.1 + +validation: + every_steps: 500 + sample_every_steps: 2000 + fixed_seed: 2026 + sample_steps: 10 + decode_videos: true + +checkpoint: + every_steps: 1000 + keep_last_recovery: 2 + preserve_steps: [5000, 15000, 25000] + auto_resume: true + +logging: + every_steps: 50 + early_steps: 10 + swanlab_enabled: true + swanlab_project: multi-wam + swanlab_experiment_name: RoboTwin-BiHub-World-v7-ShortHistory-25k + swanlab_token_file: /public/interns/haocheng/Oranger/project/multi_wam/z_tmp/swanlab_token.txt + +runtime: + phase: main + mode: formal + max_steps: null diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v7/smoke.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v7/smoke.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fc1237a77de9a713bd17a5a6b8f1e4a8c34d8c4c --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v7/smoke.yaml @@ -0,0 +1,23 @@ +extends: base.yaml +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/world_v7_smoke + debug_smoke: true +distributed: + per_device_batch: 1 + gradient_accumulation_steps: 1 + effective_global_batch: 8 +validation: + every_steps: 1 + sample_every_steps: 2 + sample_steps: 2 + decode_videos: false +checkpoint: + every_steps: 1 + preserve_steps: [1, 2] +logging: + every_steps: 1 + early_steps: 2 + swanlab_enabled: false +runtime: + mode: smoke + max_steps: 2 diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v7/train.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v7/train.yaml new file mode 100644 index 0000000000000000000000000000000000000000..785714de1723cb5408fc438bf959701fecee8427 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v7/train.yaml @@ -0,0 +1 @@ +extends: base.yaml diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v8/base.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v8/base.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5c811c28e42a6a360aca4dd3350d27c25ff10e2a --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v8/base.yaml @@ -0,0 +1,116 @@ +experiment: + name: robotwin_bihub_world_v8_h1_priority_online + seed: 2026 + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v8_h1_priority_online + artifact_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v8 + debug_smoke: false + +artifacts: + codec_checkpoint: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/mira_robotwin_codec/checkpoint-125000/checkpoint.pth + codec_sha256: c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615 + train_source_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/latent_cache/c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615/manifest_train.jsonl + val_source_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/latent_cache/c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615/manifest_val.jsonl + dataset_stats: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/datasets/RoboTwin2.0/mira_wam_aloha/dataset_stats.json + qwen_identity: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v6/identities/qwen_identity.json + qwen_hidden_cache_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v7/qwen_hidden_cache + qwen_hidden_cache_identity: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v7/qwen_hidden_cache/qwen_hidden_cache_identity.json + source_checkpoint: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v7_short_history/main-checkpoint-25000 + fixed_case_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/mira/configs/world_v8/fixed_cases.json + +data: + view_order: [left, global, right] + history_lengths: [1, 3, 6, 10] + history_probabilities: [0.4, 0.2, 0.2, 0.2] + history_cycle: [1, 1, 3, 6, 10] + clean_probability: 0.5 + num_workers: 0 + prefetch_factor: 2 + episode_cache_size: 4 + mapping_cache_size: 64 + +model: + latent_dim: 32 + latent_height: 9 + latent_width: 12 + context_latents: 10 + future_latents: 10 + hidden_size: 2048 + layers: 16 + query_heads: 16 + kv_heads: 4 + temporal_layers: [0, 4, 8, 12, 15] + attention_gating: true + qk_norm: layernorm + activation_checkpointing: true + latent_mean: 0.024823864160431405 + latent_std: 1.9595992324017892 + anchor: + qwen_hidden_size: 2048 + queries_per_view: 8 + width: 512 + heads: 8 + ffn_hidden: 2048 + layers: 1 + dropout: 0.0 + gate_init: 0.1 + history: + frames: 4 + pool_height: 3 + pool_width: 4 + width: 512 + heads: 8 + state: + hidden_size: 512 + layers: 2 + heads: 8 + history_steps: 20 + source_semantics: simulator_drive_target_not_measured_qpos + +distributed: + strategy: fsdp2_full_shard + per_device_batch: 5 + gradient_accumulation_steps: 1 + effective_global_batch: 40 + precision: bf16 + +optimizer: + betas: [0.9, 0.99] + eps: 1.0e-8 + weight_decay: 0.1 + grad_clip: 1.0 + +training: + steps: 20000 + warmup_steps: 500 + full_finetune_from_step: 1 + lr_resampler: 1.0e-5 + lr_condition: 5.0e-6 + lr_world: 1.0e-6 + min_lr_ratio: 0.1 + +validation: + every_steps: 500 + fixed_cases: 6 + sample_every_steps: 2000 + fixed_seed: 2026 + sample_steps: 10 + decode_videos: true + +checkpoint: + every_steps: 1000 + keep_last_recovery: 2 + preserve_steps: [5000, 10000, 15000, 20000] + auto_resume: true + +logging: + every_steps: 50 + early_steps: 10 + swanlab_enabled: true + swanlab_project: multi-wam + swanlab_experiment_name: RoboTwin-BiHub-World-v8-H1Priority-Online-20k + swanlab_token_file: /public/interns/haocheng/Oranger/project/multi_wam/z_tmp/swanlab_token.txt + +runtime: + phase: main + mode: formal + max_steps: null diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v8/fixed_cases.json b/release-20261107/source/workspace_joint/mira/configs/world_v8/fixed_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..01d5218ef3221b4c66748e9925d992e80f5b91c9 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v8/fixed_cases.json @@ -0,0 +1,55 @@ +{ + "format_version": 1, + "selection": "six_fixed_h1_cases_three_clean_three_randomized_unique_tasks", + "cases": [ + { + "case_id": 0, + "base_global": 0, + "episode_sha256": "669a2a18437552e4fff8289982ac59a62c1115265046d36080ebcc1f304621e8", + "latent_start": 0, + "task": "adjust_bottle", + "domain": "clean", + "purpose": "retain_v7_rank00_failure_for_longitudinal_comparison" + }, + { + "case_id": 1, + "base_global": 4817, + "episode_sha256": "ee7c7389d07972a076213e3ffd5beb9c2f89125d3e937d7ea770afd6953cf426", + "latent_start": 37, + "task": "handover_block", + "domain": "randomized" + }, + { + "case_id": 2, + "base_global": 11448, + "episode_sha256": "63797242ce5b5860cd1f335a4381d795b4d4a151f71ecf414137d2b74992c8d8", + "latent_start": 14, + "task": "place_a2b_right", + "domain": "clean" + }, + { + "case_id": 3, + "base_global": 2338, + "episode_sha256": "01c42064fbcf0eee5014eaa2142dcb3ccc820dc3d60b3307b7f4cdda657b4c91", + "latent_start": 67, + "task": "blocks_ranking_size", + "domain": "randomized" + }, + { + "case_id": 4, + "base_global": 589, + "episode_sha256": "d6c12ea7a25502a7403110db4e5bd812c15b64360a5a69554c45d4a55930a161", + "latent_start": 66, + "task": "blocks_ranking_rgb", + "domain": "clean" + }, + { + "case_id": 5, + "base_global": 27271, + "episode_sha256": "1f619ecb5791d8ffaaffe47c3fbccc194ea97db0ccdf9006515d4e754ccc77c9", + "latent_start": 65, + "task": "stack_bowls_three", + "domain": "randomized" + } + ] +} diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v8/smoke.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v8/smoke.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e4c877772bb98ddca2876856e68c919e9059a73d --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v8/smoke.yaml @@ -0,0 +1,19 @@ +extends: base.yaml +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/world_v8_smoke + debug_smoke: true +validation: + every_steps: 1 + sample_every_steps: 2 + sample_steps: 2 + decode_videos: false +checkpoint: + every_steps: 1 + preserve_steps: [1, 2] +logging: + every_steps: 1 + early_steps: 2 + swanlab_enabled: false +runtime: + mode: smoke + max_steps: 2 diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v8/train.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v8/train.yaml new file mode 100644 index 0000000000000000000000000000000000000000..785714de1723cb5408fc438bf959701fecee8427 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v8/train.yaml @@ -0,0 +1 @@ +extends: base.yaml diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v9_episode_start/base.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v9_episode_start/base.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c55a775976075c73c43a0aebaa4bc80982078ae3 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v9_episode_start/base.yaml @@ -0,0 +1,56 @@ +extends: ../world_v8/base.yaml + +experiment: + name: robotwin_bihub_world_v9_episode_start_h1 + architecture: bihub-world-v9-episode-start-h1-online + process_prefix: tagshotx_wv9 + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/robotwin_bihub_world_v9_episode_start_h1 + artifact_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v9_episode_start + debug_smoke: false + +artifacts: + source_checkpoint: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/artifacts/world_v9_episode_start/source-checkpoint-8000 + source_checkpoint_step: 8000 + source_checkpoint_architecture: bihub-world-v8-h1-priority-online + fixed_case_manifest: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/mira/configs/world_v9_episode_start/fixed_cases.json + +data: + h1_episode_start_only: true + +training: + steps: 20000 + initial_step: 8000 + warmup_steps: 300 + full_finetune_from_step: 1 + lr_resampler: 4.0e-6 + lr_condition: 2.0e-6 + lr_world: 4.0e-7 + min_lr_ratio: 0.1 + +validation: + every_steps: 500 + fixed_cases: 6 + episode_start_cases: 4 + sample_every_steps: 2000 + fixed_seed: 2026 + sample_steps: 10 + decode_videos: true + +checkpoint: + every_steps: 1000 + keep_last_recovery: 2 + preserve_steps: [10000, 12000, 14000, 16000, 18000, 20000] + auto_resume: true + +logging: + every_steps: 50 + early_steps: 10 + swanlab_enabled: true + swanlab_project: multi-wam + swanlab_experiment_name: RoboTwin-BiHub-World-v9-EpisodeStartH1-8kTo20k + swanlab_token_file: /public/interns/haocheng/Oranger/project/multi_wam/z_tmp/swanlab_token.txt + +runtime: + phase: main + mode: formal + max_steps: null diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v9_episode_start/fixed_cases.json b/release-20261107/source/workspace_joint/mira/configs/world_v9_episode_start/fixed_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..aec9b888adab212812cff45a3a6d8f9c92da291b --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v9_episode_start/fixed_cases.json @@ -0,0 +1,60 @@ +{ + "format_version": 2, + "selection": "first_four_episode_start_h1_unique_tasks_plus_two_mid_episode_regression_cases", + "cases": [ + { + "case_id": 0, + "base_global": 0, + "episode_sha256": "669a2a18437552e4fff8289982ac59a62c1115265046d36080ebcc1f304621e8", + "latent_start": 0, + "task": "adjust_bottle", + "domain": "clean", + "purpose": "episode_start_known_failure" + }, + { + "case_id": 1, + "base_global": 4780, + "episode_sha256": "ee7c7389d07972a076213e3ffd5beb9c2f89125d3e937d7ea770afd6953cf426", + "latent_start": 0, + "task": "handover_block", + "domain": "randomized", + "purpose": "episode_start_cross_task" + }, + { + "case_id": 2, + "base_global": 11434, + "episode_sha256": "63797242ce5b5860cd1f335a4381d795b4d4a151f71ecf414137d2b74992c8d8", + "latent_start": 0, + "task": "place_a2b_right", + "domain": "clean", + "purpose": "episode_start_cross_task" + }, + { + "case_id": 3, + "base_global": 2271, + "episode_sha256": "01c42064fbcf0eee5014eaa2142dcb3ccc820dc3d60b3307b7f4cdda657b4c91", + "latent_start": 0, + "task": "blocks_ranking_size", + "domain": "randomized", + "purpose": "episode_start_cross_task" + }, + { + "case_id": 4, + "base_global": 589, + "episode_sha256": "d6c12ea7a25502a7403110db4e5bd812c15b64360a5a69554c45d4a55930a161", + "latent_start": 66, + "task": "blocks_ranking_rgb", + "domain": "clean", + "purpose": "mid_episode_regression_guard" + }, + { + "case_id": 5, + "base_global": 27271, + "episode_sha256": "1f619ecb5791d8ffaaffe47c3fbccc194ea97db0ccdf9006515d4e754ccc77c9", + "latent_start": 65, + "task": "stack_bowls_three", + "domain": "randomized", + "purpose": "mid_episode_regression_guard" + } + ] +} diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v9_episode_start/smoke.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v9_episode_start/smoke.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ace844e60f0bd1c184e718dc62fb5af2d2d6a657 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v9_episode_start/smoke.yaml @@ -0,0 +1,24 @@ +extends: base.yaml + +experiment: + output_root: /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/outputs/world_v9_episode_start_smoke + debug_smoke: true + +validation: + every_steps: 1 + sample_every_steps: 1 + sample_steps: 2 + decode_videos: false + +checkpoint: + every_steps: 1 + preserve_steps: [8001, 8002] + +logging: + every_steps: 1 + early_steps: 2 + swanlab_enabled: false + +runtime: + mode: smoke + max_steps: 8002 diff --git a/release-20261107/source/workspace_joint/mira/configs/world_v9_episode_start/train.yaml b/release-20261107/source/workspace_joint/mira/configs/world_v9_episode_start/train.yaml new file mode 100644 index 0000000000000000000000000000000000000000..785714de1723cb5408fc438bf959701fecee8427 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/configs/world_v9_episode_start/train.yaml @@ -0,0 +1 @@ +extends: base.yaml diff --git a/release-20261107/source/workspace_joint/mira/docs/action_head_stage/README.md b/release-20261107/source/workspace_joint/mira/docs/action_head_stage/README.md new file mode 100644 index 0000000000000000000000000000000000000000..07fac3a81ca2887acd94ecbc11306949b3ebd3a3 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/docs/action_head_stage/README.md @@ -0,0 +1,113 @@ +# RoboTwin 3-View Joint Action Head + +This stage freezes the selected World checkpoint and trains one joint bimanual +`20 x 14` rectified-flow policy. Its inputs are the last factual three-view latent, +ten imagined future latent cells, the 20-step factual drive-target history, and the +instruction embedding. + +The formal Action model is width 1024, 16 transformer blocks, 16 attention heads, +SwiGLU width 4096, bidirectional action self-attention, and separate cross-attention +to World and task/state memories. It has 622,247,773 total parameters and +622,247,759 trainable parameters. The 14 non-trainable values are the copied +World encoder's compatibility-only action BOS tensor; the selected World branch +does not use action history, so that tensor is structurally unreachable. + +The single supported entry point is: + +```bash +cd mira +bash scripts/launch_action_head.sh +``` + +The launcher clears all proxy variables and uses direct connections. All current +coexistence commands are locked to physical GPUs `6,7`. + +## Reproducible smoke + +```bash +bash scripts/launch_action_head.sh prepare-smoke +bash scripts/launch_action_head.sh smoke +bash scripts/launch_action_head.sh smoke-resume-check +bash scripts/launch_action_head.sh eval-smoke +``` + +`smoke` uses the exact formal architecture with a two-rank FSDP2 layout and a +compressed curriculum. It covers GT-only, mixed GT/predicted, predicted-only, +whole-future dropout, online/EMA validation, fixed-case trajectory rendering, and +atomic checkpoint save. `smoke-resume-check` restores all distributed state and +continues one step. `eval-smoke` tests all offline intervention paths with fixed +initial action noise. `smoke-batch8-probe` tests the formal per-device batch on the +two authorized GPUs without saving a checkpoint. + +## Formal artifact and training pipeline + +Run these stages in order: + +```bash +bash scripts/launch_action_head.sh prepare-formal-manifest +MIRA_ACTION_FORMAL_SELECTION_GPU=6 \ + bash scripts/launch_action_head.sh select-formal-world +bash scripts/launch_action_head.sh build-formal-future +``` + +Future-cache construction is resumable at shard and row level. The current +two-GPU launcher assigns the eight shards alternately to physical GPUs 6 and 7. +It never regenerates a shard carrying a valid `COMPLETE` marker. + +Formal training deliberately requires an explicit list of eight GPUs: + +```bash +MIRA_ACTION_FORMAL_GPUS=0,1,2,3,4,5,6,7 \ + bash scripts/launch_action_head.sh tmux-formal +``` + +The launcher refuses a shorter list instead of silently changing global batch +or optimization semantics. Formal training uses: + +- 100,000 optimizer steps and effective global batch 128; +- per-device batch 8, gradient accumulation 2, two flow-noise repeats; +- AdamW main LR `1e-4`, copied-state LR `2e-5`, 2,000-step warmup, cosine decay; +- GT future through step 5,000, linear transition through 20,000, then predicted-only; +- EMA 0.9999, predicted-only fixed validation, local JSONL and compact SwanLab scalars; +- checkpoint and fixed trajectory cases every 5,000 steps. + +An optimization-equivalent two-GPU layout is also available for GPU 6/7 +coexistence runs: + +```bash +bash scripts/launch_action_head.sh tmux-formal-2gpu +``` + +It keeps per-device batch 8 and effective global batch 128, changing only gradient +accumulation from 2 to 8. The model, sample order, curriculum, LR schedule, EMA, +validation, and total optimizer steps are unchanged. + +When the full predicted-future cache is not ready, the safe staged launcher is: + +```bash +bash scripts/launch_action_head.sh tmux-formal-2gpu-warmup +bash scripts/launch_action_head.sh tmux-wait-warmup-pipeline-2gpu +``` + +The first command trains the exact GT-only curriculum through step 5,000 and then +atomically exits. It never selects a missing predicted future and skips rather than +leaks GT into predicted-future validation. The second command waits without using a +GPU, builds the deterministic full cache, and resumes the same checkpoint/SwanLab +run for transition and predicted-only training. + +After a formal checkpoint exists: + +```bash +MIRA_ACTION_EVAL_CHECKPOINT=/absolute/checkpoint-path \ + bash scripts/launch_action_head.sh eval-formal +``` + +The offline evaluator reports correct/GT/null/same-task shuffle/cross-task shuffle/ +time reverse/persistence/three view-drop conditions, repeat-last and training-task +mean baselines, paired bootstrap intervals, and local trajectory plots. It uses one +fixed action-noise sample per window across every intervention; no best-of-K oracle +enters the primary result. + +See [compatibility_map.md](compatibility_map.md) for immutable tensor/data +contracts and [deployment_and_smoke_report.md](deployment_and_smoke_report.md) +for the verified server result and plan adjustments. diff --git a/release-20261107/source/workspace_joint/mira/docs/action_head_stage/compatibility_map.md b/release-20261107/source/workspace_joint/mira/docs/action_head_stage/compatibility_map.md new file mode 100644 index 0000000000000000000000000000000000000000..58982192e594ff7499a77275f24e17642190684e --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/docs/action_head_stage/compatibility_map.md @@ -0,0 +1,105 @@ +# Action Stage Compatibility Map + +## Locked upstream + +| Contract | Deployed value | +|---|---| +| World checkpoint | completed step 80,000 | +| World parameters | 1,397,471,023 | +| selected branch | EMA, chosen by paired standardized future-latent MSE | +| views | left, global, right | +| World context/future | `[3,10,32,9,12]` each | +| World sampler | 10-step Euler, linear-quadratic schedule | +| latent standardization | mean `0.024823864160431405`, std `1.9595992324017892` | +| copied state encoder | exact selected-branch state dict, independent Action parameters | + +The selection file pins the World DCP metadata, trainer metadata, selected tensor +state, and copied state-encoder SHA-256 values. Every future-cache worker reloads +and hashes the selected branch before rollout. Training then checks all upstream, +manifest, statistics, and future-cache identities again. + +## Time and action semantics + +One Action window derives from one existing World window: + +```text +factual video/state history = d20[0:20] +action target = d20[20:40] +context latent cells = latent[0:10] +current latent = latent[9] +future latent cells = latent[10:20] +``` + +The absolute 14D order is: + +```text +left joints 0..5, left gripper, right joints 0..5, right gripper +``` + +Both state and action are simulator drive targets, not measured qpos and not +deltas. The manifest stores exact 30-to-20 FPS half-up source indices and asserts: + +- 20 factual and 20 target indices exist; +- the first target index is strictly after the last factual index; +- action indices exactly equal future-video indices; +- no time interpolation or one-step shift is permitted. + +## Memories and model shapes + +| Memory | Shape/tokens | +|---|---| +| current latent | full `[3,32,9,12]`, 324 tokens | +| predicted/GT future | pooled `[3,10,32,3,4]`, 360 tokens | +| copied state memory | left 20 + right 20 + global 1 = 41 tokens | +| text | real cached instruction embedding, at most 128 tokens | +| noisy action | `[20,14]`, 20 bidirectional tokens | + +Current and future latent use one shared channel projector plus separate source, +view, time, and coordinate embeddings. Future dropout replaces the whole future +group with one valid learned null token; it never drops independent future cells. + +The copied World state encoder was trained with `use_action_history=false`. +Therefore its 14-value `bos_action` parameter remains in the strict state dict but +is non-trainable and excluded from Action AdamW/EMA. All reachable copied-state +parameters train at 0.2 times the main learning rate. + +## Cache contract + +The predicted-future cache stores one FP16 row as: + +```text +[view=3, future_time=10, channel=32, height=3, width=4] +``` + +Each row is a real 10-step rollout from the locked World branch, standardized in +World latent space and then average-pooled from `9x12` to `3x4`. Seeds derive from +the World tensor hash, split, immutable window ID, solver settings, and base seed. +Every shard has a completion bitmap, ordered-window digest, tensor digest, +finite check, metadata, and atomic `COMPLETE` marker. + +## Loss and sampling + +Flow direction is noise at time zero to action data at time one: + +```text +t = (1 - Beta(alpha=1.5, beta=1.0)) * 0.999 +x_t = (1-t) * noise + t * action +target velocity = action - noise +``` + +One scalar time is shared by every element of a trajectory. Training uses two +independent noise repeats and masked FP32 MSE with separate arm/gripper metrics. +Inference uses fixed-step Euler integration; formal sampling uses 10 steps. + +## Resume and deployment invariants + +- FSDP2 full-shard checkpoints atomically save model, optimizer, EMA, scheduler, + balanced sampler, Python/NumPy/Torch/CUDA RNG, config, and artifact identities. +- Exact training resume requires the same rank count and rejects any artifact + identity mismatch. +- Validation after curriculum construction always uses cached predicted future. +- The policy runtime exposes no operation that can append imagined future to the + factual observation buffer. +- A queued waypoint cannot be followed by another waypoint until its returned + real RGB/state observation has been recorded. +- Unexecuted action tails are diagnostic only and never become state history. diff --git a/release-20261107/source/workspace_joint/mira/docs/action_head_stage/deployment_and_smoke_report.md b/release-20261107/source/workspace_joint/mira/docs/action_head_stage/deployment_and_smoke_report.md new file mode 100644 index 0000000000000000000000000000000000000000..fd1b92d73fe061fd8e851bfe85f46f80e31b847e --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/docs/action_head_stage/deployment_and_smoke_report.md @@ -0,0 +1,136 @@ +# Action Head Deployment and Smoke Report + +## Implemented result + +The Action stage now has a complete local data-to-evaluation path: + +1. immutable Action manifest and train-only action statistics; +2. paired World online/EMA selection and exact copied state encoder; +3. deterministic, resumable predicted-future cache; +4. 622M joint bimanual Action Flow under FSDP2; +5. curriculum training, differential LR, EMA, validation, visualization, SwanLab, + and atomic resume; +6. fixed-noise offline intervention evaluation and simple baselines; +7. factual-memory RoboTwin policy core with queue, safety, and latency contracts. + +No codec, World, dataset, or Action artifact is downloaded by this stage. + +## Upstream selection + +The smoke selection compared online and EMA on paired windows using identical +noise. EMA was selected automatically: + +```text +online standardized future-latent MSE: 0.115074 +EMA standardized future-latent MSE: 0.099187 +EMA - online: -0.015887 +bootstrap 95% CI: [-0.017858, -0.013917] +``` + +All three EMA view errors also passed the no-regression gate. The small smoke uses +two paired cases only to verify code; formal selection is configured for 64 cases +and must be run before the full cache. + +## Verified smoke + +Only physical GPUs 6 and 7 were made visible. Existing jobs on those devices were +left running. The final run passed: + +- Ruff static checks; +- 9 Action/policy tests; +- two-rank FSDP2 initialization and optimization; +- GT, mixed GT/predicted, predicted-only, and whole-future dropout paths; +- online and EMA predicted-future validation; +- fixed PNG/NPZ/JSON trajectory generation; +- atomic distributed checkpoint save; +- exact resume from step 6 to step 7; +- offline EMA loading and all planned future interventions. + +The step-6 smoke included one GT and one predicted sample in the same optimizer +step. Steps 5–7 used predicted future only. All train, gradient, validation, and +sampling values were finite. + +Observed Action-process CUDA peaks: + +| Probe | Per-device batch | FSDP ranks | peak allocated per process | +|---|---:|---:|---:| +| curriculum/resume smoke | 1 | 2 | 7.36 GiB | +| formal local-batch probe | 8 | 2 | 7.56 GiB | + +The batch-8 probe is conservative for parameter/optimizer sharding because formal +training uses eight ranks. It is not a substitute for an eight-GPU canary and does +not predict memory used by unrelated co-resident jobs. During the probe, each +authorized physical GPU still reported roughly 58 GiB free before launch. + +The seven-step checkpoint is deliberately not an effectiveness experiment. +Its future-intervention action differences are near zero because the zero-initialized +velocity head has barely trained. This confirms deterministic plumbing only; no +future-use or policy-quality claim is made from smoke metrics. + +## Adjustments made during deployment + +The initial plan was changed only where the live repository or current resource +authorization required it: + +1. The requested smoke ran on GPUs 6 and 7, not the plan's eight-GPU canary. + Architecture and per-device batch were separately kept/tested. The later + two-GPU formal layout preserves global batch 128 through accumulation 8. +2. The World checkpoint's EMA state retained activation-checkpoint wrapper names + whereas its online DCP state was canonical. Loading now reconstructs that exact + storage schema and canonicalizes only after a strict load. +3. The copied World encoder has `use_action_history=false`; its `bos_action` is + unreachable. It remains in checkpoints for strict source compatibility but is + frozen and omitted from AdamW/EMA. This fixed exact optimizer resume without + allowing partial model or optimizer loads. +4. The smoke curriculum is compressed to six steps so every condition branch is + exercised. Formal 5k/20k boundaries are unchanged. Checkpoint phase labels and + protected curriculum checkpoints now derive from config rather than hard-coded + smoke-incompatible values. +5. Training statistics now include a per-task mean 20x14 chunk baseline. An unseen + validation task falls back to the train-global mean chunk rather than leaking + validation targets or failing. +6. Formal predicted-future construction uses eight resumable shards scheduled over + the currently authorized GPUs 6 and 7. This affects preprocessing wall time only; + tensor values, seed rules, and training exposure are unchanged. + +## What is not yet complete + +The 100k run is active, but the full predicted-future cache, post-5k training, and +RoboTwin simulator canary are not yet complete. The policy core has unit-tested +factual-memory and current-only behavior, but closed-loop success rates require the +trained Action checkpoint and official simulator evaluator. + +## Two-GPU formal run update — 2026-07-30 + +The server later authorized physical GPUs 6 and 7 for a coexistence formal run. +The deployed layout keeps effective global batch 128 with per-device batch 8 and +gradient accumulation 8. A two-step full-accumulation canary passed, followed by +the real GT-only formal run. + +At step 100: + +```text +loss_action_flow = 2.009600 +grad_norm = 2.547 +throughput = 30.06 windows/s +Action CUDA peak = 7.56 GiB/rank +physical GPU free memory = approximately 32.7 GiB/card +``` + +SwanLab run: + +```text +https://swanlab.cn/@Oranger/Multi_WAM/runs/e404aa809e304d2cb754c +``` + +The full cache plan covers 1,472,828 train and 29,668 validation windows. Because +World-cache generation and Action training competed heavily at 100% GPU +utilization, deployment uses staged scheduling: Action GT-only warm-up first, +then batch-32 cache generation, then exact resume at step 5,000. This preserves +the curriculum while reducing total contention and OOM risk. + +The full action distribution exceeded the original Gaussian global `|z|>5` +review threshold in several dimensions. All action targets remained inside the +audited source drive-target ranges, so no episodes were removed. The deployed +policy records the ratios and retains the existing normalized ±5 clipping. This +avoids deleting valid rare-task poses from a multi-modal task mixture. diff --git a/release-20261107/source/workspace_joint/mira/docs/bihub_wam_stage_w_pipeline.md b/release-20261107/source/workspace_joint/mira/docs/bihub_wam_stage_w_pipeline.md new file mode 100644 index 0000000000000000000000000000000000000000..3d67cd8a3b2553f29ac470391312f9c5abecf30a --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/docs/bihub_wam_stage_w_pipeline.md @@ -0,0 +1,361 @@ +# RoboTwin 三视角 BiHub World Model:设计、部署与运行手册 + +状态:代码与 8 卡 pipeline 已通过 +最后核对:2026-07-19 +配置入口:[`configs/train_bihub_wam_world.yaml`](../configs/train_bihub_wam_world.yaml) +统一入口:[`scripts/launch_bihub_wam_world.sh`](../scripts/launch_bihub_wam_world.sh) + +## 1. 当前阶段边界 + +当前只训练 world model: + +```text +p(Z_future | Z_context, left/right target history, instruction) +``` + +不包含 action head,不把 future state/action 放进 batch,也不创建隐藏的 current-only action +分支。等 world model 通过长期 rollout、state/text sensitivity 和 persistence baseline 后,再进入 +WAM action 阶段。这样可以把视觉动力学问题与 inverse-dynamics 问题分开定位。 + +正式模型采用 MIRA 官方 1B backbone 几何,共 1,397,471,023 个可训练参数: + +- world transformer:1,387,463,200; +- two-arm state encoder:10,007,823; +- hidden dim 2048、16 blocks、16 Q heads、4 KV heads; +- temporal attention 位于 blocks `[0,4,8,12,15]`。 + +此前 5.272B 运行保留在 `../outputs/bihub_wam_world_5b` 作为实验归档。当前正式运行使用全新 +输出目录,从随机初始化开始,不加载旧 model、optimizer、scheduler 或 EMA。 + +## 2. 数据流与时间契约 + +```text +RoboTwin zip/HDF5 + └─ ALOHA episode 全字段审计、复用 codec split + ├─ 3 cameras: left/head/right + ├─ 14D simulator drive target + └─ 30→20 FPS half-up alignment + ├─ frozen codec EMA → 3 × raw latent cache at 10 Hz + ├─ frozen Wan UMT5 → instruction token cache + └─ task-first/domain-balanced sampler + └─ [10 context + 10 future] latent + 20 target-history + └─ FSDP2 BiHub flow matching +``` + +单样本 batch 契约: + +```text +world_context_raw: [B,3,10,32,9,12] +world_future_raw: [B,3,10,32,9,12] +joint_target_history: [B,20,2,7] +action_history: [B,20,2,7] # Stage W 默认不使用,冻结后续接口 +history_valid: [B,20] +text_hidden: [B,L<=128,4096] +text_mask: [B,L<=128] +future_valid: [B,10] +view_valid: [B,3] +``` + +字段语义和 codec hash 见 +[`robotwin_lingbot_codec_interface_contract.md`](robotwin_lingbot_codec_interface_contract.md)。 + +### 相对初始方案的重要修正 + +初始方案把 `joint_action/vector` 当作 qpos。核对 RoboTwin simulator 采集源码后,确认该字段是 +drive target。实现因此使用 `joint_target_state` 命名,并在 manifest、safetensors metadata、 +loader 和 audit 中强制写入 `simulator_drive_target_not_measured_qpos`。这不会影响 Stage W 的 +工程有效性,但意味着以后部署到真实机器人时要处理 target-state 与 measured-state 的 domain gap。 + +## 3. 数据审计与缓存 + +### 3.1 raw manifest + +正式 raw audit 只选 `aloha-agilex`,并对每个 episode 检查: + +- 三相机、vector 和四个 component 的帧数完全同步; +- vector 可由 component 精确重建; +- 所有 target 有限; +- 至少存在一个完整的 10+10 latent window; +- episode hash 在 train/val 零重叠; +- task/domain 分布和拒绝原因写入 summary。 + +`--max-episodes-per-split` 只用于 smoke,summary 会标为 incomplete;正式 trainer 和 launcher +会拒绝该 manifest。 + +instruction 优先使用可选的官方 task template,并用 episode `scene_info` 填充 arm/object;无 +catalog 时也会生成包含 task、arm 和 object 的 scene-grounded fallback,而不是只保留 task slug。 + +### 3.2 text cache + +冻结模型为 Wan UMT5-XXL: + +```text +repository: Wan-AI/Wan2.2-TI2V-5B +revision: 921dbaf3f1674a56f47e83fb80a34bac8a8f203e +location: ../models/wan-umt5-xxl +hidden: BF16 [L,4096], L<=128 +``` + +正式 trainer 拒绝 deterministic debug embedding。tokenizer、权重内容 hash、revision、原始 +instruction 和 mask 都进入 cache provenance。 + +### 3.3 latent cache + +使用 codec `checkpoint-125000` 的 EMA 权重。每个视角独立编码;长 episode 使用偶数对齐的 +40-frame block,重叠 latent 必须一致,绝不 padding future。 + +正式启动脚本把 episode 分为 8 个稳定 shard,并行使用 8 GPU。每个 rank 只写自己的 shard +manifest;全部 rank 成功后才按原 raw manifest 顺序严格合并。中断后已有 episode safetensors +会被复用。任一 shard 缺失、重复 episode 或覆盖不完整都会阻止 final manifest 生成。 + +每个 cache rank 显式使用 8 个 PyTorch CPU 线程。未限流时,每个 rank 创建约 161 个线程,8 个 +rank 竞争 96 个物理核,实测总吞吐只有约 5.4–6.0 episode/min;限流后每个 rank 的线程总数 +约 80(包含 CUDA 后台线程),稳定总吞吐约 152 episode/min。对优化前已缓存 episode 重新编码, +BF16 latent 逐元素完全一致(max/mean absolute error 均为 0),因此可安全混合复用。 + +三视角合并为同一 encoder batch 的候选实现保留为显式 opt-in,但正式 pipeline 默认禁用。A/B +虽在短 episode 上达到 1.49× 单例加速,却产生 max `0.1328125`、P99 `0.03125` 的 latent +差异;为避免同一 codec hash 下混入不同数值路径,本次正式 cache 只使用逐视角顺序编码。 + +## 4. BiHub 模型 + +视角顺序永远显式保留为 `[left, global, right]`。每个 block 的空间通信图为: + +```text +left ──► global ◄── right +left ◄── global ──► right +``` + +global 先从三视角 gather,left/right 再读取 held global。不存在 left↔right 直接 attention, +相应梯度边已有回归测试。 + +每个 block 顺序为: + +1. shared-weight BiHub spatial attention; +2. 仅指定层执行 causal temporal attention; +3. visual tokens 查询同一份 instruction tokens; +4. left/global/right task-aware state 分别调制 AdaLN + SwiGLU FFN。 + +state encoder 对两臂共享权重,用 arm/time embedding 区分角色;历史为 causal,两臂 state 先 +查询 instruction,再生成 left/right 条件和临时 global fusion。没有持久的第三条 global state。 + +## 5. 训练目标与课程 + +context latent 保持 clean 且不计 loss。10 个 future latent 时间各采一个 flow time `tau`;同一 +物理时间的三个视角共享 tau,空间位置共享 tau,不同 future 时间独立。目标为标准 flow +velocity,loss 只覆盖 future: + +```text +z_tau = tau * z_clean + (1 - tau) * noise +v* = z_clean - noise +loss = MSE(v_pred, v*) over valid future/view cells +``` + +课程为: + +- steps 0–29,999:role-balanced single-view; +- steps 30,000–149,999:完整 BiHub; +- effective global batch 32 = 8 GPUs × batch 4 × grad accumulation 1。 + +32 不能被 3 整除,因此单个 optimizer step 是 11/11/10;角色按 rank-local sampler 的每个样本 +分配,不依赖 micro-batch 如何切分。role offset 每步轮换,连续 3 steps 恰好 32/32/32。这既保留 +`batch 1 × accumulation 4` 的数据—角色映射,又允许用 `batch 4 × accumulation 1` 减少 FSDP +micro-step 开销;日志保留每个角色计数。 + +优化器为 AdamW,LR `1e-4`、betas `(0.9,0.99)`、weight decay `0.1`、warmup 1000、gradient +clip 1.0、EMA 0.999。BF16、TF32、block activation checkpoint 和 FSDP2 full shard 默认开启。 +FSDP checkpoint wrapper 必须先包 block 再 fully-shard;这是实际 8 卡测试确认过的组合。 + +## 6. 可观测性、验证和 checkpoint + +- 前 10 steps 每步输出;之后 terminal、本地 JSONL、SwanLab 每 100 steps 输出一次。 +- validation 每 1,000 steps,使用固定 seed 的 noise/tau,保证跨 step 可比。 +- checkpoint 每 5,000 steps,并在 single-view→BiHub 切换点强制保存。 +- 固定 4 个 validation case 每 5,000 steps 采样;保存 raw latent `.pth`、latent RMS `.png` 和 + frozen codec decoder 的三视角 GT/prediction `.mp4`。 +- 本地 artifacts 是事实源。训练进程不上传媒体,避免 SwanLab object-store 延迟/400 影响训练; + scalar 上传异常被捕获并记录,不会终止 optimizer。 +- SwanLab 云端只上传 11 个训练/健康 scalar:world/三视角 loss、recovered-clean MSE、LR、grad + norm、吞吐、CUDA peak allocated、课程阶段和角色不平衡度;validation 只增加 5 个质量 scalar。 + 不上传重复的 `step`、raw role counts、current/reserved CUDA memory,也关闭 SDK 自动生成的 54 条 + CPU/GPU system 曲线。完整诊断仍写入本地 `metrics.jsonl`。 +- SwanLab terminal capture 只保留 stderr 中的训练 logger;requirements 和 git snapshot 不上传。 + launcher 与 rank-0 tracker 都清除全部 proxy endpoint,并设置 `NO_PROXY=*`,所有 API/COS 请求直连。 +- DCP 保存 model、optimizer、EMA;每 rank 保存 scheduler、sampler、Python/NumPy/Torch/CUDA + RNG。保存采用临时目录后原子重命名。 +- 恢复时 model/EMA 严格加载;AdamW 允许缺少从未得到梯度的参数 moment,不会放宽模型权重。 + +SwanLab project 固定为 `Multi_WAM`,token 只从 `../z_oranger/token.txt` 读取,不写入命令行或 +上传 config。输出目录保存稳定 run id,resume 继续同一实验。2026-07-19 的在线直连 smoke 经云端 +API 反查确认 16 个必要 custom keys、0 个 SYSTEM keys;上传完成后云端 run 与本地 smoke 均删除。 + +## 7. 已完成的门禁 + +| 门禁 | 结果 | +|---|---| +| 30→20 half-up 与 20 Hz target 对齐 | 通过 | +| 三视角 latent cache、40-frame overlap | 2 个真实 episode,最大误差 0 | +| train/val episode hash | 0 overlap | +| cache tensor/metadata/text hash audit | 通过 | +| real Wan UMT5 tokenizer/encoder cache | `[20,4096]` BF16、finite、非 debug,通过 | +| future-state/action leakage tests | 通过 | +| BiHub 禁止 left↔right direct edge | 通过 | +| state→instruction 梯度 | 通过 | +| 精确 1.397B 架构,8 卡 FSDP2,2 optimizer steps | 通过 | +| single-view→full-BiHub transition | step 1→2 smoke 通过 | +| DCP save + 8 卡 resume 30→31 | 通过 | +| SwanLab | 正式 run 已建立,在线 scalar 上报通过;smoke 不上传云端 | +| frozen decoder RGB contract | 40 帧,`864×768` MP4 通过 | +| offline persistence-control eval | 通过 | + +2026-07-19 的精确架构 smoke 结果: + +```text +parameters: 1,397,471,023 +loss: 3.564453 (single-view step 1) +loss: 4.750000 (full-BiHub step 2) +max allocated: 10.941 GiB / GPU +``` + +该 smoke 只验证真实数据、精确模型、FSDP、EMA、验证和课程切换是否连通,不用于判断收敛质量。 +测试禁用云日志、媒体和大 checkpoint;核验后 smoke output、log 和两 episode 临时 cache 全部删除。 + +## 8. 显存实测 + +### Batch 切分 A/B(固定 global batch 32) + +2026-07-19 使用同一全量 manifest、同一随机种子、精确 1.397B 模型和 8 卡 FSDP2,对每种切分 +执行 30 个 optimizer steps;吞吐取 steps 10–30 的中位数: + +| 阶段 | 每卡 batch × accumulation | windows/s | 相对基线 | CUDA peak allocated | +|---|---:|---:|---:|---:| +| full-BiHub | 1 × 4 | 17.962 | baseline | 10.930 GiB | +| full-BiHub | 2 × 2 | 23.398 | +30.3% | 13.489 GiB | +| full-BiHub | 4 × 1 | 25.898 | +44.2% | 13.499 GiB | +| single-view | 1 × 4 | 25.801 | baseline | 10.394 GiB | +| single-view | 4 × 1 | 37.396 | +44.9% | 11.380 GiB | + +正式配置因此使用 `4 × 1`。这不是扩大 global batch:每个 optimizer step 仍为 32 个 window, +LR、warmup、scheduler、gradient clipping 和 EMA 的步进均不变。角色现在按每个 rank-local sampler +样本分配;单元测试验证不同切分下每条样本的角色不变、连续三步仍为 32/32/32,tiny model +验证 batched loss/gradient 与逐样本累计一致。8 卡真实 single-view 还验证了 step 1–3 为 +11/11/10、11/10/11、10/11/11。 + +`batch 4` 训练期间 `nvidia-smi` 实测每卡使用 17.914 GiB、空余 125.254 GiB,远高于要求的 +70 GiB 空余门槛。改变张量分组会导致 BF16 reduction 的末位数值不保证 bitwise identical,但 +优化目标、样本、角色、global batch 和更新次数等价,不引入会系统性降低最终质量的训练改动。 + +### 当前正式 batch 配置(1,397,471,023 参数) + +```text +8 × NVIDIA H200 +single-view max allocated: 11.380 GiB / GPU +full-BiHub max allocated: 13.499 GiB / GPU +nvidia-smi process memory: 17.914 GiB / GPU +free memory: 125.254 GiB / GPU +``` + +该结果分别覆盖 30 步 single-view 和 30 步 full-BiHub。正式训练还会在 step 5,000 加载 frozen +decoder 做可视化,因此最终进程生命周期峰值可能略高;距 70 GiB 最低空余要求仍有充足余量。 + +### 归档的 5.272B full-BiHub memory gate + +使用真实 `[1,3,20,32,9,12]` latent、8 卡 FSDP2、BF16、activation checkpoint、4 次梯度 +累积,完整执行 forward/backward/clip/AdamW/EMA,并与正在运行的 codec 共卡: + +```text +max allocated: 31.1119 GiB / GPU +max reserved: 37.9278 GiB / GPU +``` + +该数据只作为旧5B实验的历史对照,不再作为当前1.4B启动门槛。 + +## 9. 启动顺序 + +所有入口都会清除 proxy 变量,下载和 API 连接走直连。模型已放在 `../models/`,不下载 codec +checkpoint 或数据集。 + +```bash +cd /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/mira + +# 可重复的两 episode 准备与精确1.4B两步 smoke +./scripts/launch_bihub_wam_world.sh prepare-smoke +./scripts/launch_bihub_wam_world.sh tmux-smoke + +# 正式数据/缓存;latent 阶段默认 8 GPU episode shards × 8 CPU threads +./scripts/launch_bihub_wam_world.sh prepare-formal-manifest +./scripts/launch_bihub_wam_world.sh prepare-formal-text +./scripts/launch_bihub_wam_world.sh prepare-formal-latents + +# 中断后从 content-addressed latent cache 续跑;完成后自动 audit 并进入训练 +./scripts/launch_bihub_wam_world.sh continue-formal-pipeline + +# 也可以只在已有 complete cache 上启动训练 +./scripts/launch_bihub_wam_world.sh tmux-train +``` + +若需要指定资源: + +```bash +MIRA_WAM_NPROC=8 \ +MIRA_WAM_CACHE_CPU_THREADS=8 \ +MIRA_WAM_CACHE_BATCH_VIEWS=0 \ +MIRA_WAM_OUTPUT_DIR=../outputs/my_bihub_run \ +./scripts/launch_bihub_wam_world.sh continue-formal-pipeline +``` + +缓存进程使用 `syncnet_core_c{0..7}`;进入训练后 launcher 为 `syncnet_core_l`,8 个 rank 为 +`syncnet_core_r{0..7}`,完整 argv title 为 `syncnet_core_worker_{0..7}`。运行时进程名不包含 +`wam`。脚本只报告已有 `syncnet_codec*`/`syncnet_core*`,不会执行模糊 `pkill`。停止时只操作 +tmux 的 `world-1b` +window 或已确认 PID,禁止使用 `pkill python`。 + +## 10. 离线 case 评估 + +```bash +python scripts/eval_bihub_wam_offline.py \ + --case-root ../outputs/robotwin_3view_world_1b/visualizations \ + --output-dir ../outputs/robotwin_3view_world_1b/offline_eval \ + --codec-checkpoint ../outputs/mira_robotwin_codec/checkpoint-125000/checkpoint.pth \ + --decode-missing --latest-only +``` + +输出 latent MSE、分视角/分 horizon MSE、last-context persistence MSE 和 skill,同时可重建 +MP4。正式质量判断至少要求 persistence skill 转正,并结合 task/state/text shuffle sensitivity、 +长期 rollout 和 RGB 运动一致性;不能只看 training loss。 + +## 11. 当前正式运行 + +2026-07-19 已完成全部正式门禁并从随机初始化启动: + +1. ALOHA raw audit:train 26,950、val 550、split overlap 0; +2. 真实 UMT5 cache:`debug_only=false`; +3. 全量 codec latent cache:27,500 episodes、`complete_cache=true`; +4. preflight 随机检查 100 个 cache,全部通过; +5. 8 卡 FSDP2 从 step 1 启动,没有加载旧 model/optimizer/scheduler/EMA; +6. 使用优化后的 `batch 4 × accumulation 1`,从 step 1 开始的角色计数和 loss/grad 轨迹通过门禁; +7. world-model rank 在每卡的 `nvidia-smi` 进程占用约 `17.914 GiB`;GPU 0–6 各空余约 + `125.254 GiB`。按操作者要求,GPU 7 同时保留了另一项约 `64.016 GiB` 的任务,因此该卡总占用 + 约 `81.925 GiB`、空余约 `61.243 GiB`; +8. 当前共享 GPU 7 的正式 run 在 step 100 的 loss 为 `1.431641`、吞吐为 + `17.999 windows/s`、CUDA peak allocated 为 `11.380 GiB`,三角色累计严格为 + `960/960/960`。独占 8 卡时同配置的已验证吞吐约为 `36.94 windows/s`;当前降速来自 GPU 7 + 上两个满负载任务的同步争用,不是 dataloader 或 SwanLab 卡住; +9. 云端 API 已反查到 step 100,正式 run 只有 11 个必要 custom scalar、0 个自动 SYSTEM + scalar,状态为 `RUNNING`,且本地日志无上传失败。 + +此前 `batch 1 × accumulation 4` 的首次 1B run 在 step 700 停止,输出归档到 +`../outputs/robotwin_3view_world_1b_b1a4_stopped_step700`,没有被当前 run 自动恢复。 + +运行位置: + +```text +tmux socket/session: hc / hc +training window: world-1b +monitor window: world-watch +local log: ../outputs/world_model_logs/formal-1b.log +metrics: ../outputs/robotwin_3view_world_1b/metrics.jsonl +SwanLab: https://swanlab.cn/@Oranger/Multi_WAM/runs/31d857e6ad6a46689ce8d +``` + +任一条件不满足时 launcher 应失败退出,而不是降级到不完整数据或 debug embedding。 diff --git a/release-20261107/source/workspace_joint/mira/docs/dataset_card.md b/release-20261107/source/workspace_joint/mira/docs/dataset_card.md new file mode 100644 index 0000000000000000000000000000000000000000..9e7c4144b681c2a45f27b7705cd5493a3944704f --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/docs/dataset_card.md @@ -0,0 +1,41 @@ +# Rocket League 4-player dataset + +Time-aligned **video, keyboard actions, game events, and per-frame game state** for all four players +of a 2v2 Rocket League match. + +## Loading + +```python +from mira.data import RocketScienceDataset + +ds = RocketScienceDataset.from_hub("kyutai/rocket-science", split="test") +clip = ds.load_match(ds.match_ids()[0], clip_len=16, target_fps=10)[0] +``` + +`pip install mira[decode]` (provide your own torch + a compatible FFmpeg), or use the +repo's pixi environment. + +## What's in a sample + +One sample is a short (~4 s, 80 frames at 20 fps) window of a match with all four players' +synchronised views. A **clip** is a fixed-length, fps-downsampled slice read from one. For each +clip, per perspective: + +- **`frames`** — `(P, T, C, H, W)` uint8 video (1280×720), one decoded view per perspective. +- **`actions`** — `(P, T, 9)` int32 multi-hot keyboard over a fixed key set (`W A S D Q E Space + LShiftKey LControlKey`), OR-ed over each downsample window so it stays frame-aligned. +- **`events`** — discrete game events (`KickoffStarted/Ended`, `GoalScored`, `Demolition`, + `GoalReplayStarted/Ended`, …) on a single match-wide master clock, mapped onto each perspective's + frames via its `recording_offset_sec`. `exclude_replays=True` skips clips overlapping goal replays. +- **`physics`** — per-frame game state, one list of `FrameState` dicts per perspective, frame-aligned + with the video: the **ball** (location, velocity, rotation, angular velocity), the four **cars** + (location, velocity, boost, on-ground / supersonic flags, …), and the **game** info (score, + overtime, clock). See `mira.data.state` for the typed field layout. + +Perspectives are ordered by `player_id`; `clip.teams` gives each one's team (0 / 1). + +## Exploring + +`mira.data.viz` renders a clip as a synchronised 4-view grid with a keyboard overlay plus a +top-down arena radar and HUD; `examples/explore.py` is a guided, interactive tour (`pixi run +explore`). diff --git a/release-20261107/source/workspace_joint/mira/docs/hero.png b/release-20261107/source/workspace_joint/mira/docs/hero.png new file mode 100644 index 0000000000000000000000000000000000000000..596a703840ae2d537e949e8066a1de6e0d92363a --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/docs/hero.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9e68cb0ec466b6736243b450bac7a1a4081803a9ff43446dfda1b38105dd6e91 +size 650181 diff --git a/release-20261107/source/workspace_joint/mira/docs/joint_rgb_pipeline_20261030.md b/release-20261107/source/workspace_joint/mira/docs/joint_rgb_pipeline_20261030.md new file mode 100644 index 0000000000000000000000000000000000000000..f29fc85cb717084054b22bd4e66ad97ec5c454fa --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/docs/joint_rgb_pipeline_20261030.md @@ -0,0 +1,71 @@ +# Joint RGB pipeline 与训练/推理一致性复核 + +日期:2026-10-30。范围:`workspace_joint/mira` 的当前 joint 训练入口及 BiHubJoint 部署。 + +## 本次修改 + +- `joint_online._decode` 改为调用官方 `XPolicyLab.utils.process_data.decode_image_bit`。 + 它根据 JPEG 的 `XPL-RGB1` 标记区分标准 RGB 与旧格式,统一返回 RGB;训练端不再自行交换通道。 +- 三路相机的全部 40 帧(20 帧历史、20 帧未来监督)均使用该解码。训练、验证共用数据集; + codec 和 Qwen 分别从同一 RGB 张量取输入。重复的 padding 帧只解码一次。 +- 当前 joint 的 codec latent、Qwen hidden、预测未来均在线计算,不读取旧特征缓存。 + 原始数据与清单不需要重写。历史单独 World/Action/cache 训练脚本不属于此次迁移范围。 +- checkpoint 的 resolved config、artifact identity 和 Qwen identity 记录 `robotwin-official-rgb-v1`。 + 配对导出保留该信息;BiHubJoint 在加载模型前拒绝对新 RGB checkpoint 使用 BGR 输入模式。 +- 原有无颜色标记的 checkpoint 仍允许显式 RGB/BGR 对照评测,已有实验参数不变。 +- 通用与四卡入口的新输出目录带 `rgb`。四卡启动脚本显式传入 `--image-color-order rgb`。 + +## 恢复训练的语义 + +旧 checkpoint 的模型权重可以通过 `--init-from-joint-checkpoint PATH` 用于 RGB 适应训练, +但要使用新输出目录,重置 optimizer、scheduler、采样位置和训练 step。 +从 released World/Action 权重重新开始 joint 优化也可使用当前四卡入口。 + +`--resume-from-joint-checkpoint` 以及自动 resume 只接受相同 RGB 解码约定的新 checkpoint。 +这项检查比较预处理语义,没有新增源码哈希一致性限制;旧 checkpoint 不会被原地改写。 +未标记的旧 checkpoint 不应通过手工补写 RGB 标记来绕过检查。 + +官方解码器来自完整的 pinned RoboTwin checkout,默认: +`workspace_joint/transfer/robotwin-official-20260921`。 +迁移环境时可以设置 `ROBOTWIN_EVAL_ROOT`,必须包含支持两种 JPEG 格式的官方解码函数。 +缺少该依赖时会明确报错,不会退回 torchvision/PIL 解码。 + +## 检查结果 + +| 项目 | 结果与证据 | +| --- | --- | +| 真实图像 | train/val × 50 任务 × clean/randomized × 3 相机 × 首/中/尾帧,共 1,800 帧,训练解码和官方解码→WebSocket→RGB adapter 的输出逐像素一致 | +| 模型输入预处理 | handover_block 实际样本 anchor=16,训练 40 帧中的历史部分与推理 20 帧经 codec letterbox/resize/归一化后完全一致;Qwen 当前帧 resize 后完全一致 | +| 两种存储格式 | 人工构造的 legacy JPEG 与官方 encoder 产生的带标记 JPEG 均恢复正确颜色;混合存储、重复帧、冷启动与尾部均通过回归检查 | +| 视角/时间索引 | left/global/right;Qwen 使用历史最后一帧;未来图像不进入历史;冷启动重复首帧,独立 history/context/action/future masks 保留 | +| 语言 | seen 80% / full_goal 20%;删除原文本分支;左/右视角保留 Role: Left-Arm. / Role: Right-Arm.;clean Eval 的 seen 与 randomized Eval 的 unseen 是官方协议差异 | +| World rollout | 训练可微 rollout 与部署采样使用相同 linear_quadratic schedule;2/4/10 步的小模型数值测试通过;正式配置仍为 10 步 | +| Action 条件 | joint Action 使用预测未来;梯度能传入 World、current resampler、共享 state encoder;配对导出绑定更新后的 state encoder | +| 状态/动作 | 继续使用来源 checkpoint 的归一化统计、左右臂 6+1 排列、绝对 joint targets;Action horizon=20,执行前 8 个 waypoint | +| 数据划分 | train=26,950、val=550,各有 50 任务;episode 标识无交集 | +| 启动与旧模型兼容 | 四卡 `--check` 通过;实际 trainer 子进程在 CUDA 分配之前拒绝旧 checkpoint 的 optimizer resume;旧 checkpoint 的 RGB/BGR 实验仍允许运行 | + +测试:`test_rgb_contract.py`、`test_official_adapter_contract.py`、`test_anchor_contract.py`、 +`test_eval_language.py`、`test_flow_tail.py` 共 25 项通过;`test_action_gradient.py` 另 1 项通过。 +真实数据审计脚本为 `workspace_joint/scripts/audit_joint_rgb_pipeline.py`,结果为 +`workspace_joint/artifacts/reports/joint_rgb_pipeline_20261030/audit.json`。 +这是分层抽查,未逐帧扫描全部数据。 + +## 仍需区分的差异和验证边界 + +1. **动作裁剪**:训练目标只标准化,推理预测先裁到 ±5σ,再施加物理范围。 + 上一次 100 个 episode 的抽样有 129/14,347 个参考 target 会被这个推理裁剪改变。 + 这不是预测动作的实际裁剪率,也不能直接推断成功率影响。此次保留,需另做同种子裁剪消融。 +2. **物理时间**:训练按名义 30→20 的帧索引重采样;官方 TOPP 的每个 waypoint 执行时长可变。 + 图像和动作的序列索引对齐,不代表物理执行频率严格为 20 Hz。此次没有修改 benchmark controller。 +3. **状态历史**:训练记录 simulator drive target;推理初始化后记忆 issued waypoint。 + 上次轨迹抽查发现 7 个非终止步骤存在差异,最大约 0.005。控制器回退时仍可能有小偏差。 +4. **预训练历史**:冻结 codec 和来源 World/Action 权重仍来自旧通道训练。 + 现在训练与推理都喂 RGB,消除了输入约定不一致,但不能据此保证冻结 codec 的表示最优, + 也不能保证旧权重未经 RGB 适应训练就保持性能。是否需要 codec 适应需要独立重建质量/下游实验。 +5. **验证范围**:本次做了 CPU 回归、真实数据/预处理验证和小模型梯度及 rollout 数值检查; + 未启动新的正式训练,未执行完整大模型 GPU 训练步,也没有 RGB 适应后的新 checkpoint Acc。 + 当前旧 checkpoint 的 BGR/RGB 配对评测继续运行,其结果回答的是旧模型输入修复的收益。 + +结论:当前 joint 新训练的颜色输入约定已与标准 RGB 推理对齐;其余列出的协议差异仍存在, +不能将本次修复描述为“所有训练与闭环推理条件完全相同”。 diff --git a/release-20261107/source/workspace_joint/mira/docs/joint_world_action_online.md b/release-20261107/source/workspace_joint/mira/docs/joint_world_action_online.md new file mode 100644 index 0000000000000000000000000000000000000000..3693458db05620b757160678192d6cbc3c496a17 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/docs/joint_world_action_online.md @@ -0,0 +1,66 @@ +# Cache-free joint World + Action fine-tuning (anchor-v2, 2026-09-20) + +Current runbook: `../../docs/validation_20260920.md`. Repair evidence and boundaries: +`../../docs/repair_report_20260920.md`. Do not resume an old joint-v1 run with this sampler. + +This training path initializes the complete trainable graph from the released World-v12 step +25,066 and Action-v13 step 23,016 checkpoints. Qwen3-VL and the codec encoder/decoder are frozen. +No codec latent, Qwen hidden, or predicted-future cache is read or written. + +For each sample, the loader reads the original RoboTwin zip/HDF5 episode and builds an +current-anchor-first available history (all 20 Hz anchors, duplicate initial observation, +separate action/future/RGB validity masks). The frozen codec produces context and ground-truth future +latents online, while frozen Qwen produces the current-frame instruction features online. The +World model has two training paths: + +1. Its original conditional flow-matching objective preserves the pretrained generative field. +2. A differentiable Euler rollout produces a future latent without seeing the ground-truth + future. That same prediction conditions Action-v13 and passes through the frozen codec decoder. + +The total objective is + +```text +L = 1.0 L_world_flow + 1.0 L_action_flow +# Optional independent ablations: --weight-latent, --weight-pixel (both default 0) +``` + +`L_future_RGB` is a Charbonnier loss in normalized RGB space. Because the codec decoder is causal, +the trainer decodes `context + predicted future` together and applies the loss only to the future +frames, matching deployment. Freezing decoder parameters does not detach its input, so this loss +updates the World model. Likewise, the predicted future is not detached before Action-v13; action +supervision therefore updates both the Action head and World. +The live World state encoder is shared with the Action path and is fine-tuned as part of World. + +## Launch + +From a restored `snapshot-20260902-full` workspace, the only required argument is the RoboTwin +dataset directory: + +```bash +bash scripts/launch_joint_world_action.sh /path/to/RoboTwin2.0 +``` + +The directory must contain `dataset/*/*.zip`. The launcher automatically creates deterministic +episode-level manifests and train-only state statistics inside +`RoboTwin2.0/mira_manifests/`; these are small provenance/index files, not model caches. It locates +the released checkpoints and frozen models in the restored workspace, starts one worker per +visible GPU, writes atomic distributed checkpoints, and resumes the latest compatible checkpoint. + +Useful optional environment variables are `CUDA_VISIBLE_DEVICES`, `NPROC_PER_NODE`, `OUTPUT_DIR`, +`WORLD_CHECKPOINT`, `ACTION_CHECKPOINT`, `CODEC_CHECKPOINT`, and `QWEN_ROOT`. Trainer overrides can +follow the dataset argument, for example: + +```bash +bash scripts/launch_joint_world_action.sh /path/to/RoboTwin2.0 \ + --steps 20000 --world-rollout-steps 10 +``` + +With eight visible GPUs and explicit H200_PROFILE=1 the launcher enables its H200 profile: BF16 FSDP2, micro-batch 4/GPU, +accumulation 1 (global batch 32), eight data workers/rank, Flash SDPA and expandable CUDA allocator. +Set `H200_PROFILE=0` to use generic trainer defaults. If batch 4 exceeds memory in the destination +software stack, `PER_DEVICE_BATCH=2 GRADIENT_ACCUMULATION=2` preserves global batch 32. + +The default is ten rollout steps, matching the released runtime. Alternate counts (2/4) must +be exported with their paired joint runtime; that runtime reads the saved count. No claim of +equal policy quality is made for different schedules. Fixed-seed validation, best/milestone +retention and paired export are implemented; GPU FSDP2 smoke and closed-loop checks remain required. diff --git a/release-20261107/source/workspace_joint/mira/docs/pre_full_eval_audit_20261030.md b/release-20261107/source/workspace_joint/mira/docs/pre_full_eval_audit_20261030.md new file mode 100644 index 0000000000000000000000000000000000000000..8e3d02862f14a66e6d826e5acaa06d429812c1f6 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/docs/pre_full_eval_audit_20261030.md @@ -0,0 +1,64 @@ +# step 6563 全量评测前复核 + +本次目标:评估已有的 `joint-checkpoint-6563`,并非评估尚未训练出的 RGB 新模型。 +结论:正式评测使用原配 codec、Qwen、World/Action 配对导出和 BGR 兼容输入。 +以下修复已完成;没有启动全量评测。 + +## 必须修复的路径 + +| 问题 | 原行为与风险 | 修复 | +| --- | --- | --- | +| 颜色默认值 | 旧全量启动脚本没有指定 BGR,runner 默认 RGB;重启会再次产生通道错配 | runner 支持 checkpoint-aware `auto`:历史 joint 导出解析为 BGR,新 RGB checkpoint 解析为 RGB;正式 step 6563 启动脚本显式指定 BGR | +| 指令回退/传递失败 | 生成异常或空候选时回退任务名;prepare_case RPC 异常被吞掉,策略可能使用旧指令或默认指令 | 正式入口启用 `--strict-eval`;指令缺失或 prepare/reset/rollout 失败中止该次尝试,不产生有效的任务失败记录 | +| 失败计数 | 执行若干动作后发生策略/环境异常,会被记录为任务失败;首步前异常可能跳到下一个种子 | 严格模式中止,runner 仅保留已完成的 episode,重启从最后完成种子之后继续;异常 episode 不被计入 Acc | +| 指令复现 | 候选列表生成会消费全局 Python RNG;只固定候选索引不足以保证重试、分片或改变 test_num 后指令一致 | 严格模式按 task/domain/seed 固定生成 RNG,固定 100 个候选,生成后恢复 RNG。保持官方 seen/unseen 模板与物体描述;协议记录为 strict_seeded_candidates100_v1 | +| 新旧结果混合 | 修复后沿用旧 run ID 会混入 RGB 结果或断点数据 | 正式入口、调度器和报告默认改到 joint4fresh_full100_step6563_bgr_strict_20261030;原 RGB 数据保留在原目录。manifest 比较颜色、严格模式和指令协议 | + +旧 checkpoint 的显式 RGB/BGR 小实验仍允许两种模式,其 runner 未启用严格模式, +以便当前实验维持已经记录的协议。XPolicyLab adapter 的 deploy.yml 默认仍为 RGB; +正式入口通过 override 显式传入 BGR。 + +## 不应在本轮全量评测前直接替换的内容 + +- **codec**:现有 codec 与旧 World/Action 共同在旧输入约定下训练。全量评测先保持原 codec 并统一 BGR 输入。 + RGB codec 微调以及后续 joint 适应训练属于新模型实验,不能将新 codec 直接换进旧模型后比较 Acc。 +- **动作裁剪**:训练目标仅标准化,推理仍有 ±5σ 和物理范围裁剪。 + 历史抽样 129/14,347 个参考 target 会被 ±5σ 改变,这不等于预测实际裁剪率。 + 本次新增每次 replan 的 normalized/physical clip 坐标数、执行前 8 步的裁剪坐标数与预测幅值;不改动作数值。 + 是否调整阈值应结合这些记录做配对消融,不能凭参考 target 覆盖率直接取消裁剪。 +- **物理时间**:训练按名义 30→20 FPS 重采样,官方 TOPP 每个 waypoint 的执行时间可变。 + 索引对齐不等于严格物理 20 Hz;保持官方 controller 才能解释 benchmark 成绩。 +- **状态历史**:训练与官方 observation 都取 drive target(不是测量关节位置);当前 adapter 冷启动后记忆 issued waypoint。 + 控制器回退可能使两者略有差别。此前抽查 16,888 步仅 7 个非终止步骤不同,最大约 0.005。 + 没有证据说明这是主要低 Acc 原因,宜另做 observed-drive-target 历史的消融。 +- **expert 过滤**:保留官方不可行/不稳定场景的筛选,包括 expert planner 抛异常的路径与连续异常上限。 + 旧 full Eval 的 3 次 expert 异常为 lift_pot/grab_roller 的 target_pose=None,以及 click_alarmclock 的 NoneType; + 不能把所有 expert 异常都判为基础设施故障而强行中止,否则可能卡住官方可行性筛选。 + 通过 expert 后的 eval setup 异常在严格模式下中止重试。 + +## 已核对的一致项 + +- 原 checkpoint 与导出的 resolved_config、artifact_identity 一致。 +- World/Action 导出的 38 个 state encoder 张量逐元素相同,Action mean/std 与保存配置逐元素相同。 +- World 使用 linear_quadratic 10 步;Action 使用 Euler 10 步、horizon=20、execute_steps=8。 +- 当前帧 Qwen 输入、三视角顺序、左右 Role 后缀、状态排列与归一化沿用训练实现。 +- 训练 Action 条件来自预测未来,且 joint 使用更新后的共享 state encoder。 +- codec 特征骨干逐帧处理,temporal bottleneck 的 kernel=stride=2,不跨相邻单元;40 帧训练 context 前缀不会读取未来 20 帧。 +- 训练 seen 80% / full_goal 20%;clean Eval 使用 seen,randomized Eval 使用 unseen,后者是官方泛化设置。 +- 冷启动、历史 mask、future/action 尾部 mask、动作映射及 World rollout 数值回归测试通过。 + +## 验证与限制 + +- 36 项相关回归检查通过;最后的异常清理调整后,11 项正式评测协议测试再次通过。 + 故障注入覆盖指令缺失、prepare RPC 异常、执行一步后的 rollout 异常、setup 异常以及 expert 连续失败上限。 +- 50 个任务 × 2 个 domain 的验证集场景,各验证 seen/unseen,共 200 条真实语言路径。 + 均无空文本、任务名回退或未替换占位符;不同全局 RNG 与请求数量下可复现。 + 这不是全部可能物体组合的穷举。 +- 05 节点正式启动脚本 `--check` 通过;Python 与 shell 语法检查通过。 +- 当前颜色小实验 16 份 client 日志未发现 rollout 错误、指令回退或 setup 错误。 +- 本次没有再次运行完整模型的 GPU 数值等价测试,也没有开始新一轮全量或 codec 适应训练。 +- 开始全量时仍需将四卡占卡程序的显存交给 full Eval workers,避免同时运行两套调度器; + 本次预检没有释放或中止正在跑的小实验资源。 + +可复查证据:`workspace_joint/artifacts/reports/pre_full_eval_20261030/audit.json`。 +生成脚本:`workspace_joint/scripts/audit_before_full_eval_20261030.py`。 diff --git a/release-20261107/source/workspace_joint/mira/docs/robotwin_lingbot_codec_design.md b/release-20261107/source/workspace_joint/mira/docs/robotwin_lingbot_codec_design.md new file mode 100644 index 0000000000000000000000000000000000000000..1217f7ba16252b78ecea501c7effc7cca982ba82 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/docs/robotwin_lingbot_codec_design.md @@ -0,0 +1,376 @@ +# RoboTwin × LingBot Codec 训练设计说明 + +状态:稳定基线 +最后核对:2026-07-17 +配置入口:[`configs/train_codec.yaml`](../configs/train_codec.yaml) +启动入口:[`scripts/train_robotwin_codec.sh`](../scripts/train_robotwin_codec.sh) + +## 1. 文档目的 + +本文固定本项目 RoboTwin codec 的设计边界和接口契约,供后续 WAM(World Action +Model)设计、训练恢复和结构迭代使用。重点是“系统为何这样组织”和“修改会影响什么”, +不是某一次实验结果的复盘。 + +配置和代码始终是参数的最终事实源;本文解释这些参数之间必须保持的关系。 + +## 2. 目标与非目标 + +当前 codec 的目标是: + +- 将 RoboTwin 的不同任务、机器人、域和相机视角映射到统一、紧凑的视频 latent 空间; +- 保留足够的像素、感知和 LingBot 语义信息,供后续 WAM 学习动力学和动作条件生成; +- 不解压整套 RoboTwin 数据,直接从 zip/HDF5 流式训练; +- 在多卡训练中均衡覆盖三个视角,同时避免把高度相关的三视角样本连续送入模型; +- 使数据过滤、配置、可视化、云端指标和 checkpoint 都可复现、可恢复、可审计。 + +当前 codec 明确不负责: + +- 动作建模。codec 只重建视频,空 action tensor 仅用于兼容统一 batch API; +- 三视角联合融合。每个训练样本只包含一个视角,三个视角共享同一个 codec; +- 任务或机器人身份建模。这些条件应在后续 WAM 层显式加入; +- 自动下载模型权重或数据。 + +## 3. 系统总览 + +```text +RoboTwin zip/HDF5 + │ + ├─ 基础 manifest:episode 级、train/val 不相交 + │ + ├─ clip 兼容性审计:三相机存在、长度对齐、至少 60 个源帧 + │ + ▼ +兼容 manifest + │ + ├─ DDP rank / DataLoader worker 按 archive 分片 + ├─ episode 每轮只选一个视角,三轮循环覆盖 head/left/right + └─ 30 FPS → 20 FPS,随机截取 40 帧 clip + ▼ +[B, 40, 3, 288, 384] + │ + ├─ 冻结 LingBot-Vision-L/16,多层特征聚合 + ├─ 3D bottleneck:时间 ×2、空间 ×2(叠加 patch/16) + ▼ +latent [B, 20, 32, 9, 12] + │ + └─ 28 层时空 ViT decoder + ▼ +重建视频 [B, 40, 3, 288, 384] + │ + └─ L1 + LPIPS + LingBot feature consistency +``` + +## 4. 稳定接口契约 + +下面这些值共同定义 codec 与未来 WAM 的表示接口。任何一项变化都应视为“新 codec”, +需要重新训练,并重新验证或训练依赖它的 WAM。 + +| 契约 | 当前值 | 含义 | +|---|---:|---| +| 视频帧率 | 20 FPS | codec 接收和重建的时间基准 | +| clip 长度 | 40 帧 | 每个样本约 2 秒 | +| codec 分辨率 | 288 × 384 | 保持 RoboTwin 4:3 比例,且可被空间下采样整除 | +| latent 时间长度 | 20 | 每个 latent 时间单元对应两个视频帧 | +| latent 通道 | 32 | WAM 的主要表示通道契约 | +| latent 空间网格 | 9 × 12 | 总空间下采样为 32 倍 | +| latent 形状 | `[B, 20, 32, 9, 12]` | WAM 应直接依赖的 codec 输出格式 | +| backbone patch | 16 | LingBot patch 网格为 18 × 24 | +| 时间下采样 | 2 | 20 FPS 视频变成 10 Hz latent 序列 | + +代码会显式检查 encoder/decoder 的 `latent_dim`、时间倍率和空间倍率是否匹配,避免产生 +形状正确但语义错位的 checkpoint。 + +### 对未来 WAM 的直接约束 + +- WAM 应把 latent 当作 10 Hz 序列,而不是 20 Hz 视频帧序列。 +- 动作原始时间基准仍建议保留为 20 Hz;映射到 latent 时必须显式处理每个 latent 对应的 + 两个动作时刻,不能默认动作与 latent 一一对应。 +- 多视角 WAM 建议分别用同一个 codec 编码三个视角,再在 WAM 中保留显式视角维或 + view embedding,例如 `[B, V, Tz, Cz, Hz, Wz]`。不建议把三相机直接拼成一张大图再送入 + 当前 codec,因为这会改变空间统计和上述表示契约。 +- codec checkpoint 内包含冻结的 LingBot 权重和 `codec_config.yaml`;WAM 加载 codec + checkpoint 后不应再依赖外部 LingBot 权重目录。 + +## 5. 数据设计 + +### 5.1 数据来源与 batch + +数据根目录默认为 `../datasets/RoboTwin2.0`。loader 直接读取每个 task 下的 zip 成员, +每个 episode 是一个 HDF5 文件,使用: + +- `observation/head_camera/rgb` +- `observation/left_camera/rgb` +- `observation/right_camera/rgb` + +loader 输出 `uint8`、`[B, T, C, H, W]` 视频。模型在 GPU 上执行等比例 letterbox、双线性 +resize 到 288 × 384,再从 `[0, 1]` 归一化到 `[-1, 1]`。保持 resize 在 GPU 上是避免 CPU +预处理成为瓶颈的设计要求。 + +### 5.2 30 FPS 到 20 FPS + +输出第 `i` 帧使用 half-up 最近邻规则: + +```text +source_index(i) = floor(i × source_fps / target_fps + 0.5) +``` + +40 个输出帧对应的最后一个源 offset 是 59,因此一个 episode 至少需要 60 个源帧。 +对长度为 `N` 的有效 episode,随机起点范围是 `[0, N - 60]`。这一规则必须与兼容 manifest +的审计参数保持一致。 + +### 5.3 manifest 与兼容性过滤 + +启动脚本使用两层 manifest: + +1. 基础 manifest 在每个 task/robot/domain archive 内做稳定的 episode 级 train/val 划分, + 同一个 episode 不会泄漏到两个 split。 +2. codec 兼容 manifest 位于 `mira_manifests/codec_40f_30to20/`,针对 40 帧、30→20 FPS + 契约检查数据。 + +兼容性审计先对每个 archive 的均匀位置做探针检查。一旦发现任一探针过短、相机缺失、 +相机长度不齐或文件损坏,就完整检查该 archive 的所有 episode。审计结果和清单会缓存; +基础 manifest 或审计参数改变时才重建。 + +探针策略避免为一次预检查解压整个数据集。对于极少数未被探针覆盖的异常,loader 会在 +第一次失败后把该 episode 记入当前 worker 的无效集合,后续 epoch 不再重复解压和警告。 +生成的 `summary.json` 和 `compatibility_index.jsonl` 是数据审计的事实记录。 + +### 5.4 三视角分配 + +训练阶段不把同一 episode 的三个相机同时作为三个相邻样本。视角由以下规则决定: + +```text +camera = cameras[(stable_hash(episode) + epoch) mod 3] +``` + +因此: + +- 每个 episode 每轮只解码一个相机,控制 I/O 和样本相关性; +- 稳定 hash 使同一轮内三个视角在不同 episode 间近似均衡; +- 连续三轮后,每个 episode 覆盖 head、left、right 三个视角; +- 每 100 steps 记录一次各视角 count 和 fraction,便于发现分配漂移。 + +这是一种“共享表示、轮换覆盖”的训练设计,不是同步多视角融合。 + +### 5.5 分布式数据读取 + +archive 先按 DDP rank 分片,再按 DataLoader worker 分片,避免多个 worker 重复遍历同一 +archive 集合。每个 worker 以 `archive_mix_size` 为块打开若干 zip,并在 archive 间轮转 +取样。当前默认值 32 是任务混合度、文件句柄数和随机 I/O 之间的折中。 + +`num_workers`、`prefetch_factor` 和 `archive_mix_size` 属于性能参数,可以在不改变模型接口 +的情况下调整;但修改后应重新观察 GPU 等待、CPU、磁盘吞吐和无效样本警告。 + +## 6. 模型设计 + +模型配置见 +[`configs/model/lingbot_raev2_codec_tdown.yaml`](../configs/model/lingbot_raev2_codec_tdown.yaml)。 + +### 6.1 冻结的 LingBot encoder + +- 使用本地 LingBot-Vision `large`、patch size 16、特征维 1024; +- 权重只允许从本地目录或 `.pt` 文件加载,禁止静默回退到网络下载; +- backbone 始终保持 `eval` 且 `requires_grad=False`; +- 取第 `[11, 13, 15, 17, 19, 21, 23]` 层的归一化 patch feature; +- 多层聚合为 `mean(all_layers) + last_layer`; +- 只训练聚合后的投影 bottleneck 和 decoder。 + +冻结 backbone 的目的不是仅降低显存,而是固定未来 WAM 所依赖的表示语义。替换 encoder、 +修改层选择或解冻 backbone 都会改变 latent 分布,必须作为新 codec 版本处理。 + +### 6.2 bottleneck + +聚合特征形状为 `[B, 40, 1024, 18, 24]`。一个 kernel/stride 都为 `(2, 2, 2)` 的 3D +卷积把它投影为: + +```text +[B, 20, 32, 9, 12] +``` + +当前 `noise_tau=0`,即不向 latent 注入随机噪声。若未来启用 noise regularization,需要 +同时评估重建质量、latent 动力学可预测性和 WAM 稳定性。 + +### 6.3 时空 ViT decoder + +decoder 先用 stride-2 `ConvTranspose2d` 把 latent 空间网格恢复到 18 × 24 token 网格, +然后使用 28 层、宽度 1152、16 heads 的时空 Transformer: + +- 每帧内部使用双向 spatial attention; +- 时间方向使用 causal temporal attention; +- 最后以空间 patch 16、时间 patch 2 unpatchify 回 40 帧视频; +- activation checkpointing 默认开启以控制训练显存。 + +时间 causal 的含义是在 latent 序列上不读取未来 latent;每个 latent 单元最终解码两个视频帧。 + +## 7. 训练目标 + +总损失由三部分组成,基础配置权重均为 1: + +1. **L1/MAE**:对全部 40 帧计算,提供稳定的像素重建锚点。 +2. **LPIPS**:每步随机选取约 25% 帧,约束局部感知质量。 +3. **LingBot feature consistency**:每步随机选取约 25% 帧,在与 encoder 相同的七层 + LingBot normalized feature 上计算均方误差,约束语义表示。 + +LPIPS 和 LingBot 项使用 decoder 最后一层上的梯度范数,相对于 L1 做动态 auto-weight, +并由 `max_auto_weight` 限制极端倍率。LingBot backbone 参数仍冻结,但重建图像经过 backbone +时保留对图像的梯度,从而能更新 decoder。 + +这个组合的设计意图是:L1 保证低频和颜色稳定,LPIPS 保证感知细节,LingBot consistency +保证 latent/重建不偏离后续 WAM 需要的视觉语义。 + +## 8. 训练与调度 + +默认采用一 GPU 一 DDP process,CUDA 使用 bfloat16 autocast。当前保守配置是每卡 +batch size 1;8 卡时全局 batch size 为 8。优化器是 AdamW,配合 warmup + cosine decay。 + +模型维护两类 EMA: + +- `model_ema_decay=0.9999`:验证、固定可视化和可部署 checkpoint 使用 EMA 模型参数; +- `latents_ema_decay=0.99`:估计 latent mean/std,并写入 checkpoint,供 WAM 归一化使用。 + +当前周期彼此独立: + +| 事件 | 默认周期 | 成本与作用 | +|---|---:|---| +| 本地/SwanLab 标量 | 100 steps | 轻量;聚合窗口内 loss、吞吐和视角分布 | +| 固定可视化 | 1%(2500 steps) | 较重;四个三视角 case | +| validation | 2%(5000 steps) | 较重;分布式验证集重建损失 | +| checkpoint | 5%(12500 steps) | 较重;模型及完整恢复状态 | + +前 10 个 steps 会逐步输出,之后每 100 steps 输出一次。除前 10 步外,SwanLab 上的 +训练 loss 是最近一个日志窗口的平均值,而不是单个 batch 的瞬时值,这有利于观察趋势。 + +## 9. 可视化与可观测性 + +### 9.1 固定三视角 case + +程序从 validation manifest 中按 task/robot/domain 分层选择 4 个固定 case,并把 episode 和 +时间起点写入 `visualizations/cases.json`。resume 时复用同一组 case。 + +每个 case 的 MP4: + +- 三行依次为 head、left、right,三者来自同一 episode 和同一时间窗口; +- 每行横向展示 ground truth 与 reconstruction; +- 本地 MP4 是质量判断的事实源; +- SwanLab 只上传 2 FPS、最大边 384 的紧凑 GIF,降低媒体上传对训练的影响。 + +### 9.2 标量日志 + +rank 0 同时写本地日志和 SwanLab `Multi_WAM`,主要包括: + +- train/test 各损失项和 auto-weight; +- learning rate、latent mean/std、各损失的 gradient norm; +- 总吞吐、每卡吞吐、ETA、step 时间; +- GPU allocated/reserved/max memory; +- head/left/right 的样本数和比例。 + +SwanLab token 从独立文件读取,不进入命令行,上传配置前会移除 secret/token 字段。媒体上传 +失败不应被当作训练数值失败;发生问题时首先以本地 MP4、训练日志和 checkpoint 为准。 + +## 10. Checkpoint 与恢复 + +checkpoint 目录包含: + +- `checkpoint.pth`:EMA 模型权重、必要元数据和 latent mean/std; +- `training_state.pth`:原始模型、model EMA、optimizer、scheduler、latent EMA 和 step; +- 输出根目录的 `codec_config.yaml`:完整解析后的 codec/数据/训练配置。 + +保存先写临时目录,再原子重命名,防止中断留下可被误识别的半成品 checkpoint。 + +恢复模式: + +- `continue_from`:恢复全部训练状态,并从下一个 step 继续; +- `finetune_from`:只加载模型权重,optimizer/scheduler/step 从头开始; +- 同一输出目录已有 checkpoint 且未显式指定时,自动选择最新 checkpoint 恢复。 + +当前默认只保留最近一个非永久 checkpoint。若后续需要做长期回归、消融或选择最佳 codec, +应调整 retention,而不是依赖 SwanLab 替代模型文件。 + +## 11. 启动与运行安全 + +统一使用: + +```bash +./scripts/train_robotwin_codec.sh +``` + +启动脚本负责: + +- 激活名为 `mira` 的 conda 环境; +- 清除代理变量,并设置 Hugging Face/Transformers 离线模式; +- 检查数据、LingBot 本地权重和 SwanLab token; +- 构建或复用基础 manifest 与兼容 manifest; +- 生成 Hydra 参数并启动单卡或 `torchrun`; +- 为等待器、launcher 和 worker 设置 `syncnet_*` 进程名; +- 默认拒绝在忙碌 GPU 上误启动,也可显式等待空闲。 + +只有明确决定与其他任务共跑时才使用: + +```bash +REQUIRE_IDLE_GPUS=0 NPROC_PER_NODE=8 ./scripts/train_robotwin_codec.sh +``` + +不要用 `pkill python` 管理训练。推荐使用独立 tmux session,并只向对应 launcher 发送 +`SIGINT`/`Ctrl-C`。若尚未到首次 checkpoint,重启会从 step 0 开始。 + +## 12. 后续修改分级 + +### A. 通常可安全修改,不改变 codec/WAM 接口 + +- `LOG_EVERY`、SwanLab 名称和媒体压缩参数; +- DataLoader worker、prefetch、archive mix; +- validation 样本数和可视化 case 数; +- checkpoint 保存/保留周期; +- 在显存允许时调整每卡 batch size,但需要相应检查优化器和学习率策略。 + +### B. 需要重新训练 codec,但可保持 latent 形状 + +- optimizer、学习率、loss 权重和 frame fraction; +- encoder 层聚合方式、是否解冻 backbone; +- decoder 深度/宽度; +- latent noise regularization。 + +即使 latent tensor 形状不变,这类修改也会改变 latent 分布,已有 WAM 不能默认兼容。 + +### C. 会破坏 codec/WAM 结构接口 + +- `latent_dim`; +- 输入 FPS、clip 帧数或时空分辨率; +- encoder/decoder 的 temporal stride、spatial stride、patch size; +- 单视角输入改为拼接或联合多视角输入; +- 更换 backbone 家族或预处理规范。 + +这类变更必须产生新配置名、新输出目录和新 WAM 版本,禁止覆盖现有稳定 checkpoint。 + +## 13. 变更前检查清单 + +设计新 codec 或接入 WAM 前,至少确认: + +- [ ] 数据兼容 manifest 的 `clip_len/source_fps/target_fps` 与模型完全一致; +- [ ] encoder 和 decoder 的时间、空间倍率一致; +- [ ] 实际 latent 形状仍符合目标 WAM 配置; +- [ ] 三视角是共享编码还是联合编码,语义已明确,不靠张量拼接隐式表达; +- [ ] 动作频率到 latent 频率的映射已显式定义; +- [ ] checkpoint 保存了 `codec_config.yaml` 和 latent mean/std; +- [ ] step 0 固定 case、validation 和至少一个训练 step 均成功; +- [ ] 三视角 count/fraction 没有长期偏斜; +- [ ] resume 流程至少做过一次真实 checkpoint 验证; +- [ ] 新结构使用新的配置名、输出目录和 SwanLab run,不覆盖稳定基线。 + +## 14. 代码事实源 + +| 主题 | 文件 | +|---|---| +| 总训练配置 | [`configs/train_codec.yaml`](../configs/train_codec.yaml) | +| 模型结构 | [`configs/model/lingbot_raev2_codec_tdown.yaml`](../configs/model/lingbot_raev2_codec_tdown.yaml) | +| RoboTwin 配置 | [`configs/dataset/robotwin2.yaml`](../configs/dataset/robotwin2.yaml) | +| 启动与安全检查 | [`scripts/train_robotwin_codec.sh`](../scripts/train_robotwin_codec.sh) | +| 训练循环 | [`scripts/train_codec.py`](../scripts/train_codec.py) | +| 数据过滤/三视角 loader | [`src/mira/data/robotwin_loader.py`](../src/mira/data/robotwin_loader.py) | +| LingBot 本地适配 | [`src/mira/codec/lingbot.py`](../src/mira/codec/lingbot.py) | +| encoder/bottleneck | [`src/mira/codec/rae_encoder.py`](../src/mira/codec/rae_encoder.py) | +| decoder | [`src/mira/codec/vit_decoder.py`](../src/mira/codec/vit_decoder.py) | +| loss | [`src/mira/codec/loss.py`](../src/mira/codec/loss.py) | +| checkpoint | [`src/mira/training/checkpoint_manager.py`](../src/mira/training/checkpoint_manager.py) | +| SwanLab | [`src/mira/training/swanlab_tracker.py`](../src/mira/training/swanlab_tracker.py) | + diff --git a/release-20261107/source/workspace_joint/mira/docs/robotwin_lingbot_codec_interface_contract.md b/release-20261107/source/workspace_joint/mira/docs/robotwin_lingbot_codec_interface_contract.md new file mode 100644 index 0000000000000000000000000000000000000000..060994d5bfb4c669bff7a250426fe9a4288bcc16 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/docs/robotwin_lingbot_codec_interface_contract.md @@ -0,0 +1,65 @@ +# RoboTwin LingBot Codec → BiHub WAM 接口契约 + +状态:Stage W 不可变基线 +最后核对:2026-07-18 +codec:`checkpoint-125000` EMA +SHA-256:`2b80052d4cf8a046e800697a360a2d3d4a35027635478860c243c34ff7d8d19d` + +这份文件只记录跨阶段不能静默变化的接口。训练设计见 +[`bihub_wam_stage_w_pipeline.md`](bihub_wam_stage_w_pipeline.md)。 + +## 视频与 latent + +| 项目 | 固定值 | +|---|---| +| 视角顺序 | `left, global(head), right` | +| 源视频 | 30 FPS | +| codec 视频 | 20 FPS,half-up 最近邻采样 | +| codec 输入 | 40 帧,`288×384`,约 2 秒 | +| codec latent | `[T=20,C=32,H=9,W=12]`,10 Hz | +| WAM window | 10 个 context latent + 10 个 future latent | +| latent 归一化 | `(z_raw - 0.024823864160431405) / 1.9595992324017892` | + +源帧索引必须是: + +```text +s(i) = floor(i * 30 / 20 + 0.5) +``` + +三个视角由同一 EMA codec 独立编码,WAM 中保留显式 view 维,禁止把相机图像预先拼接后编码。 + +## 状态语义 + +RoboTwin HDF5 的 `joint_action/vector` 经上游 simulator 源码核对,是 +`get_drive_target()` 的记录,不是实测 encoder/qpos。本项目统一称为 +`joint_target_state`,语义字符串固定为: + +```text +simulator_drive_target_not_measured_qpos +``` + +维度顺序固定为: + +```text +left arm 6, left gripper 1, right arm 6, right gripper 1 +``` + +构建 manifest 时必须用四个 component 数组重建 14D vector,并要求最大误差不超过 `1e-6`。 +20 Hz 对齐和下一目标约定为: + +```text +q_target20[i] = q_target30[s(i)] +u20[i] = q_target20[i + 1] +``` + +Stage W 只读取 20 个历史 target;不会读取 future state、future action,也不会实例化 action +head。真实机器人若提供的是 measured qpos,必须在后续 WAM/action 阶段显式设计 domain adapter, +不能把当前字段改名为 qpos 后直接混用。 + +## 缓存与版本 + +- latent cache 由 codec checkpoint SHA-256 命名空间隔离;换 codec 必须重建。 +- text cache 由 Wan UMT5 repository、revision、权重 hash 和 max length 共同隔离。 +- train/val 继承 codec 的 episode split,以 episode hash 证明零交集。 +- 正式 Stage W 只接受 `aloha-agilex`;其他 embodiment 需要单独 stem/head 与语义审计。 +- 缓存 tensor、metadata、instruction hash 或 codec hash 任一不匹配时必须 fail fast。 diff --git a/release-20261107/source/workspace_joint/mira/docs/world_model_stage/01_final_model.md b/release-20261107/source/workspace_joint/mira/docs/world_model_stage/01_final_model.md new file mode 100644 index 0000000000000000000000000000000000000000..98e3e5a52e3927935db306f64d3dcff95c65b40d --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/docs/world_model_stage/01_final_model.md @@ -0,0 +1,207 @@ +# 最终模型实现 + +## 1. 最终训练范围 + +正式配置的训练范围为 `world_only`,action 分支关闭。最终模型执行: + +\[ +(三视角过去视频,\ 历史双臂状态,\ 指令) +\longrightarrow 三视角未来视频 +\] + +视频在冻结 codec 的 latent 空间中建模。训练时不加载 RGB encoder、文本大模型或 action 模块。 + +## 2. 输入输出 + +### 输入 + +| 输入 | Shape | 物理含义 | +|---|---|---| +| Context latent | `[B, 3, 10, 32, 9, 12]` | 三视角过去 1 秒 | +| Drive-target history | `[B, 20, 2, 7]` | 过去 1 秒、20 Hz、双臂 7 DoF | +| History valid | `[B, 20]` | 状态时间有效位 | +| Text embedding | `[B, L, 4096]` | 任务指令,`L <= 128` | +| View/time masks | 随 batch | 视角和时间有效位 | + +视角维顺序固定为: + +```text +left, global, right +``` + +### 监督目标 + +```text +future latent: [B, 3, 10, 32, 9, 12] +``` + +对应三个视角未来 1 秒。future observation 只用于 loss,不进入条件输入。 + +## 3. 主干配置 + +| 参数 | 最终值 | +|---|---:| +| Hidden size | 2048 | +| Transformer layers | 16 | +| Query heads | 16 | +| KV heads | 4 | +| Text dim | 4096 | +| Visual latent channels | 32 | +| Latent spatial size | 9 × 12 | +| Temporal layers | 0、4、8、12、15 | +| State encoder hidden | 512 | +| State encoder layers | 2 | +| State query heads | 8 | +| State text KV heads | 4 | +| 主干参数量 | 1,387,463,200 | +| 状态编码器参数量 | 10,007,823 | +| 总参数量 | 1,397,471,023 | + +主干启用了: + +- QK layer normalization; +- attention gating; +- activation checkpointing; +- 显式 view embedding; +- flow-time conditioning。 + +## 4. 实际 block 结构 + +完整三视角阶段中,一个主干 block 的执行顺序为: + +1. BiHub spatial attention; +2. 在指定层执行 causal temporal attention; +3. visual-to-text cross-attention; +4. 使用 flow time 和 state condition 的 AdaLN/MLP。 + +### BiHub 的实际通信关系 + +每个物理时间点上: + +1. global 从 left、global、right 汇聚; +2. left 和 right 分别从更新后的 global 接收信息; +3. left 与 right 不直接建立注意力边。 + +三个视角共享空间模块权重,通过 view embedding 区分角色。 + +### 时间模块 + +时间注意力仅位于第 0、4、8、12、15 层,并使用 causal mask。20 个 latent 时间点按: + +```text +10 context + 10 future +``` + +排列。context 不读取 future,较早的 future 不读取更晚 future。 + +## 5. State condition 的最终实现 + +状态输入来源于 `joint_action/vector`,部署时已经确认其语义为: + +```text +simulator_drive_target_not_measured_qpos +``` + +每个时间点构造: + +- 标准化 drive target; +- 相邻时刻 delta; +- valid flag; +- time embedding; +- arm embedding。 + +两臂共享一个 2 层 causal state Transformer。状态 token 可以读取文本条件,文本 gate 初值为 0.1。编码后: + +- left 使用左臂最后一个有效 token; +- right 使用右臂最后一个有效 token; +- global 融合左右臂表示; +- 三种角色分别生成视觉主干的调制条件。 + +`use_action_history` 为关闭状态,本阶段没有把 future action 或额外 action history 接入主干。 + +## 6. 文本条件的最终实现 + +指令由冻结的 Wan UMT5-XXL 编码,embedding 维度为 4096。文本 embedding 在训练前离线缓存。 + +主干每一层均包含 visual-to-text cross-attention。新加入的文本和状态条件支路使用接近零输出但梯度非零的初始化,正式训练从头开始,没有复用之前更大模型的 World Model 权重。 + +## 7. Flow matching 的实际目标 + +latent 使用固定训练统计量标准化: + +\[ +z_\mathrm{norm}=\frac{z-\mu}{\sigma} +\] + +其中: + +- \(\mu=0.024823864160431405\) +- \(\sigma=1.9595992324017892\) + +对 future 的每个物理时间点独立采样 \(\tau\)。同一 future 时间点的三个视角和所有空间位置共享该 \(\tau\)。 + +\[ +z_\tau=\tau z_\mathrm{clean}+(1-\tau)\epsilon +\] + +\[ +v^\*=z_\mathrm{clean}-\epsilon +\] + +模型在所有有效 future view/time/spatial cell 上最小化: + +\[ +\mathcal L_\mathrm{world} += +\operatorname{MSE}(v_\theta,v^\*) +\] + +训练同时记录 recovered-clean 诊断: + +\[ +\hat z_\mathrm{clean} +=z_\tau+(1-\tau)v_\theta +\] + +context 始终是 clean latent。配置中的 `clean_past=false` 只关闭额外的 clean-past auxiliary path,不表示对 context 加噪。 + +## 8. 推理实现 + +固定可视化采用以下推理流程: + +1. future latent 从标准高斯噪声初始化; +2. context、历史 drive target 和文本作为条件; +3. 使用 10 步 `linear_quadratic` 时间表; +4. 用 Euler update 积分预测 velocity; +5. latent 反标准化; +6. 冻结 codec 解码三个视角; +7. 以 20 FPS 保存 GT/pred 对比视频。 + +## 9. 课程切换 + +### Step 0–29,999 + +- 单视角模式; +- 每个样本仅训练 left/global/right 中一个角色; +- global batch 32 的单步角色数为 11/11/10; +- 多出的角色位置循环移动; +- 连续三个 optimizer step 的角色数为 32/32/32。 + +### Step 30,000 之后 + +- 切换完整三视角 BiHub; +- 每个样本三个视角同时参与; +- 开放 global hub 汇聚和广播; +- loss 覆盖所有有效视角; +- 切换点单独保存 checkpoint。 + +角色分配基于全局样本索引,与单卡 batch 和 gradient accumulation 的切分无关。 + +## 10. 权重状态 + +每个正式 checkpoint 同时包含: + +- 在线模型参数; +- decay 0.999 的 EMA 参数。 + +训练期固定验证和固定 case 使用在线模型参数。EMA 已保存,但没有在训练期记录中被静默当作在线模型结果。 diff --git a/release-20261107/source/workspace_joint/mira/docs/world_model_stage/02_data_and_cache.md b/release-20261107/source/workspace_joint/mira/docs/world_model_stage/02_data_and_cache.md new file mode 100644 index 0000000000000000000000000000000000000000..11b15d8fe95c299f613314ee08f9a11032220fc9 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/docs/world_model_stage/02_data_and_cache.md @@ -0,0 +1,193 @@ +# 数据、缓存与训练输入 + +## 1. 最终数据范围 + +World Model 使用 RoboTwin 2.0 中的 ALOHA AgileX 数据,覆盖 50 个任务。 + +最终 episode 划分为: + +| Split | Episode 数 | +|---|---:| +| Train | 26,950 | +| Validation | 550 | +| Total | 27,500 | + +每个任务固定包含: + +- Train:539 个 episode,其中 49 clean、490 randomized; +- Validation:11 个 episode,其中 1 clean、10 randomized。 + +划分发生在 episode 级别。部署审计确认训练和验证 hash 零重叠。 + +## 2. 窗口和时间轴 + +原始视频为 30 FPS。数据窗口先对齐到 20 FPS,codec 编码后 latent 时间频率为 10 Hz。 + +一个训练样本覆盖连续 2 秒: + +| 区间 | 时长 | 20 FPS 视频帧 | 10 Hz latent | 20 Hz state | +|---|---:|---:|---:|---:| +| Context | 1 秒 | 20 | 10 | 20 | +| Future | 1 秒 | 20 | 10 | 不提供给模型 | +| 合计 | 2 秒 | 40 | 20 | 仅使用历史 20 | + +30 FPS 原始 episode 需要覆盖约 60 帧,才能提供完整 2 秒物理时长。 + +## 3. 短 episode 过滤的部署改动 + +最初在线 dataloader 会在采样时发现 52、53 帧等不足 2 秒的 episode,并持续输出 warning。这会导致: + +- 无效文件被重复打开; +- worker 时间浪费; +- 有效样本命中率下降; +- 训练日志被 warning 淹没。 + +最终实现改为训练前离线过滤: + +1. 扫描 episode; +2. 验证三视角及状态完整性; +3. 计算可用 2 秒窗口; +4. 只把合法 episode/window 写入 manifest; +5. dataloader 只从合法 manifest 采样。 + +短 episode 不再进入训练热路径。 + +## 4. 三视角数据契约 + +缓存、batch、模型和可视化统一使用: + +```text +view 0 = left +view 1 = global +view 2 = right +``` + +审计检查: + +- 三个摄像头均存在; +- 三路时间同步; +- 每路均可生成完整 20 latent step; +- view mask 与 tensor 顺序一致; +- train/validation 中同一 episode 不重复。 + +## 5. Codec latent cache + +使用冻结的 LingBot codec checkpoint。World Model 训练不更新 codec。 + +每个视角的完整窗口 latent 为: + +```text +[20, 32, 9, 12] +``` + +再切分为: + +```text +context = [10, 32, 9, 12] +future = [10, 32, 9, 12] +``` + +最终完整 cache: + +| 项目 | 状态 | +|---|---:| +| Episode | 27,500 | +| 可训练 latent window cell | 2,024,996 | +| Cache shard | 8 | +| Complete-cache 标记 | 通过 | +| Split overlap | 0 | + +cache 以 codec SHA 做内容寻址。World Model 启动时会核对 checkpoint 身份、cache 摘要、统计量和完整性标记。 + +## 6. 多视角编码方式 + +正式 cache 使用逐视角顺序编码。 + +实施过程中测试过将三个视角合并 batch 送入 codec。该方式速度更快,但与逐视角编码结果存在数值差异: + +- 最大差异约 0.1328125; +- p99 差异约 0.03125。 + +为了保持 codec 输出和既有缓存协议稳定,正式数据没有启用 `batch_views`。8 张 GPU 按 episode shard 并行,每张卡内部仍逐视角编码。 + +## 7. 文本 cache + +任务指令使用冻结 Wan UMT5-XXL BF16 encoder 离线计算: + +```text +[L, 4096], L <= 128 +``` + +cache 同时保存文本有效位。训练进程只加载 embedding 和 mask,不加载文本模型。 + +## 8. 状态预处理 + +`joint_action/vector` 被重建为: + +```text +[20, 2, 7] +``` + +数值使用训练集统计量标准化,并在标准化空间裁剪到 `[-5, 5]`。预处理还生成: + +- drive-target delta; +- history-valid mask; +- arm identity; +- 时间位置。 + +字段的冻结语义是 simulator drive target,不是 measured qpos。 + +## 9. 最终采样器 + +训练采样按以下层级进行: + +1. 均匀选任务; +2. 以 0.5/0.5 选择 clean 或 randomized 域; +3. 在任务和域内选择 episode; +4. 在 episode 内选择合法窗口。 + +该实现避免两个原始数据偏置: + +- 任务 episode 数或长度造成的任务失衡; +- randomized 数量约为 clean 十倍造成的域失衡。 + +`clean probability=0.5` 只表示数据域采样比例,与 flow noise 或 clean context 无关。 + +采样器状态可保存。prefetch 不会提前提交 checkpoint 中的 sampler cursor,恢复后可以继续原数据顺序。 + +## 10. 训练 batch 的防泄漏边界 + +World Model batch 包含: + +```text +context latent +future latent target +history drive target +history valid +instruction embedding +view/time masks +``` + +其中: + +- future latent 仅进入监督目标; +- future state 不进入模型; +- future action 不进入模型; +- action 条件模块为关闭; +- context 末端之后的信息不进入 condition。 + +该边界在 manifest 审计、dataset 输出和模型 forward 三处落实。 + +## 11. Cache 重启行为 + +完整 latent cache 生成后会写入: + +- train/validation latent manifest; +- latent normalization stats; +- cache 完整性状态; +- codec identity; +- shard 合并信息; +- preflight audit。 + +后续重启若检测到这些文件完整且摘要一致,会直接跳过 ZIP/HDF5 解压、codec 编码和全文本计算,不再重复首次预处理阶段。 + diff --git a/release-20261107/source/workspace_joint/mira/docs/world_model_stage/03_training_deployment.md b/release-20261107/source/workspace_joint/mira/docs/world_model_stage/03_training_deployment.md new file mode 100644 index 0000000000000000000000000000000000000000..8dc09b7f116c3a98bcfecfbb82a2f6cbcf9e93cd --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/docs/world_model_stage/03_training_deployment.md @@ -0,0 +1,254 @@ +# 训练部署与运行保障 + +## 1. 运行环境 + +正式训练使用名为 `mira` 的 Conda 环境。落地时的核心版本为: + +| 组件 | 版本 | +|---|---| +| PyTorch | 2.8.0+cu128 | +| CUDA runtime | 12.8 | +| Transformers | 4.57.6 | +| Hydra | 1.3.4 | +| SwanLab | 0.9.0 | + +项目还安装了 RoboTwin HDF5、视频、可视化、分布式训练和进程命名所需依赖。codec、World Model、数据预处理和离线评估共用该环境。 + +## 2. 网络环境 + +所有可能访问网络的正式入口在启动时显式清除: + +```text +http_proxy, https_proxy, all_proxy, ftp_proxy +HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, FTP_PROXY +``` + +并设置: + +```text +NO_PROXY=* +no_proxy=* +``` + +模型下载和 SwanLab 标量上传均使用直连。训练本身不依赖在线下载: + +- codec 权重已在本地; +- 文本模型权重已在本地; +- latent 和文本 embedding 已离线缓存; +- 正式训练热路径只读取本地数据。 + +## 3. 正式分布式配置 + +| 配置 | 最终值 | +|---|---| +| GPU 数量 | 8 | +| 每卡 batch | 4 | +| Gradient accumulation | 1 | +| Global batch | 32 | +| Precision | BF16 | +| 梯度归约 | FP32 | +| Matmul | TF32 enabled | +| 并行策略 | FSDP2 full shard | +| Dataloader workers | 每 rank 4 | +| Prefetch factor | 2 | + +FSDP2 对每个 Transformer block 和根模块执行 full shard。activation checkpoint wrapper 在 fully-shard 之前应用。 + +## 4. Batch 配置的实际测试 + +在模型、数据、global batch 32、学习率和 optimizer update 完全相同的前提下,对两种切分进行了 A/B 测试: + +| 每卡 batch × accumulation | 单视角吞吐 | 完整 BiHub 吞吐 | +|---|---:|---:| +| 1 × 4 | 25.801 windows/s | 17.962 windows/s | +| 4 × 1 | 37.396 windows/s | 25.898 windows/s | + +最终正式配置为 `4 × 1`。完整 BiHub 吞吐提高约 44.2%,global batch 和样本角色分配不变。 + +正式训练进入稳定区间后的实际吞吐约为 25.4 windows/s。 + +## 5. 显存 + +完整训练生命周期中观测到: + +- 每 rank peak allocated:约 15.725 GiB; +- 较早记录的进程峰值:约 17.914 GiB。 + +该数字包含完整三视角 BiHub 训练,不只是单视角 smoke test。显存没有接近 GPU 容量上限。 + +## 6. Optimizer + +| 项目 | 配置 | +|---|---| +| Optimizer | AdamW | +| Learning rate | 1e-4 | +| Betas | 0.9, 0.99 | +| Epsilon | 1e-8 | +| Weight decay | 0.1 | +| Warmup | 1,000 step | +| Minimum LR | 1e-6 | +| Gradient clip | 1.0 | +| EMA decay | 0.999 | +| Total step | 150,000 | + +配置中的 step 均指 optimizer step。 + +## 7. 正式启动流程 + +部署入口提供以下几类操作: + +1. 生成正式 episode manifest; +2. 生成文本 embedding cache; +3. 8 卡并行生成 latent cache; +4. 合并 shard 并执行 cache audit; +5. 启动正式训练; +6. 检测完整 cache 后跳过预处理并继续训练; +7. 在 tmux server/session `hc` 中启动训练窗口。 + +正式 train 启动前会: + +- 检查 codec checkpoint; +- 读取 codec SHA; +- 检查 train/validation latent manifest; +- 检查 cache complete 标记; +- 执行最多 100 个 cache sample 的 preflight; +- 要求原始 summary 和完整 cache 一致; +- 打印当前 GPU 与既有命名进程; +- 不主动杀掉同时存在的 codec 或其他训练任务。 + +## 8. 进程命名 + +World Model 相关进程不再包含 `wam` 字样。部署后使用 `syncnet_core_*` 统一命名: + +| 角色 | 名称 | +|---|---| +| 完整 pipeline | `syncnet_core_p` | +| Torch launcher | `syncnet_core_l` | +| Train rank | `syncnet_core_r0` ... `syncnet_core_r7` | +| 完整 Python title | `syncnet_core_worker_0` ... | +| Manifest | `syncnet_core_m` | +| Text cache | `syncnet_core_x` | +| Latent cache shard | `syncnet_core_c*` | +| Cache merge | `syncnet_core_g` | +| Audit | `syncnet_core_a` | +| Monitor | `syncnet_core_watch` | + +名称同时写入 process title 和 Linux `comm`,便于 `ps`、监控和定向终止识别,避免只修改 shell argv 后仍显示 Python/torchrun。 + +## 9. Smoke test + +正式部署前使用 8 卡执行过 30-step smoke test,覆盖: + +- 分布式初始化; +- FSDP2 wrap; +- 三视角 batch; +- 单视角角色分配; +- forward/backward; +- optimizer 和 scheduler; +- checkpoint 写入和恢复; +- SwanLab 标量; +- 本地日志; +- GPU 显存。 + +smoke 使用独立 manifest、cache、输出和日志,不与正式训练共享 resume 目录。确认正式流程后,smoke checkpoint 和临时训练日志被清理,不参与正式 checkpoint 自动发现。 + +## 10. 本地日志 + +正式训练本地保留: + +- `metrics.jsonl` 完整训练指标; +- validation 指标; +- 每 rank 运行日志; +- cache shard 进度; +- preflight audit; +- checkpoint 保存与恢复事件; +- 固定 case 视频、关键帧和 tensor。 + +输出规则: + +- 前 10 个 step 每步输出; +- 之后每 100 step 输出训练汇总; +- 每 1,000 step 输出固定验证; +- 每 5,000 step 保存 checkpoint 和固定可视化。 + +因此没有 console 输出的短区间不表示停止;可通过 GPU、step time、data time 和本地 JSONL 联合判断运行状态。 + +## 11. SwanLab + +SwanLab 项目固定为: + +```text +Multi_WAM +``` + +World Model 实验名为: + +```text +RoboTwin-3View-WorldModel-1B +``` + +云端只记录必要标量。正式训练上传的训练指标包括: + +- world loss; +- left/global/right loss; +- recovered-clean MSE; +- learning rate; +- gradient norm; +- windows/s; +- peak allocated memory; +- 是否进入 full BiHub; +- 单视角角色失衡量。 + +验证上传总 loss、分视角 loss 和 recovered-clean MSE。完整诊断仍写入本地 JSONL。 + +训练进程不再上传 GIF、MP4 等媒体。曾出现对象存储 PUT 400 和单个媒体上传耗时数分钟的问题;最终处理是媒体全部本地保存,SwanLab 只传标量。云日志上传失败不会终止或阻塞 optimizer step。 + +## 12. 固定验证和可视化 + +### Validation + +- 每 1,000 step; +- 固定 16 个 batch; +- validation seed 为 2026; +- noise 和 tau 确定; +- 每卡 validation batch 为 1; +- 训练结束时额外验证。 + +### Visualization + +- 每 5,000 step; +- 固定 4 个 case; +- case seed 为 2026; +- sampling steps 为 10; +- 解码三个视角 RGB; +- 输出 20 FPS GT/pred 对比; +- 保存视频、关键帧图和 tensor; +- 不上传云端。 + +固定 seed 和 case 使不同 checkpoint 可以直接比较。 + +## 13. Checkpoint + +保存频率: + +- 每 5,000 step; +- curriculum 切换点; +- 训练结束; +- 保留最近 2 个常规 checkpoint。 + +保存内容: + +- 在线模型; +- EMA; +- optimizer; +- scheduler; +- sampler; +- Python RNG; +- NumPy RNG; +- PyTorch CPU/CUDA RNG; +- global step; +- curriculum phase。 + +分布式 checkpoint 先写临时目录,完整成功后原子替换为正式目录。恢复时模型和 EMA 严格匹配;optimizer moment 只允许受控的部分兼容,并输出加载报告。 + +`auto_resume` 已启用。完整 cache 存在时,重启训练不会重新执行 ZIP/HDF5 解压、codec 编码或文本编码。 diff --git a/release-20261107/source/workspace_joint/mira/docs/world_model_stage/04_results_and_handoff.md b/release-20261107/source/workspace_joint/mira/docs/world_model_stage/04_results_and_handoff.md new file mode 100644 index 0000000000000000000000000000000000000000..e3294e78fe5bb852a0cfba8fdb988bb8d01a2e09 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/docs/world_model_stage/04_results_and_handoff.md @@ -0,0 +1,153 @@ +# 训练结果与交接事实 + +## 1. 结果说明 + +本阶段已完成 World Model 的代码、数据缓存、正式分布式 pipeline、日志、可视化和可恢复 checkpoint 部署,并获得稳定可用的三视角短时预测模型。 + +下面保留训练中的代表性固定验证记录。它们用于说明模型收敛过程和最终结构有效性,不把某个中间 step 的记录定义为完整训练终点数值。 + +## 2. 代表性收敛记录 + +| Step | 阶段 | Validation flow loss | Recovered-clean MSE | +|---:|---|---:|---:| +| 1,000 | 单视角 | 1.1082 | 0.30072 | +| 5,000 | 单视角 | 0.41333 | 0.06210 | +| 10,000 | 单视角 | 0.39307 | 0.05679 | +| 20,000 | 单视角 | 0.38257 | — | +| 29,000 | 单视角 | 0.37518 | — | +| 30,000 | 课程切换点 | 0.37543 | — | +| 31,000 | 完整 BiHub | 0.25366 | 0.02377 | +| 40,000 | 完整 BiHub | 0.22928 | 0.01919 | +| 50,000 | 完整 BiHub | 0.22592 | 0.01860 | +| 53,000 | 完整 BiHub | 0.22540 | 0.01840 | + +45k–53.5k 区间的 training loss: + +- mean:约 0.20742; +- median:约 0.20648。 + +训练后段验证 loss 稳定在约 0.225,没有出现梯度、数值或分布式训练崩坏。 + +## 3. 课程切换结果 + +单视角训练结束时,validation flow loss 约为 0.375。启用完整 BiHub 后约 1,000 step,validation flow loss 降至约 0.254,recovered-clean MSE 降至约 0.0238。 + +该变化与 step 30,000 的完整三视角通信切换对齐。之后 validation 继续稳定下降至约 0.225。 + +## 4. 分视角结果 + +完整 BiHub 阶段的代表性分视角验证: + +| Step | Left | Global | Right | +|---:|---:|---:|---:| +| 50,000 | 0.26404 | 0.21683 | 0.19717 | +| 53,000 | 0.26263 | 0.21658 | 0.19666 | + +三个视角均稳定,没有单个视角 loss 发散。left 的误差高于 global 和 right,但变化趋势同步。 + +## 5. 可视化结果 + +固定 case 对比显示: + +- 训练早期预测可以保持大体场景,但运动区域存在明显拖影和透明叠加; +- 训练后段背景、物体身份和主要结构保持稳定; +- 机械臂运动能够从 context 连续延伸; +- 三个视角生成的是同一个操作过程; +- 快速运动和遮挡区域仍比静态区域模糊; +- future 后半段的结构稳定性明显优于训练早期。 + +可视化覆盖固定 4 个 case,每次使用相同 seed、相同 context 和相同采样步数,因此不同 checkpoint 间具有可比性。 + +## 6. 性能结果 + +| 指标 | 正式完整 BiHub | +|---|---:| +| 稳定吞吐 | 约 25.4 windows/s | +| Peak allocated / rank | 约 15.725 GiB | +| 观测进程峰值 / rank | 约 17.914 GiB | +| Global batch | 32 | +| GPU | 8 | + +采用每卡 batch 4、accumulation 1 后,相比每卡 1、accumulation 4,完整 BiHub 吞吐提高约 44.2%,global batch 和训练目标未改变。 + +## 7. 已完成的部署产物 + +当前阶段已经形成以下可复用产物: + +- 1.397B 三视角 World Model 在线权重; +- 对应 EMA 权重; +- optimizer/scheduler/sampler/RNG 完整恢复状态; +- 冻结 LingBot codec 及其身份摘要; +- 完整三视角 latent cache; +- 完整 instruction embedding cache; +- 训练/验证 episode manifest; +- latent normalization 统计量; +- state normalization 与字段语义; +- preflight audit; +- 本地训练与验证 JSONL; +- 固定 case 解码结果; +- 8 卡正式启动封装; +- 直连 SwanLab 标量日志; +- 独立的离线评估入口。 + +## 8. 交给下一位 agent 的固定事实 + +接续设计时,可以把以下内容视为本阶段已确定事实: + +### 模型事实 + +- 主干为 2048 × 16,约 1.397B 参数; +- 三视角顺序为 left/global/right; +- 空间通信为 global hub; +- 时间 attention 位于 0、4、8、12、15 层; +- context/future 均为 10 个 latent step; +- latent 为 10 Hz; +- 本阶段只训练 world loss; +- action 模块关闭; +- 在线权重和 EMA 均已保存。 + +### 数据事实 + +- 数据为 50 个 RoboTwin ALOHA AgileX 任务; +- episode split 为 train 26,950 / validation 550; +- 训练采样按 task uniform、clean/randomized 0.5/0.5; +- context 为过去 1 秒; +- future target 为未来 1 秒; +- state 是 20 Hz simulator drive target; +- state 不是 measured qpos; +- future state/action 不进入 World Model; +- codec 和文本 encoder 均已冻结并缓存。 + +### 部署事实 + +- 环境名为 `mira`; +- 正式训练为 8 卡 BF16 FSDP2; +- global batch 为 32; +- cache 完整时重启直接进入训练; +- 每 100 step 有本地训练汇总; +- 每 1,000 step 固定验证; +- 每 5,000 step checkpoint 和固定 case; +- SwanLab 项目为 `Multi_WAM`; +- 云端只传必要标量; +- 所有网络操作走直连; +- 训练进程统一使用 `syncnet_core_*` 命名。 + +## 9. 结果的解释范围 + +当前结果能够说明: + +- 模型学到了稳定的 1 秒三视角 latent dynamics; +- 完整 BiHub 的三视角结果优于课程切换前的单视角结果; +- 模型训练、验证、可视化和恢复 pipeline 已跑通; +- checkpoint 可以作为后续设计所使用的既有 World Model backbone。 + +当前结果本身不表示: + +- 已经训练了动作策略; +- action-conditioned world prediction 已经完成; +- 模型已经具备闭环任务成功率; +- simulator drive target 可以直接替代真实机器人 measured qpos; +- 一秒预测结果能够直接代表多秒 rollout。 + +这些边界只是描述当前产物,不包含对下一阶段结构或训练方式的建议。 + diff --git a/release-20261107/source/workspace_joint/mira/docs/world_model_stage/README.md b/release-20261107/source/workspace_joint/mira/docs/world_model_stage/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c6a47e42511efadd1a119973e665fdc1d6591a58 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/docs/world_model_stage/README.md @@ -0,0 +1,57 @@ +# World Model 阶段实施总结 + +## 文档用途 + +这组文档面向接手后续设计的 agent,记录 World Model 阶段最终实际落地的状态。 + +文档只回答以下问题: + +- 最终训练的模型是什么; +- 实际使用了什么数据和输入输出契约; +- 训练前处理、分布式训练、日志、可视化和恢复如何部署; +- 实施过程中解决了哪些会影响训练有效性或效率的问题; +- 已完成模型表现到什么程度; +- 哪些事实需要作为后续设计的既有输入。 + +这里不再论证原计划中的方案,也不给出下一阶段的模型或训练建议。 + +## 阶段最终状态 + +| 项目 | 最终状态 | +|---|---| +| 训练范围 | `world_only` | +| 模型规模 | 1,397,471,023 参数 | +| 主干 | hidden size 2048,16 层 | +| 视觉输入 | 三视角 LingBot codec latent | +| 条件输入 | 历史双臂 drive target、任务指令 | +| 时间范围 | 过去 1 秒预测未来 1 秒 | +| 训练目标 | Future latent flow matching | +| 多视角结构 | BiHub | +| 课程 | 前 30k 单视角,之后完整三视角 | +| 数据 | RoboTwin 2.0,ALOHA AgileX,50 个任务 | +| 正式训练 | 8 卡 BF16 FSDP2 full shard | +| 全局 batch | 32 | +| 训练长度 | 150,000 optimizer step | +| 日志 | 本地完整记录 + SwanLab 必要标量 | +| 可视化 | 每 5,000 step 固定 4 个 case | +| Checkpoint | 模型、EMA、优化器、采样器和 RNG 完整保存 | +| Action 模块 | 本阶段关闭 | + +World Model 已达到稳定可用状态。文档中的数值结果采用训练过程中的代表性固定验证记录,用于说明收敛和多视角训练有效性,不将某个中间 checkpoint 标记为最终模型数值。 + +## 文档列表 + +1. [最终模型实现](01_final_model.md) +2. [数据、缓存与训练输入](02_data_and_cache.md) +3. [训练部署与运行保障](03_training_deployment.md) +4. [训练结果与交接事实](04_results_and_handoff.md) + +## 交接时的解释边界 + +- 本阶段 checkpoint 是 World Model backbone。 +- 模型生成未来三视角 latent,不输出机器人动作。 +- action 标签没有进入本阶段模型输入或 loss。 +- state 字段是 simulator drive target,不是 measured qpos。 +- context 是真实 clean latent;`clean/randomized` 是数据域分类。 +- 训练结果证明短时三视角视觉动力学可用,不等价于闭环策略已经完成。 + diff --git a/release-20261107/source/workspace_joint/mira/docs/world_model_stage/world_model_stage.zip b/release-20261107/source/workspace_joint/mira/docs/world_model_stage/world_model_stage.zip new file mode 100644 index 0000000000000000000000000000000000000000..cfe220791cb36e6461e0768a268875c48409e35b --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/docs/world_model_stage/world_model_stage.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:109f78dcb0fe4fe8582a25fe673de951a814d8a6a28195c8c7c357c25b69dc10 +size 14753 diff --git a/release-20261107/source/workspace_joint/mira/docs/world_v6_stage/README.md b/release-20261107/source/workspace_joint/mira/docs/world_v6_stage/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6e60d403ac0c45ec41ed50e7b7dd9cbdf7f2b013 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/docs/world_v6_stage/README.md @@ -0,0 +1,49 @@ +# BiHub World v6 最终实现说明 + +本目录记录 `world_model_v6_stage` 方案在当前代码和真实 RoboTwin2.0 artifact 上的最终部署结果。范围仅为 World v6;Action Head 不在本阶段内。正式训练尚未启动,当前状态是代码、全量数据 join、身份锁、阶段门和 GPU 6/7 smoke 均已就绪。 + +## 1. 最终模型 + +World 主干保持方案锁定的 `hidden=2048, layers=16, query_heads=16, kv_heads=4`,共有 `1,349,974,130` 个参数。输入输出合同为: + +- 三视角顺序固定为 `Left / Global / Right`; +- 10 个 clean context latent + 10 个 future latent,10 Hz; +- latent 形状固定为 `[32,9,12]`; +- future 使用逐帧独立 flow time,但同一 future frame 的 time 在三视角共享; +- 只对 future 计算 flow matching loss,context 不加噪、不计 loss; +- 不读取 future action、future state 或 instruction text embedding。 + +当前语义条件由三路隔离的 frozen Qwen3-VL current lanes 产生。每路完整 image/text/role hidden sequence 经共享的一层 8-query、512-wide Current Resampler 得到 `[3,8,512]` anchors。History Builder 只读取最后 4 个 clean latent,按 `3x4` pooling 和 time-major/row-major 顺序得到每视角 48 个 token。HHR 先由 Global gather 三路 history,再用同一个 Local block 将更新后的 Global condition 分别 relay 给 Left/Right;不存在 Left/Right raw history 直连。 + +physical state 使用 20-step simulator drive-target history,State Encoder 不接 instruction。World block 的顺序为 BiHub spatial、指定层 causal temporal、view-matched condition cross-attention、physical-state/flow-time/physical-horizon AdaLN-SwiGLU。flow 插值、target 和 reduction 明确保留 FP32。 + +## 2. 初始化与阶段衔接 + +旧 World `checkpoint-80000` 的既有 64-case online/EMA 审计选择 EMA。迁移结果为: + +- loaded 511 keys; +- new 131 keys; +- dropped 74 keys; +- shape mismatch 0; +- 所有旧 text/state-text 分支均显式列为 dropped。 + +5k bootstrap 只训练 Current Resampler、History/HHR、新 condition cross-attention 和 state adapters,旧主干冻结。bootstrap checkpoint 选择后会同时导出: + +1. frozen Current Resampler; +2. 被选中 online/EMA 分支的完整 v6 system initialization。 + +100k main 从第 2 项起步,而不是重新回到迁移初值;Current Resampler 在 main 中冻结。该衔接用于保留 bootstrap 已学到的 HHR/state/cross-attention 接口。 + +## 3. 数据与身份 + +全量合法 join 为 train `1,472,828`、validation `29,668`,共 `1,502,496` 个 window。每个 window 使用: + +- context latent `k..k+9`; +- Qwen current RGB20 `2k+19`,对应 30 Hz source index 的确定性映射; +- history latent `k+6..k+9`; +- future latent `k+10..k+19`; +- 20 个 factual drive-target state 全部有效。 + +anchor cache 为 8 个稳定 SHA shard,纯 BF16 tensor 预算 `34.389 GiB`。cache identity 锁定 codec、source/window manifest、Qwen revision/files、prompt、attention implementation、RGB preprocessing、Resampler selection/weights 和 locator SHA。 + +详细部署和命令见 [deployment.md](deployment.md),实际 smoke 和偏差说明见 [smoke_report.md](smoke_report.md)。 diff --git a/release-20261107/source/workspace_joint/mira/docs/world_v6_stage/deployment.md b/release-20261107/source/workspace_joint/mira/docs/world_v6_stage/deployment.md new file mode 100644 index 0000000000000000000000000000000000000000..08ac3203a82426a85f2c7b5e78d9de1d12a568a0 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/docs/world_v6_stage/deployment.md @@ -0,0 +1,80 @@ +# World v6 训练部署与阶段门 + +## 1. 环境和网络 + +使用现有 `mira` Conda 环境:Python 3.12.13、PyTorch 2.8.0+cu128、Transformers 4.57.6。Qwen 固定为 `Qwen/Qwen3-VL-2B-Instruct` revision `89644892e4d85e24eaac8bacfd4f463576704203`,attention implementation 在 bootstrap/cache/deployment 三处统一为 SDPA。 + +唯一入口为: + +```bash +cd /private/codes/exp/haocheng_workspace/projects/Mutil_WAM/mira +bash scripts/launch_world_v6.sh +``` + +launcher 会清除大小写全部 HTTP/HTTPS/ALL/FTP proxy,并设置 `NO_PROXY=*`。Qwen 已下载到 workspace 的 `models/`,训练和 cache 阶段同时设置 Hugging Face/Transformers offline,热路径不会访问网络。SwanLab 只在 rank 0 启动,project 为 `Multi_WAM`,token 从已有 token file 读取但不上传;客户端也再次强制直连。 + +## 2. 严格执行顺序 + +预备阶段已完成,命令可凭 identity 幂等复核: + +```bash +bash scripts/launch_world_v6.sh prepare-qwen +bash scripts/launch_world_v6.sh prepare-formal +``` + +正式 GPU 阶段均有防误启动开关。只有在独占的 8-GPU 训练节点上明确设置下列变量才允许执行: + +```bash +export MIRA_V6_ALLOW_FORMAL=YES +export MIRA_V6_GPUS=0,1,2,3,4,5,6,7 +``` + +阶段顺序: + +```bash +# M1:64-window overfit,最多 3000 optimizer steps +bash scripts/launch_world_v6.sh overfit64 + +# S0:online-Qwen 8-GPU 200-step 技术 canary +bash scripts/launch_world_v6.sh canary-bootstrap + +# Phase B:正式 5k online-Qwen bootstrap +bash scripts/launch_world_v6.sh formal-bootstrap + +# 在 1k/3k/5k 固定验证候选中选择一次并冻结 +bash scripts/launch_world_v6.sh select-formal-anchor + +# Phase C:全量 8-shard anchor cache + 200-window online parity audit +bash scripts/launch_world_v6.sh formal-cache + +# cached-anchor 8-GPU 200-step 技术 canary +bash scripts/launch_world_v6.sh canary-main + +# Phase D:正式 100k main +bash scripts/launch_world_v6.sh formal-main + +# Phase E:online/EMA fixed evaluation、干预、10-step rollout 和 MP4 +bash scripts/launch_world_v6.sh formal-eval +``` + +正式配置保持 global batch 32:bootstrap 为 `per_gpu=1, accumulation=4`,main 为 `per_gpu=4, accumulation=1`。第一次正式 run 不改变模型几何、global batch、flow-time distribution、optimizer 或 loss。 + +## 3. 恢复、日志和可视化 + +checkpoint 使用 FSDP2 distributed checkpoint,包含 model、optimizer、scheduler、EMA、sampler cursor、Python/NumPy/Torch/CUDA RNG、resolved config 和全部 artifact identity。只把含 `trainer_state.json` 的原子完成目录视为可恢复点;`.tmp`/partial 目录不会进入搜索。SIGTERM/SIGINT 在下一个安全 optimizer 边界写 recovery checkpoint。 + +本地 `metrics.jsonl` 每 100 步记录: + +- total/Left/Global/Right loss、10 个 horizon loss、4 个 flow-time bucket loss; +- clean/randomized 与 task loss/count; +- new/inherited 或 bootstrap 各组 gradient norm/LR; +- anchor/condition norm、finite rate、HHR attention mass 和 condition gates; +- windows/s、data/cache time、GPU peak。 + +SwanLab 上传必要 scalar,不上传 raw data、anchor cache 或 checkpoint。每 1000 步用同一固定 cases/noise 分别评估 online 和 EMA,并执行 null/shuffled/role 干预。每 5000 步分别保存 online/EMA 的固定 10-step latent rollout;rank 0 用 frozen codec 解码最多 4 个固定 case,生成本地三视角 GT/预测 MP4,云端不传大视频。 + +进程名固定为 `syncnet_v6_b*`、`syncnet_v6_c*`、`syncnet_v6_r*`、`syncnet_v6_e*`;不会主动终止其他任务。 + +## 4. Fail-closed 条件 + +preflight 会逐文件核对 Qwen SHA,并核对 codec/config、source manifests、window manifests、旧 World selection、migration、Resampler、RGB preprocessing 和 anchor cache identities。以下任一情况都会中止:future leakage、camera/state 语义变化、train/val episode overlap、未知迁移 key、cache/window 非双射、非有限 tensor、frozen 参数进入 optimizer、identity/SHA 变化、或磁盘低于动态硬预算。 diff --git a/release-20261107/source/workspace_joint/mira/docs/world_v6_stage/smoke_report.md b/release-20261107/source/workspace_joint/mira/docs/world_v6_stage/smoke_report.md new file mode 100644 index 0000000000000000000000000000000000000000..0e35f920e00555f7579c22061a7b6d98b9b61ffb --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/docs/world_v6_stage/smoke_report.md @@ -0,0 +1,32 @@ +# World v6 部署与 Smoke 记录 + +记录日期:2026-08-04 UTC。仅使用物理 GPU 6、7,与既有高负载任务并行;没有启动正式 5k/100k 训练。 + +## 1. 已通过项目 + +- Qwen 真实 RoboTwin 输入:RGB `[1,3,3,288,384]`,3 条隔离 lane,grid 均为 `[1,18,24]`,每 lane 108 image tokens,hidden `[1,3,146,2048]` BF16 且全 finite;Qwen eval、0 requires-grad、0 grad。Qwen 单卡审计自身峰值 `4.185 GiB`。 +- bootstrap:全尺寸 2048x16、FSDP2、两卡各 1 window,完成 forward/backward/optimizer/atomic checkpoint;loss `0.268555`、grad norm `0.273`、自身峰值 `10.65 GiB/卡`。 +- cache:train/val 各 8 个 smoke window,8 个稳定 shard;row/window join 双射、finite rate 1.0;在线与 cache cosine 1.0、MAE/max error 0,重复生成逐 bit 一致。 +- main:从被选中的完整 bootstrap system initialization 起步,Resampler 冻结;完成 forward/backward/optimizer/checkpoint;loss `0.248535`、grad norm `0.427`、自身峰值 `14.42 GiB/卡`。随后新进程 auto-resume 成功读取完整状态。 +- evaluator:online/EMA fixed validation、null/shuffled/role/history/global 干预和 10-step rollout 均运行完成;两分支各 2 个 case 解码为 40 帧、20 FPS、`768x864` MP4。 +- 测试:方案指定的 47 个测试名称全部实现,另含 5 个 sampler/RGB/checkpoint-retention 边界测试;最终 `52 passed`。ruff、py_compile、shell syntax 全通过。 + +两块共享 H200 在 smoke 前已有约 100 GiB/卡占用和 99–100% utilization,剩余约 42 GiB。上述 windows/s 受同机任务竞争严重影响,不作为正式吞吐结论;显存数是本 v6 进程的 `torch.cuda.max_memory_allocated`,不是整卡总占用。 + +## 2. 按真实 artifact 调整的地方 + +1. 方案引用的两个上级 v6 文档在服务器上不存在,因此以 `world_model_v6_stage` 四份文档、真实 checkpoint/config/manifests 为权威,没有推断缺失内容。 +2. 方案中的 `2,024,996` 实际是 latent-cell 口径,不是可采样 window 数。部署按真实 join 使用 `1,502,496`,anchor 纯 tensor 因而为 `34.389 GiB`,并使用动态磁盘预算。 +3. 旧 checkpoint 的真实 trainer 是 DDP/global batch 256,与旧文字记录不一致。v6 只迁移被审计的模型权重;v6 优化合同仍严格保持 FSDP2/global batch 32。 +4. 当前环境没有 FlashAttention。为避免 bootstrap/cache/部署数值路径漂移,三处统一锁定 SDPA,不做混用。 +5. 方案写“原图保留 288x384、无 resize”,但实际 RoboTwin JPEG 为 240x320。两者均为 4:3;部署固定使用与 codec 一致的 antialiased bilinear、无裁剪、无 letterbox resize 到 288x384,并将该实现身份写入 cache identity。 +6. 旧 action-history loader 在 `latent_start=0` 会因不存在 previous action 而产生 invalid mask;v6 不读取 action,20 个 simulator drive-target state 均为 factual,因此单独实现为全 valid,避免错误丢弃合法窗口。 +7. 初版 main 只载入 Resampler 会丢失 bootstrap 学到的 HHR/state/cross-attention。已改为从选择后的完整 bootstrap online/EMA system 起步,再冻结 Resampler。这是为保持方案训练语义而做的必要修正。 +8. smoke 子集只覆盖少量 task,原 sampler 从完整 task vocabulary 取样会命中空桶。现对 bounded manifest 只从实际 indexed tasks 采样;全量 sampler 的 task/domain/episode 分层逻辑未改变。 +9. 固定验证最初遗漏 BF16 autocast,已在 smoke 中暴露并修复;flow path/loss 仍显式 FP32。FSDP2 gate 日志也改为 local-shard sum/count 归约,避免直接 all-reduce DTensor。 +10. Qwen 当前帧除 manifest 中的 half-up 20→30 FPS 公式外,运行时还直接读取并核对 latent cache 的 `source_index_i32`;任何规则漂移都会 fail closed,不会静默读取错帧。 +11. checkpoint 清理原本统一读取主训练保留表,可能在 bootstrap 5k 时误删 1k 候选;现按 phase 分别使用 bootstrap `1k/3k/5k` 与 main `80k/90k/100k` 保留表,并有独立回归测试。 + +## 3. 尚未执行的效果门 + +受“本机只能使用 GPU 6–7 且不可启动正式训练”的约束,以下保持未执行:64-window 3000-step overfit、8-GPU 200-step canary、5k bootstrap、全量 anchor cache、100k main、正式 online/EMA/旧 v5 paired evaluation。代码和命令已准备,但不能用 1-step smoke 指标声称 v6 的最终条件有效性或模型效果。 diff --git a/release-20261107/source/workspace_joint/mira/examples/README.md b/release-20261107/source/workspace_joint/mira/examples/README.md new file mode 100644 index 0000000000000000000000000000000000000000..44ce8885f6e686de11c8147e4f4561a6ab1b5efc --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/examples/README.md @@ -0,0 +1,10 @@ +# Examples + +- **`explore.py`** — a guided, interactive tour of the dataset (a [marimo](https://marimo.io) + notebook). Pick a match and clip and every view re-renders: a synchronised 4-player video grid with + a keyboard overlay, a top-down arena radar, a HUD, and the per-frame game state. + + ```bash + pixi run explore # read-only app view + pixi run edit # editable (headless on :2718; SSH-tunnel to view) + ``` diff --git a/release-20261107/source/workspace_joint/mira/examples/explore.py b/release-20261107/source/workspace_joint/mira/examples/explore.py new file mode 100644 index 0000000000000000000000000000000000000000..0746fa6d614c893bb76baa998dd482699165c643 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/examples/explore.py @@ -0,0 +1,249 @@ +"""A guided tour of the 4-player Rocket League dataset. + +Run it as an app, or open it editable to change the match/clip and re-render live: + + pixi run explore # read-only app view + pixi run edit # editable (headless on :2718; SSH-tunnel to view) + +Each section explains one facet of the data — what a sample is, the four co-temporal perspectives, +frame-aligned keyboard actions, master-clock events, and per-frame game state — and shows it on a +clip you pick. +""" + +import marimo + +app = marimo.App(width="full") + + +@app.cell +def _(): + import base64 + import json + + import marimo as mo + + from mira.data import RocketScienceDataset, physics, viz + + return RocketScienceDataset, base64, json, mo, physics, viz + + +@app.cell +def _(mo): + mo.md( + """ + # 🚗 The 4-player Rocket League dataset + + Time-aligned **video · keyboard actions · game events · per-frame game state** for all four + players of a 2v2 match. This notebook walks through what a sample contains; pick a match and + clip in the controls below and every section re-renders on it. + """ + ) + return + + +@app.cell +def _(mo): + repo_in = mo.ui.text("kyutai/rocket-science", label="HuggingFace dataset repo") + split_in = mo.ui.text("test", label="Split") + local_in = mo.ui.text("", full_width=True, label="…or a local dataset directory (overrides the repo)") + mo.accordion( + { + "⚙️ Data source": mo.vstack( + [ + mo.md("Load a split from the Hub, or point at a local dataset directory."), + repo_in, + split_in, + local_in, + ] + ) + } + ) + return local_in, repo_in, split_in + + +@app.cell +def _(RocketScienceDataset, local_in, mo, repo_in, split_in): + try: + if local_in.value.strip(): + ds = RocketScienceDataset.from_local(local_in.value.strip()) + else: + ds = RocketScienceDataset.from_hub(repo_in.value.strip(), split=split_in.value.strip() or None) + _err = None + except Exception as exc: # surface the load error in the UI rather than crashing the notebook + ds, _err = None, str(exc) + mo.stop( + ds is None, + mo.callout(mo.md(f"Couldn't load the dataset.\n\n```\n{_err}\n```"), kind="danger"), + ) + return (ds,) + + +@app.cell +def _(ds, mo): + _cf = ds.index.entries[0].chunk_frames + _desc = f"{_cf[0]} frames each" if len(set(_cf)) == 1 else f"{min(_cf)}–{max(_cf)} frames" + mo.md( + f""" + ## 1 · What a sample is + + The dataset is served as short (~4 s, 80 frames at 20 fps) windows of a match, each bundling + all four players' synchronised views. A **clip** is a fixed-length, fps-downsampled slice you + read out of one — pick its length and frame rate in the controls below. + + Loaded **{len(ds.match_ids())}** match(es); the first has **{len(_cf)}** such windows of {_desc}. + """ + ) + return + + +@app.cell +def _(ds, mo): + match_dd = mo.ui.dropdown(ds.match_ids(), value=ds.match_ids()[0], label="Match", searchable=True) + persp = mo.ui.dropdown( + ["all", "player1", "player2", "player3", "player4", "random"], value="all", label="Perspective" + ) + fps = mo.ui.dropdown(["20", "10", "5"], value="10", label="Target fps") + # Default to a full ~4 s window (40 frames @ 10 fps) rather than a short 1 s loop. + clip_len = mo.ui.slider(4, 80, value=40, step=4, label="Clip length", show_value=True) + mo.vstack([match_dd, mo.hstack([persp, fps, clip_len], justify="start", gap=1.5)]) + return clip_len, fps, match_dd, persp + + +@app.cell +def _(clip_len, ds, fps, match_dd, mo): + # Enumerate clips without decoding (cheap) to size the selector; an over-long clip raises, which + # we surface as a hint rather than a crash. + try: + _n = len(ds.load_match(match_dd.value, clip_len=clip_len.value, target_fps=int(fps.value), decode=False)) + clip_idx = mo.ui.number(0, max(0, _n - 1), value=0, label=f"Clip (0–{max(0, _n - 1)})") + _out = clip_idx + except ValueError as exc: + clip_idx = None + _out = mo.callout(str(exc), kind="warn") + _out + return (clip_idx,) + + +@app.cell +def _(clip_idx, clip_len, ds, fps, match_dd, mo, persp): + mo.stop(clip_idx is None, mo.md("_Reduce the clip length so it fits._")) + clip = ds.load_match( + match_dd.value, + clip_len=clip_len.value, + target_fps=int(fps.value), + perspective=persp.value, + clip_ids=[clip_idx.value], + )[0] + mo.md( + f"**Clip {clip.clip_id}** · {clip.actions.shape[1]} steps @ {clip.target_fps} fps · " + f"players {clip.player_ids} (teams {clip.teams})" + ) + return (clip,) + + +@app.cell +def _(base64, mo): + def video_html(mp4: bytes): + _b = base64.b64encode(mp4).decode() + return mo.Html( + f'' + ) + + return (video_html,) + + +@app.cell +def _(clip, mo, video_html, viz): + mo.vstack( + [ + mo.md( + """ + ## 2 · Four co-temporal perspectives + + Every player records the same match from their own camera. Here all selected + perspectives are tiled into one **frame-synchronised** video, grouped by team — + 🔵 blue on top, 🟠 orange on the bottom — each framed in its team colour with a + live keyboard overlay. + """ + ), + video_html(viz.clip_grid_video(clip)), + ] + ) + return + + +@app.cell +def _(mo): + mo.md( + """ + ## 3 · Frames ↔ actions + + The game is keyboard-only. Each frame has a `{"keys": [...]}` line; the loader turns it into a + multi-hot `(P, T, 9)` tensor over a fixed key vocabulary, OR-ing presses over each downsample + window so frames and actions stay aligned. Below: when each key is held over the clip, with + in-window events marked. + """ + ) + return + + +@app.cell +def _(clip, viz): + viz.keystroke_timeline(clip, perspective=0) + return + + +@app.cell +def _(clip, mo): + # `master_sec or 0.0` normalizes a -0.0 (kickoff at the very start) to 0.0. + _rows = "\n".join(f"- `{e.event_name}` @ {e.master_sec or 0.0:.2f}s" for e in clip.events) + # Built flush-left (not an indented triple-quote) so the spliced bullet list renders as markdown. + mo.md( + "## 4 · Game events on the master clock\n\n" + "Discrete events (kickoffs, goals, demolitions, goal replays) live on a single match-wide " + "master clock shared by all perspectives, and map onto each perspective's frames via its " + "`recording_offset_sec`. `exclude_replays=True` skips clips overlapping goal-replay segments." + "\n\nEvents overlapping this clip:\n\n" + (_rows or "_(none in this window)_") + ) + return + + +@app.cell +def _(clip, json, mo, video_html, viz): + _parts = [ + mo.md( + """ + ## 5 · Per-frame game state + + Alongside video and actions, each frame carries the world state. `clip.physics` is one + list of per-frame state dicts per perspective, frame-aligned with the video. Below: the + state animated as a top-down arena radar + HUD, then the **actual fields** — one decoded + frame of state and the per-perspective metadata. + """ + ) + ] + if clip.physics is not None: + _fr = clip.physics[0][0] + _peek = { + "game": _fr["game"], + "ball": _fr["ball"], + "cars": [_fr["cars"][0], f"... ({len(_fr['cars'])} cars, one shown)"], + } + _parts += [ + video_html(viz.clip_grid_with_radar_video(clip)), + mo.md("**One frame of state** — `clip.physics[0][0]` (the other cars share this shape):"), + mo.md("```json\n" + json.dumps(_peek, indent=2) + "\n```"), + ] + else: + _parts.append(mo.md("_This dataset carries no physics track._")) + _parts += [ + mo.md("**Per-perspective metadata** — `clip.metadata[0]`:"), + mo.md("```json\n" + json.dumps(clip.metadata[0], indent=2, default=str) + "\n```"), + ] + mo.vstack(_parts) + return + + +if __name__ == "__main__": + app.run() diff --git a/release-20261107/source/workspace_joint/mira/pixi.lock b/release-20261107/source/workspace_joint/mira/pixi.lock new file mode 100644 index 0000000000000000000000000000000000000000..9c8979d0063362100b54a9a0e3a195ab98e83ce5 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/pixi.lock @@ -0,0 +1,1781 @@ +version: 6 +environments: + default: + channels: + - url: https://conda.anaconda.org/conda-forge/ + options: + pypi-prerelease-mode: if-necessary-or-explicit + packages: + linux-64: + - conda: https://conda.anaconda.org/conda-forge/linux-64/_openmp_mutex-4.5-20_gnu.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/alsa-lib-1.2.16.1-hb03c661_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/aom-3.9.1-hac33072_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/bzip2-1.0.8-hda65f42_9.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/ca-certificates-2026.6.17-hbd8a1cb_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/cairo-1.18.4-he90730b_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/dav1d-1.2.1-hd590300_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/dbus-1.16.2-h24cb091_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/ffmpeg-7.1.1-gpl_hbbdf940_911.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/font-ttf-dejavu-sans-mono-2.37-hab24e00_0.tar.bz2 + - conda: https://conda.anaconda.org/conda-forge/noarch/font-ttf-inconsolata-3.000-h77eed37_0.tar.bz2 + - conda: https://conda.anaconda.org/conda-forge/noarch/font-ttf-source-code-pro-2.038-h77eed37_0.tar.bz2 + - conda: https://conda.anaconda.org/conda-forge/noarch/font-ttf-ubuntu-0.83-h77eed37_3.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/fontconfig-2.18.1-h27c8c51_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/fonts-conda-ecosystem-1-0.tar.bz2 + - conda: https://conda.anaconda.org/conda-forge/noarch/fonts-conda-forge-1-hc364b38_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/fribidi-1.0.16-hb03c661_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/gdk-pixbuf-2.44.7-h2b0a6b4_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/gmp-6.3.0-hac33072_2.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/graphite2-1.3.15-hecca717_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/harfbuzz-14.2.1-h6083320_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/icu-78.3-h33c6efd_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/intel-gmmlib-22.10.0-hb700be7_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/intel-media-driver-25.3.4-hecca717_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/lame-3.100-h166bdaf_1003.tar.bz2 + - conda: https://conda.anaconda.org/conda-forge/linux-64/ld_impl_linux-64-2.45.1-default_hbd61a6d_102.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/lerc-4.1.0-hdb68285_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/level-zero-1.29.0-hb700be7_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libabseil-20250512.1-cxx17_hba17884_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libass-0.17.4-h96ad9f0_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libcap-2.78-hd0affe5_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libdeflate-1.25-h17f619e_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libdrm-2.4.127-hb03c661_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libegl-1.7.0-ha4b6fd6_3.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libexpat-2.8.1-hecca717_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libffi-3.5.2-h3435931_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libflac-1.5.0-he200343_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libfreetype-2.14.3-ha770c72_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libfreetype6-2.14.3-h73754d4_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libgcc-15.2.0-he0feb66_19.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libgcc-ng-15.2.0-h69a702a_19.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libgl-1.7.0-ha4b6fd6_3.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libglib-2.88.2-h0d30a3d_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libglvnd-1.7.0-ha4b6fd6_3.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libglx-1.7.0-ha4b6fd6_3.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libgomp-15.2.0-he0feb66_19.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libhwloc-2.13.0-default_he001693_1000.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libiconv-1.18-h3b78370_2.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libjpeg-turbo-3.1.4.1-hb03c661_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/liblzma-5.8.3-hb03c661_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libnsl-2.0.1-hb9d3cd8_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libogg-1.3.5-hd0c01bc_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-2025.2.0-hb617929_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-auto-batch-plugin-2025.2.0-hed573e4_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-auto-plugin-2025.2.0-hed573e4_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-hetero-plugin-2025.2.0-hd41364c_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-intel-cpu-plugin-2025.2.0-hb617929_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-intel-gpu-plugin-2025.2.0-hb617929_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-intel-npu-plugin-2025.2.0-hb617929_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-ir-frontend-2025.2.0-hd41364c_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-onnx-frontend-2025.2.0-h1862bb8_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-paddle-frontend-2025.2.0-h1862bb8_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-pytorch-frontend-2025.2.0-hecca717_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-tensorflow-frontend-2025.2.0-h0767aad_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-tensorflow-lite-frontend-2025.2.0-hecca717_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libopus-1.6.1-h280c20c_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libpciaccess-0.19-hb03c661_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libpng-1.6.58-h421ea60_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libprotobuf-6.31.1-hfb7daa7_5.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/librsvg-2.62.3-h4c96295_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libsndfile-1.2.2-hc7d488a_2.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libsqlite-3.53.3-h0c1763c_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libstdcxx-15.2.0-h934c35e_19.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libstdcxx-ng-15.2.0-hdf11a46_19.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libsystemd0-257.13-h084b8d7_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libtiff-4.7.1-h9d88235_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libudev1-257.13-h084b8d7_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libunwind-1.8.3-h65a8314_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/liburing-2.14-hb700be7_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libusb-1.0.29-h73b1eb8_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libuuid-2.42.2-h5347b49_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libva-2.23.0-he1eb515_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libvorbis-1.3.7-h54a6638_2.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libvpl-2.15.0-h54a6638_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libvpx-1.14.1-hac33072_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libvulkan-loader-1.4.341.0-h5279c79_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libwebp-base-1.6.0-hd42ef1d_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libxcb-1.17.0-h8a09558_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libxcrypt-4.4.36-hd590300_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libxkbcommon-1.13.2-hca5e8e5_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libxml2-16-2.15.3-hca6bf5a_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libxml2-2.15.3-h49c6c72_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libzlib-1.3.2-h25fd6f3_2.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/mpg123-1.32.9-hc50e24c_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/ncurses-6.6-hdb14827_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/ocl-icd-2.3.4-hb03c661_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/opencl-headers-2025.06.13-hecca717_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/openh264-2.6.0-h65dd3cf_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/openssl-3.6.3-h35e630c_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/pango-1.56.4-hda50119_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/pcre2-10.47-haa7fec5_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/pixman-0.46.4-h54a6638_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/pthread-stubs-0.4-hb9d3cd8_1002.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/pugixml-1.15-h3f63f65_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/pulseaudio-client-17.0-h9a6aba3_3.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/python-3.12.13-hd63d673_0_cpython.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/readline-8.3-h853b02a_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/sdl2-2.32.56-h54a6638_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/sdl3-3.4.10-hdeec2a5_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/snappy-1.2.2-h03e3b7b_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/svt-av1-3.1.2-hecca717_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/tbb-2023.0.0-hab88423_2.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/tk-8.6.13-noxft_h366c992_103.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/tzdata-2025c-hc9c84f9_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/uv-0.11.25-h26efc2c_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/wayland-1.25.0-hd6090a7_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/wayland-protocols-1.49-hd8ed1ab_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/x264-1!164.3095-h166bdaf_2.tar.bz2 + - conda: https://conda.anaconda.org/conda-forge/linux-64/x265-3.5-h924138e_3.tar.bz2 + - conda: https://conda.anaconda.org/conda-forge/linux-64/xkeyboard-config-2.48-h280c20c_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libice-1.1.2-hb9d3cd8_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libsm-1.2.6-he73a12e_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libx11-1.8.13-he1eb515_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxau-1.0.12-hb03c661_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxcursor-1.2.3-hb9d3cd8_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxdmcp-1.1.5-hb03c661_1.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxext-1.3.7-hb03c661_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxfixes-6.0.2-hb03c661_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxi-1.8.3-hb03c661_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxrandr-1.5.5-hb03c661_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxrender-0.9.12-hb9d3cd8_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxscrnsaver-1.2.4-hb9d3cd8_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxtst-1.2.5-hb9d3cd8_3.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/zstd-1.5.7-hb78ec9c_6.conda +packages: +- conda: https://conda.anaconda.org/conda-forge/linux-64/_openmp_mutex-4.5-20_gnu.conda + build_number: 20 + sha256: 1dd3fffd892081df9726d7eb7e0dea6198962ba775bd88842135a4ddb4deb3c9 + md5: a9f577daf3de00bca7c3c76c0ecbd1de + depends: + - __glibc >=2.17,<3.0.a0 + - libgomp >=7.5.0 + constrains: + - openmp_impl <0.0a0 + license: BSD-3-Clause + license_family: BSD + size: 28948 + timestamp: 1770939786096 +- conda: https://conda.anaconda.org/conda-forge/linux-64/alsa-lib-1.2.16.1-hb03c661_0.conda + sha256: cf93ca0f1f107e95a35969a4622684e08fcb8cf37f8cf4a1e9e424828386c921 + md5: 8904e09bda369377b3dd07e2ac828c5d + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + license: LGPL-2.1-or-later + license_family: LGPL + size: 592377 + timestamp: 1781521980743 +- conda: https://conda.anaconda.org/conda-forge/linux-64/aom-3.9.1-hac33072_0.conda + sha256: b08ef033817b5f9f76ce62dfcac7694e7b6b4006420372de22494503decac855 + md5: 346722a0be40f6edc53f12640d301338 + depends: + - libgcc-ng >=12 + - libstdcxx-ng >=12 + license: BSD-2-Clause + license_family: BSD + size: 2706396 + timestamp: 1718551242397 +- conda: https://conda.anaconda.org/conda-forge/linux-64/bzip2-1.0.8-hda65f42_9.conda + sha256: 0b75d45f0bba3e95dc693336fa51f40ea28c980131fec438afb7ce6118ed05f6 + md5: d2ffd7602c02f2b316fd921d39876885 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + license: bzip2-1.0.6 + license_family: BSD + size: 260182 + timestamp: 1771350215188 +- conda: https://conda.anaconda.org/conda-forge/noarch/ca-certificates-2026.6.17-hbd8a1cb_0.conda + sha256: f8e3c730fa14ee3f170493779f06522c4acf89169f43db4f039727709b6419cf + md5: a9965dd99f683c5f444428f896635716 + depends: + - __unix + license: ISC + size: 128866 + timestamp: 1781708962055 +- conda: https://conda.anaconda.org/conda-forge/linux-64/cairo-1.18.4-he90730b_1.conda + sha256: 06525fa0c4e4f56e771a3b986d0fdf0f0fc5a3270830ee47e127a5105bde1b9a + md5: bb6c4808bfa69d6f7f6b07e5846ced37 + depends: + - __glibc >=2.17,<3.0.a0 + - fontconfig >=2.15.0,<3.0a0 + - fonts-conda-ecosystem + - icu >=78.1,<79.0a0 + - libexpat >=2.7.3,<3.0a0 + - libfreetype >=2.14.1 + - libfreetype6 >=2.14.1 + - libgcc >=14 + - libglib >=2.86.3,<3.0a0 + - libpng >=1.6.53,<1.7.0a0 + - libstdcxx >=14 + - libxcb >=1.17.0,<2.0a0 + - libzlib >=1.3.1,<2.0a0 + - pixman >=0.46.4,<1.0a0 + - xorg-libice >=1.1.2,<2.0a0 + - xorg-libsm >=1.2.6,<2.0a0 + - xorg-libx11 >=1.8.12,<2.0a0 + - xorg-libxext >=1.3.6,<2.0a0 + - xorg-libxrender >=0.9.12,<0.10.0a0 + license: LGPL-2.1-only or MPL-1.1 + size: 989514 + timestamp: 1766415934926 +- conda: https://conda.anaconda.org/conda-forge/linux-64/dav1d-1.2.1-hd590300_0.conda + sha256: 22053a5842ca8ee1cf8e1a817138cdb5e647eb2c46979f84153f6ad7bde73020 + md5: 418c6ca5929a611cbd69204907a83995 + depends: + - libgcc-ng >=12 + license: BSD-2-Clause + license_family: BSD + size: 760229 + timestamp: 1685695754230 +- conda: https://conda.anaconda.org/conda-forge/linux-64/dbus-1.16.2-h24cb091_1.conda + sha256: 8bb557af1b2b7983cf56292336a1a1853f26555d9c6cecf1e5b2b96838c9da87 + md5: ce96f2f470d39bd96ce03945af92e280 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libstdcxx >=14 + - libzlib >=1.3.1,<2.0a0 + - libglib >=2.86.2,<3.0a0 + - libexpat >=2.7.3,<3.0a0 + license: AFL-2.1 OR GPL-2.0-or-later + size: 447649 + timestamp: 1764536047944 +- conda: https://conda.anaconda.org/conda-forge/linux-64/ffmpeg-7.1.1-gpl_hbbdf940_911.conda + sha256: fdbec8d65b252c08a73ee418eb5b0a4d05579556b432d715adde7f783562e9b4 + md5: fe3678db2768972f0351eb8604bc3ca8 + depends: + - __glibc >=2.17,<3.0.a0 + - alsa-lib >=1.2.14,<1.3.0a0 + - aom >=3.9.1,<3.10.0a0 + - bzip2 >=1.0.8,<2.0a0 + - dav1d >=1.2.1,<1.2.2.0a0 + - fontconfig >=2.15.0,<3.0a0 + - fonts-conda-ecosystem + - gmp >=6.3.0,<7.0a0 + - harfbuzz >=11.5.1 + - lame >=3.100,<3.101.0a0 + - libass >=0.17.4,<0.17.5.0a0 + - libexpat >=2.7.1,<3.0a0 + - libfreetype >=2.14.1 + - libfreetype6 >=2.14.1 + - libgcc >=14 + - libiconv >=1.18,<2.0a0 + - liblzma >=5.8.1,<6.0a0 + - libopenvino >=2025.2.0,<2025.2.1.0a0 + - libopenvino-auto-batch-plugin >=2025.2.0,<2025.2.1.0a0 + - libopenvino-auto-plugin >=2025.2.0,<2025.2.1.0a0 + - libopenvino-hetero-plugin >=2025.2.0,<2025.2.1.0a0 + - libopenvino-intel-cpu-plugin >=2025.2.0,<2025.2.1.0a0 + - libopenvino-intel-gpu-plugin >=2025.2.0,<2025.2.1.0a0 + - libopenvino-intel-npu-plugin >=2025.2.0,<2025.2.1.0a0 + - libopenvino-ir-frontend >=2025.2.0,<2025.2.1.0a0 + - libopenvino-onnx-frontend >=2025.2.0,<2025.2.1.0a0 + - libopenvino-paddle-frontend >=2025.2.0,<2025.2.1.0a0 + - libopenvino-pytorch-frontend >=2025.2.0,<2025.2.1.0a0 + - libopenvino-tensorflow-frontend >=2025.2.0,<2025.2.1.0a0 + - libopenvino-tensorflow-lite-frontend >=2025.2.0,<2025.2.1.0a0 + - libopus >=1.5.2,<2.0a0 + - librsvg >=2.58.4,<3.0a0 + - libstdcxx >=14 + - libva >=2.22.0,<3.0a0 + - libvorbis >=1.3.7,<1.4.0a0 + - libvpl >=2.15.0,<2.16.0a0 + - libvpx >=1.14.1,<1.15.0a0 + - libxcb >=1.17.0,<2.0a0 + - libxml2 + - libxml2-16 >=2.14.6 + - libzlib >=1.3.1,<2.0a0 + - openh264 >=2.6.0,<2.6.1.0a0 + - openssl >=3.5.3,<4.0a0 + - pulseaudio-client >=17.0,<17.1.0a0 + - sdl2 >=2.32.56,<3.0a0 + - svt-av1 >=3.1.2,<3.1.3.0a0 + - x264 >=1!164.3095,<1!165 + - x265 >=3.5,<3.6.0a0 + - xorg-libx11 >=1.8.12,<2.0a0 + constrains: + - __cuda >=12.8 + license: GPL-2.0-or-later + license_family: GPL + size: 10533973 + timestamp: 1758924873115 +- conda: https://conda.anaconda.org/conda-forge/noarch/font-ttf-dejavu-sans-mono-2.37-hab24e00_0.tar.bz2 + sha256: 58d7f40d2940dd0a8aa28651239adbf5613254df0f75789919c4e6762054403b + md5: 0c96522c6bdaed4b1566d11387caaf45 + license: BSD-3-Clause + license_family: BSD + size: 397370 + timestamp: 1566932522327 +- conda: https://conda.anaconda.org/conda-forge/noarch/font-ttf-inconsolata-3.000-h77eed37_0.tar.bz2 + sha256: c52a29fdac682c20d252facc50f01e7c2e7ceac52aa9817aaf0bb83f7559ec5c + md5: 34893075a5c9e55cdafac56607368fc6 + license: OFL-1.1 + license_family: Other + size: 96530 + timestamp: 1620479909603 +- conda: https://conda.anaconda.org/conda-forge/noarch/font-ttf-source-code-pro-2.038-h77eed37_0.tar.bz2 + sha256: 00925c8c055a2275614b4d983e1df637245e19058d79fc7dd1a93b8d9fb4b139 + md5: 4d59c254e01d9cde7957100457e2d5fb + license: OFL-1.1 + license_family: Other + size: 700814 + timestamp: 1620479612257 +- conda: https://conda.anaconda.org/conda-forge/noarch/font-ttf-ubuntu-0.83-h77eed37_3.conda + sha256: 2821ec1dc454bd8b9a31d0ed22a7ce22422c0aef163c59f49dfdf915d0f0ca14 + md5: 49023d73832ef61042f6a237cb2687e7 + license: LicenseRef-Ubuntu-Font-Licence-Version-1.0 + license_family: Other + size: 1620504 + timestamp: 1727511233259 +- conda: https://conda.anaconda.org/conda-forge/linux-64/fontconfig-2.18.1-h27c8c51_0.conda + sha256: 2e50bdcebdf70a865b81f2456bbc586386451ec601c60f2b6cd22b8c40a2d384 + md5: e0e050cfa9fa85fe39632ab11cb7f3e0 + depends: + - __glibc >=2.17,<3.0.a0 + - libexpat >=2.8.1,<3.0a0 + - libfreetype >=2.14.3 + - libfreetype6 >=2.14.3 + - libgcc >=14 + - libuuid >=2.42.1,<3.0a0 + - libzlib >=1.3.2,<2.0a0 + license: MIT + license_family: MIT + size: 281880 + timestamp: 1780450077431 +- conda: https://conda.anaconda.org/conda-forge/noarch/fonts-conda-ecosystem-1-0.tar.bz2 + sha256: a997f2f1921bb9c9d76e6fa2f6b408b7fa549edd349a77639c9fe7a23ea93e61 + md5: fee5683a3f04bd15cbd8318b096a27ab + depends: + - fonts-conda-forge + license: BSD-3-Clause + license_family: BSD + size: 3667 + timestamp: 1566974674465 +- conda: https://conda.anaconda.org/conda-forge/noarch/fonts-conda-forge-1-hc364b38_1.conda + sha256: 54eea8469786bc2291cc40bca5f46438d3e062a399e8f53f013b6a9f50e98333 + md5: a7970cd949a077b7cb9696379d338681 + depends: + - font-ttf-ubuntu + - font-ttf-inconsolata + - font-ttf-dejavu-sans-mono + - font-ttf-source-code-pro + license: BSD-3-Clause + license_family: BSD + size: 4059 + timestamp: 1762351264405 +- conda: https://conda.anaconda.org/conda-forge/linux-64/fribidi-1.0.16-hb03c661_0.conda + sha256: 858283ff33d4c033f4971bf440cebff217d5552a5222ba994c49be990dacd40d + md5: f9f81ea472684d75b9dd8d0b328cf655 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + license: LGPL-2.1-or-later + size: 61244 + timestamp: 1757438574066 +- conda: https://conda.anaconda.org/conda-forge/linux-64/gdk-pixbuf-2.44.7-h2b0a6b4_0.conda + sha256: 1c22e37f9d7e06e9e0582ee5a55c2ddd19ea75f71f44eb13b56f504ef5c37aa5 + md5: 5d355db3e937086e22cf4cb5fe19787c + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libglib >=2.88.2,<3.0a0 + - libjpeg-turbo >=3.1.4.1,<4.0a0 + - liblzma >=5.8.3,<6.0a0 + - libpng >=1.6.58,<1.7.0a0 + - libtiff >=4.7.1,<4.8.0a0 + license: LGPL-2.1-or-later + license_family: LGPL + size: 581631 + timestamp: 1782591374199 +- conda: https://conda.anaconda.org/conda-forge/linux-64/gmp-6.3.0-hac33072_2.conda + sha256: 309cf4f04fec0c31b6771a5809a1909b4b3154a2208f52351e1ada006f4c750c + md5: c94a5994ef49749880a8139cf9afcbe1 + depends: + - libgcc-ng >=12 + - libstdcxx-ng >=12 + license: GPL-2.0-or-later OR LGPL-3.0-or-later + size: 460055 + timestamp: 1718980856608 +- conda: https://conda.anaconda.org/conda-forge/linux-64/graphite2-1.3.15-hecca717_0.conda + sha256: 885fa7d1d7e2ad9ed0a700ee0d81ceb49de278253082d517959b22d6336eecce + md5: cf09e9fc938518e91d0706572cadf17a + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libstdcxx >=14 + license: LGPL-2.0-or-later + license_family: LGPL + size: 100054 + timestamp: 1780454302233 +- conda: https://conda.anaconda.org/conda-forge/linux-64/harfbuzz-14.2.1-h6083320_0.conda + sha256: da9901aa1e20cbc2369fda212039b294dd02bce95f005539bab840b7310bf7d0 + md5: 21ee4640b7c2d94e584349fa12b29b9a + depends: + - __glibc >=2.17,<3.0.a0 + - cairo >=1.18.4,<2.0a0 + - graphite2 >=1.3.14,<2.0a0 + - icu >=78.3,<79.0a0 + - libexpat >=2.8.1,<3.0a0 + - libfreetype >=2.14.3 + - libfreetype6 >=2.14.3 + - libgcc >=14 + - libglib >=2.88.1,<3.0a0 + - libstdcxx >=14 + - libzlib >=1.3.2,<2.0a0 + license: MIT + license_family: MIT + size: 2362258 + timestamp: 1780450503234 +- conda: https://conda.anaconda.org/conda-forge/linux-64/icu-78.3-h33c6efd_0.conda + sha256: fbf86c4a59c2ed05bbffb2ba25c7ed94f6185ec30ecb691615d42342baa1a16a + md5: c80d8a3b84358cb967fa81e7075fbc8a + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libstdcxx >=14 + license: MIT + license_family: MIT + size: 12723451 + timestamp: 1773822285671 +- conda: https://conda.anaconda.org/conda-forge/linux-64/intel-gmmlib-22.10.0-hb700be7_0.conda + sha256: bc231d69eb6663db0e09738fb916c5e5507147cf1ac60f364f964004e0b29bab + md5: 10909406c1b0e4b57f9f4f0eb0999af8 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libstdcxx >=14 + license: MIT + license_family: MIT + size: 1013714 + timestamp: 1774422680665 +- conda: https://conda.anaconda.org/conda-forge/linux-64/intel-media-driver-25.3.4-hecca717_0.conda + sha256: 286679d4c175e8db2d047be766d1629f1ea5828bff9fe7e6aac2e6f0fad2b427 + md5: 7ae2034a0e2e24eb07468f1a50cdf0bb + depends: + - __glibc >=2.17,<3.0.a0 + - intel-gmmlib >=22.8.1,<23.0a0 + - libgcc >=14 + - libstdcxx >=14 + - libva >=2.22.0,<3.0a0 + license: MIT + license_family: MIT + size: 8424610 + timestamp: 1757591682198 +- conda: https://conda.anaconda.org/conda-forge/linux-64/lame-3.100-h166bdaf_1003.tar.bz2 + sha256: aad2a703b9d7b038c0f745b853c6bb5f122988fe1a7a096e0e606d9cbec4eaab + md5: a8832b479f93521a9e7b5b743803be51 + depends: + - libgcc-ng >=12 + license: LGPL-2.0-only + license_family: LGPL + size: 508258 + timestamp: 1664996250081 +- conda: https://conda.anaconda.org/conda-forge/linux-64/ld_impl_linux-64-2.45.1-default_hbd61a6d_102.conda + sha256: 3d584956604909ff5df353767f3a2a2f60e07d070b328d109f30ac40cd62df6c + md5: 18335a698559cdbcd86150a48bf54ba6 + depends: + - __glibc >=2.17,<3.0.a0 + - zstd >=1.5.7,<1.6.0a0 + constrains: + - binutils_impl_linux-64 2.45.1 + license: GPL-3.0-only + license_family: GPL + size: 728002 + timestamp: 1774197446916 +- conda: https://conda.anaconda.org/conda-forge/linux-64/lerc-4.1.0-hdb68285_0.conda + sha256: f84cb54782f7e9cea95e810ea8fef186e0652d0fa73d3009914fa2c1262594e1 + md5: a752488c68f2e7c456bcbd8f16eec275 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libstdcxx >=14 + license: Apache-2.0 + license_family: Apache + size: 261513 + timestamp: 1773113328888 +- conda: https://conda.anaconda.org/conda-forge/linux-64/level-zero-1.29.0-hb700be7_0.conda + sha256: d87cfc5eaa08eefff97d891ecb49faa958fcfc32a425767796269c4100d4e516 + md5: f3c3bc77c96af553f761af0e78bc8d9d + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libstdcxx >=14 + license: MIT + license_family: MIT + size: 875773 + timestamp: 1780142086148 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libabseil-20250512.1-cxx17_hba17884_0.conda + sha256: dcd1429a1782864c452057a6c5bc1860f2b637dc20a2b7e6eacd57395bbceff8 + md5: 83b160d4da3e1e847bf044997621ed63 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=13 + - libstdcxx >=13 + constrains: + - libabseil-static =20250512.1=cxx17* + - abseil-cpp =20250512.1 + license: Apache-2.0 + license_family: Apache + size: 1310612 + timestamp: 1750194198254 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libass-0.17.4-h96ad9f0_0.conda + sha256: 035eb8b54e03e72e42ef707420f9979c7427776ea99e0f1e3c969f92eb573f19 + md5: d3be7b2870bf7aff45b12ea53165babd + depends: + - libgcc >=13 + - __glibc >=2.17,<3.0.a0 + - libzlib >=1.3.1,<2.0a0 + - libfreetype >=2.13.3 + - libfreetype6 >=2.13.3 + - fribidi >=1.0.10,<2.0a0 + - libiconv >=1.18,<2.0a0 + - fontconfig >=2.15.0,<3.0a0 + - fonts-conda-ecosystem + - harfbuzz >=11.0.1 + license: ISC + size: 152179 + timestamp: 1749328931930 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libcap-2.78-hd0affe5_0.conda + sha256: cc8c9fc6ddf0fbd3d1275b558ae9abad6cda23bced268732e2da21a87bb358cd + md5: f9f17eab7f3df1c6fd4b1a548a2f683a + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + license: BSD-3-Clause + license_family: BSD + size: 124335 + timestamp: 1775488792584 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libdeflate-1.25-h17f619e_0.conda + sha256: aa8e8c4be9a2e81610ddf574e05b64ee131fab5e0e3693210c9d6d2fba32c680 + md5: 6c77a605a7a689d17d4819c0f8ac9a00 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + license: MIT + license_family: MIT + size: 73490 + timestamp: 1761979956660 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libdrm-2.4.127-hb03c661_0.conda + sha256: 7d3187c11b7ae66c5595a8afd5a7ce352a490527fdf6614cab129bc7f2c16ba3 + md5: d8d16b9b32a3c5df7e5b3350e2cbe058 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libpciaccess >=0.19,<0.20.0a0 + license: MIT + license_family: MIT + size: 311505 + timestamp: 1778975798004 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libegl-1.7.0-ha4b6fd6_3.conda + sha256: 9a25ea93e8272785405a21d30f84e620befb1d545f6dfaae18f06103b5df0443 + md5: 75e9f795be506c96dd43cb09c7c8d557 + depends: + - __glibc >=2.17,<3.0.a0 + - libglvnd 1.7.0 ha4b6fd6_3 + license: LicenseRef-libglvnd + size: 46500 + timestamp: 1779728188901 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libexpat-2.8.1-hecca717_1.conda + sha256: 16feffd9ddbbe5b718515d38ee376c685ba95491cd901244e24671d20b952a77 + md5: b24d3c612f71e7aa74158d92106318b2 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + constrains: + - expat 2.8.1.* + license: MIT + license_family: MIT + size: 77856 + timestamp: 1781203599810 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libffi-3.5.2-h3435931_0.conda + sha256: 31f19b6a88ce40ebc0d5a992c131f57d919f73c0b92cd1617a5bec83f6e961e6 + md5: a360c33a5abe61c07959e449fa1453eb + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + license: MIT + license_family: MIT + size: 58592 + timestamp: 1769456073053 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libflac-1.5.0-he200343_1.conda + sha256: e755e234236bdda3d265ae82e5b0581d259a9279e3e5b31d745dc43251ad64fb + md5: 47595b9d53054907a00d95e4d47af1d6 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libiconv >=1.18,<2.0a0 + - libogg >=1.3.5,<1.4.0a0 + - libstdcxx >=14 + license: BSD-3-Clause + license_family: BSD + size: 424563 + timestamp: 1764526740626 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libfreetype-2.14.3-ha770c72_0.conda + sha256: 38f014a7129e644636e46064ecd6b1945e729c2140e21d75bb476af39e692db2 + md5: e289f3d17880e44b633ba911d57a321b + depends: + - libfreetype6 >=2.14.3 + license: GPL-2.0-only OR FTL + size: 8049 + timestamp: 1774298163029 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libfreetype6-2.14.3-h73754d4_0.conda + sha256: 16f020f96da79db1863fcdd8f2b8f4f7d52f177dd4c58601e38e9182e91adf1d + md5: fb16b4b69e3f1dcfe79d80db8fd0c55d + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libpng >=1.6.55,<1.7.0a0 + - libzlib >=1.3.2,<2.0a0 + constrains: + - freetype >=2.14.3 + license: GPL-2.0-only OR FTL + size: 384575 + timestamp: 1774298162622 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libgcc-15.2.0-he0feb66_19.conda + sha256: 8e0a3b5e41272e5678499b5dfc4cddb673f9e935de01eb0767ce857001229f46 + md5: 57736f29cc2b0ec0b6c2952d3f101b6a + depends: + - __glibc >=2.17,<3.0.a0 + - _openmp_mutex >=4.5 + constrains: + - libgcc-ng ==15.2.0=*_19 + - libgomp 15.2.0 he0feb66_19 + license: GPL-3.0-only WITH GCC-exception-3.1 + license_family: GPL + size: 1041084 + timestamp: 1778269013026 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libgcc-ng-15.2.0-h69a702a_19.conda + sha256: 9dcf54adfaa5e861123c2da4f2f0451a685464ea7e5a41ad91cf67b31d658d98 + md5: 331ee9b72b9dff570d56b1302c5ab37d + depends: + - libgcc 15.2.0 he0feb66_19 + license: GPL-3.0-only WITH GCC-exception-3.1 + license_family: GPL + size: 27694 + timestamp: 1778269016987 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libgl-1.7.0-ha4b6fd6_3.conda + sha256: ec353b3076ed8e357ed961d0e9ff6997491cade0e603de5bd18a2e301ac78ebd + md5: f25206d7322c0e9648e8b83694d143ab + depends: + - __glibc >=2.17,<3.0.a0 + - libglvnd 1.7.0 ha4b6fd6_3 + - libglx 1.7.0 ha4b6fd6_3 + license: LicenseRef-libglvnd + size: 133469 + timestamp: 1779728207669 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libglib-2.88.2-h0d30a3d_0.conda + sha256: 4bee10e62796f01e4fa2b5849135b1cc061337fe9cf5eb9bd79e9664922ae0e4 + md5: 889febc66cd9e4190f80ef9718fa239b + depends: + - libgcc >=14 + - __glibc >=2.17,<3.0.a0 + - libiconv >=1.18,<2.0a0 + - libzlib >=1.3.2,<2.0a0 + - libffi >=3.5.2,<3.6.0a0 + - pcre2 >=10.47,<10.48.0a0 + constrains: + - glib >2.66 + license: LGPL-2.1-or-later + size: 4754220 + timestamp: 1782463895250 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libglvnd-1.7.0-ha4b6fd6_3.conda + sha256: e019ebe4e3f5cdf23e2f5e58ddf7ade27988c53820115b17b98f218ebcc87748 + md5: eb83f3f8cecc3e9bff9e250817fc69b6 + depends: + - __glibc >=2.17,<3.0.a0 + license: LicenseRef-libglvnd + size: 133586 + timestamp: 1779728183422 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libglx-1.7.0-ha4b6fd6_3.conda + sha256: 2f74713c9ca408ea84e88a30a9028153e7b553e8bb42e06139eac9a753c27da9 + md5: ec3c4350aa0261bf7f87b8ca15c8e80e + depends: + - __glibc >=2.17,<3.0.a0 + - libglvnd 1.7.0 ha4b6fd6_3 + - xorg-libx11 >=1.8.13,<2.0a0 + license: LicenseRef-libglvnd + size: 76586 + timestamp: 1779728199059 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libgomp-15.2.0-he0feb66_19.conda + sha256: 5abe4ab9d93f6c9757d654f1969ae2267d4505315c1f2f8fe705fd60af084f1b + md5: faac990cb7aedc7f3a2224f2c9b0c26c + depends: + - __glibc >=2.17,<3.0.a0 + license: GPL-3.0-only WITH GCC-exception-3.1 + license_family: GPL + size: 603817 + timestamp: 1778268942614 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libhwloc-2.13.0-default_he001693_1000.conda + sha256: 5041d295813dfb84652557839825880aae296222ab725972285c5abe3b6e4288 + md5: c197985b58bc813d26b42881f0021c82 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libstdcxx >=14 + - libxml2 + - libxml2-16 >=2.14.6 + license: BSD-3-Clause + license_family: BSD + size: 2436378 + timestamp: 1770953868164 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libiconv-1.18-h3b78370_2.conda + sha256: c467851a7312765447155e071752d7bf9bf44d610a5687e32706f480aad2833f + md5: 915f5995e94f60e9a4826e0b0920ee88 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + license: LGPL-2.1-only + size: 790176 + timestamp: 1754908768807 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libjpeg-turbo-3.1.4.1-hb03c661_0.conda + sha256: 10056646c28115b174de81a44e23e3a0a3b95b5347d2e6c45cc6d49d35294256 + md5: 6178c6f2fb254558238ef4e6c56fb782 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + constrains: + - jpeg <0.0.0a + license: IJG AND BSD-3-Clause AND Zlib + size: 633831 + timestamp: 1775962768273 +- conda: https://conda.anaconda.org/conda-forge/linux-64/liblzma-5.8.3-hb03c661_0.conda + sha256: ec30e52a3c1bf7d0425380a189d209a52baa03f22fb66dd3eb587acaa765bd6d + md5: b88d90cad08e6bc8ad540cb310a761fb + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + constrains: + - xz 5.8.3.* + license: 0BSD + size: 113478 + timestamp: 1775825492909 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libnsl-2.0.1-hb9d3cd8_1.conda + sha256: 927fe72b054277cde6cb82597d0fcf6baf127dcbce2e0a9d8925a68f1265eef5 + md5: d864d34357c3b65a4b731f78c0801dc4 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=13 + license: LGPL-2.1-only + license_family: GPL + size: 33731 + timestamp: 1750274110928 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libogg-1.3.5-hd0c01bc_1.conda + sha256: ffb066ddf2e76953f92e06677021c73c85536098f1c21fcd15360dbc859e22e4 + md5: 68e52064ed3897463c0e958ab5c8f91b + depends: + - libgcc >=13 + - __glibc >=2.17,<3.0.a0 + license: BSD-3-Clause + license_family: BSD + size: 218500 + timestamp: 1745825989535 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-2025.2.0-hb617929_1.conda + sha256: 235e7d474c90ad9d8955401b8a91dbe373aa1dc65db3c8232a5e22e4eaf41976 + md5: 1da20cc4ff32dc74424dec68ec087dba + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libstdcxx >=14 + - pugixml >=1.15,<1.16.0a0 + - tbb >=2021.13.0 + size: 6244771 + timestamp: 1753211097492 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-auto-batch-plugin-2025.2.0-hed573e4_1.conda + sha256: 193f760e828b0dd5168dd1d28580d4bf429c5f14a4eee5e0c02ff4c6d4cf8093 + md5: 94f9d17be1d658213b66b22f63cc6578 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libopenvino 2025.2.0 hb617929_1 + - libstdcxx >=14 + - tbb >=2021.13.0 + size: 114760 + timestamp: 1753211116381 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-auto-plugin-2025.2.0-hed573e4_1.conda + sha256: a6f9f996e64e6d2f295f017a833eda7018ff58b6894503272d72f0002dfd6f33 + md5: 071b3a82342715a411f216d379ab6205 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libopenvino 2025.2.0 hb617929_1 + - libstdcxx >=14 + - tbb >=2021.13.0 + size: 250500 + timestamp: 1753211127339 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-hetero-plugin-2025.2.0-hd41364c_1.conda + sha256: f43f9049338ef9735b6815bac3f483d1e3adddecbfdeb13be365bc3f601fe156 + md5: 77c0c7028a8110076d40314dc7b1fa98 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libopenvino 2025.2.0 hb617929_1 + - libstdcxx >=14 + - pugixml >=1.15,<1.16.0a0 + size: 194815 + timestamp: 1753211138624 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-intel-cpu-plugin-2025.2.0-hb617929_1.conda + sha256: a4a1cd320fa010a45d01f438dc3431b7a60271ee19188a901f884399fe744268 + md5: e4cc6db5bdc8b554c06bf569de57f85f + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libopenvino 2025.2.0 hb617929_1 + - libstdcxx >=14 + - pugixml >=1.15,<1.16.0a0 + - tbb >=2021.13.0 + size: 12377488 + timestamp: 1753211149903 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-intel-gpu-plugin-2025.2.0-hb617929_1.conda + sha256: 03ebf700586775144ca5913f401393a386b9a1d7a7cfcba4494830063ca5eb92 + md5: b846fe6c158ca417e246122172d68d3a + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libopenvino 2025.2.0 hb617929_1 + - libstdcxx >=14 + - ocl-icd >=2.3.3,<3.0a0 + - pugixml >=1.15,<1.16.0a0 + - tbb >=2021.13.0 + size: 10815480 + timestamp: 1753211182626 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-intel-npu-plugin-2025.2.0-hb617929_1.conda + sha256: b6dbc342293d6ce0c7b37c9f29f734b3e1856cff9405a02fb33cedd1b36528e6 + md5: 86fd4c25f6accaf646c86adf0f1382d3 + depends: + - __glibc >=2.17,<3.0.a0 + - level-zero >=1.23.1,<2.0a0 + - libgcc >=14 + - libopenvino 2025.2.0 hb617929_1 + - libstdcxx >=14 + - pugixml >=1.15,<1.16.0a0 + - tbb >=2021.13.0 + size: 1261488 + timestamp: 1753211212823 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-ir-frontend-2025.2.0-hd41364c_1.conda + sha256: 334733396d4c9a9b2b2d7d7d850e8ee8deca1f9becd0368d106010076ceb20ca + md5: 75e595d9f2019a60f6dcb500266da615 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libopenvino 2025.2.0 hb617929_1 + - libstdcxx >=14 + - pugixml >=1.15,<1.16.0a0 + size: 204890 + timestamp: 1753211224567 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-onnx-frontend-2025.2.0-h1862bb8_1.conda + sha256: 3937b028e7192ed3805581ac0ea171725843056c8544537754fad45a1791e864 + md5: 68f5ad9d8e3979362bb9dfc9388980aa + depends: + - __glibc >=2.17,<3.0.a0 + - libabseil * cxx17* + - libabseil >=20250512.1,<20250513.0a0 + - libgcc >=14 + - libopenvino 2025.2.0 hb617929_1 + - libprotobuf >=6.31.1,<6.31.2.0a0 + - libstdcxx >=14 + size: 1724503 + timestamp: 1753211235981 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-paddle-frontend-2025.2.0-h1862bb8_1.conda + sha256: c7ac3d4187323ab37ef62ec0896a41c8ca7da426c7f587494c72fe74852269e5 + md5: a032d03468dee9fb5b8eaf635b4571c2 + depends: + - __glibc >=2.17,<3.0.a0 + - libabseil * cxx17* + - libabseil >=20250512.1,<20250513.0a0 + - libgcc >=14 + - libopenvino 2025.2.0 hb617929_1 + - libprotobuf >=6.31.1,<6.31.2.0a0 + - libstdcxx >=14 + size: 744746 + timestamp: 1753211248776 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-pytorch-frontend-2025.2.0-hecca717_1.conda + sha256: 2d4a680a16509b8dd06ccd7a236655e46cc7c242bb5b6e88b83a834b891658db + md5: cd40cf2d10a3279654c9769f3bc8caf5 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libopenvino 2025.2.0 hb617929_1 + - libstdcxx >=14 + size: 1243134 + timestamp: 1753211260154 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-tensorflow-frontend-2025.2.0-h0767aad_1.conda + sha256: 311ec1118448a28e76f0359c4393c7f7f5e64761c48ac7b169bf928a391eae77 + md5: f71c6b4e342b560cc40687063ef62c50 + depends: + - __glibc >=2.17,<3.0.a0 + - libabseil * cxx17* + - libabseil >=20250512.1,<20250513.0a0 + - libgcc >=14 + - libopenvino 2025.2.0 hb617929_1 + - libprotobuf >=6.31.1,<6.31.2.0a0 + - libstdcxx >=14 + - snappy >=1.2.2,<1.3.0a0 + size: 1325059 + timestamp: 1753211272484 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libopenvino-tensorflow-lite-frontend-2025.2.0-hecca717_1.conda + sha256: 581f4951e645e820c4a6ffe40fb0174b56d6e31fb1fefd2d64913fea01f8f69e + md5: fd9dacd7101f80ff1110ea6b76adb95d + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libopenvino 2025.2.0 hb617929_1 + - libstdcxx >=14 + size: 497047 + timestamp: 1753211285617 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libopus-1.6.1-h280c20c_0.conda + sha256: f1061a26213b9653bbb8372bfa3f291787ca091a9a3060a10df4d5297aad74fd + md5: 2446ac1fe030c2aa6141386c1f5a6aed + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + license: BSD-3-Clause + license_family: BSD + size: 324993 + timestamp: 1768497114401 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libpciaccess-0.19-hb03c661_0.conda + sha256: f41721636a7c2e51bc2c642e1127955ab9c81145470714fdaac44d4d09e4af41 + md5: 33082e13b4769b48cfeb648e15bfe3fc + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + license: MIT + license_family: MIT + size: 29147 + timestamp: 1773533027610 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libpng-1.6.58-h421ea60_0.conda + sha256: 377cfe037f3eeb3b1bf3ad333f724a64d32f315ee1958581fc671891d63d3f89 + md5: eba48a68a1a2b9d3c0d9511548db85db + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libzlib >=1.3.2,<2.0a0 + license: zlib-acknowledgement + size: 317729 + timestamp: 1776315175087 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libprotobuf-6.31.1-hfb7daa7_5.conda + sha256: b04322e2128684d4043e256f56b74528b0a0a296ba4a81299056ec04655a0580 + md5: da31d891434e50d7e7be8adc5832269b + depends: + - __glibc >=2.17,<3.0.a0 + - libabseil * cxx17* + - libabseil >=20250512.1,<20250513.0a0 + - libgcc >=14 + - libstdcxx >=14 + - libzlib >=1.3.2,<2.0a0 + license: BSD-3-Clause + license_family: BSD + size: 4204474 + timestamp: 1780003940664 +- conda: https://conda.anaconda.org/conda-forge/linux-64/librsvg-2.62.3-h4c96295_0.conda + sha256: 5571bd8239d71961d4e3ce972f865b3ea95a91ce0b53d5749fe2dd24254ddbda + md5: 492c8d9b1c564c2e948b6cb4ba0f8261 + depends: + - __glibc >=2.17,<3.0.a0 + - cairo >=1.18.4,<2.0a0 + - fontconfig >=2.18.0,<3.0a0 + - fonts-conda-ecosystem + - gdk-pixbuf >=2.44.6,<3.0a0 + - harfbuzz >=14.2.0 + - libgcc >=14 + - libglib >=2.88.1,<3.0a0 + - libxml2-16 >=2.14.6 + - pango >=1.56.4,<2.0a0 + constrains: + - __glibc >=2.17 + license: LGPL-2.1-or-later + size: 3476570 + timestamp: 1780450632624 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libsndfile-1.2.2-hc7d488a_2.conda + sha256: 57cb5f92110324c04498b96563211a1bca6a74b2918b1e8df578bfed03cc32e4 + md5: 067590f061c9f6ea7e61e3b2112ed6b3 + depends: + - __glibc >=2.17,<3.0.a0 + - lame >=3.100,<3.101.0a0 + - libflac >=1.5.0,<1.6.0a0 + - libgcc >=14 + - libogg >=1.3.5,<1.4.0a0 + - libopus >=1.5.2,<2.0a0 + - libstdcxx >=14 + - libvorbis >=1.3.7,<1.4.0a0 + - mpg123 >=1.32.9,<1.33.0a0 + license: LGPL-2.1-or-later + license_family: LGPL + size: 355619 + timestamp: 1765181778282 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libsqlite-3.53.3-h0c1763c_0.conda + sha256: 365376f4815e5e80def2b3462a2419708b7c292da0da85278386c2618621fff4 + md5: 4aed8e657e9ff156bdbe849b4df44389 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libzlib >=1.3.2,<2.0a0 + license: blessing + size: 962119 + timestamp: 1782519076616 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libstdcxx-15.2.0-h934c35e_19.conda + sha256: dff1058c76ec6b8759e41cefa2508162d00e4a5e6721aa68ec3fd10094e702dc + md5: 5794b3bdc38177caf969dabd3af08549 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc 15.2.0 he0feb66_19 + constrains: + - libstdcxx-ng ==15.2.0=*_19 + license: GPL-3.0-only WITH GCC-exception-3.1 + license_family: GPL + size: 5852044 + timestamp: 1778269036376 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libstdcxx-ng-15.2.0-hdf11a46_19.conda + sha256: 0672b6b6e1791c92e8eccad58081a99d614fcf82bca5841f9dfa3c3e658f83b9 + md5: e5ce228e579726c07255dbf90dc62101 + depends: + - libstdcxx 15.2.0 h934c35e_19 + license: GPL-3.0-only WITH GCC-exception-3.1 + license_family: GPL + size: 27776 + timestamp: 1778269074600 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libsystemd0-257.13-h084b8d7_1.conda + sha256: 2293884d59cf0436c37fc0a4bad71011a8de2a6913610d1c701a7703377c1f75 + md5: ea0da9c20bbb221b530810c3c68bbe62 + depends: + - __glibc >=2.17,<3.0.a0 + - libcap >=2.78,<2.79.0a0 + - libgcc >=14 + license: LGPL-2.1-or-later + size: 493022 + timestamp: 1780084748140 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libtiff-4.7.1-h9d88235_1.conda + sha256: e5f8c38625aa6d567809733ae04bb71c161a42e44a9fa8227abe61fa5c60ebe0 + md5: cd5a90476766d53e901500df9215e927 + depends: + - __glibc >=2.17,<3.0.a0 + - lerc >=4.0.0,<5.0a0 + - libdeflate >=1.25,<1.26.0a0 + - libgcc >=14 + - libjpeg-turbo >=3.1.0,<4.0a0 + - liblzma >=5.8.1,<6.0a0 + - libstdcxx >=14 + - libwebp-base >=1.6.0,<2.0a0 + - libzlib >=1.3.1,<2.0a0 + - zstd >=1.5.7,<1.6.0a0 + license: HPND + size: 435273 + timestamp: 1762022005702 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libudev1-257.13-h084b8d7_1.conda + sha256: 287d05680e49eea51b8145fbf34bc213c0618b04f32e450e9da5d715e5134e38 + md5: 89e5671a076d99516a6acd72a35b1640 + depends: + - __glibc >=2.17,<3.0.a0 + - libcap >=2.78,<2.79.0a0 + - libgcc >=14 + license: LGPL-2.1-or-later + size: 145969 + timestamp: 1780084753104 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libunwind-1.8.3-h65a8314_0.conda + sha256: 71c8b9d5c72473752a0bb6e91b01dd209a03916cb71f36cc6a564e3a2a132d7a + md5: e179a69edd30d75c0144d7a380b88f28 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libstdcxx >=14 + license: MIT + license_family: MIT + size: 75995 + timestamp: 1757032240102 +- conda: https://conda.anaconda.org/conda-forge/linux-64/liburing-2.14-hb700be7_0.conda + sha256: 3d17b7aa90610afc65356e9e6149aeac0b2df19deda73a51f0a09cf04fd89286 + md5: 56f65185b520e016d29d01657ac02c0d + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libstdcxx >=14 + license: MIT + license_family: MIT + size: 154203 + timestamp: 1770566529700 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libusb-1.0.29-h73b1eb8_0.conda + sha256: 89c84f5b26028a9d0f5c4014330703e7dff73ba0c98f90103e9cef6b43a5323c + md5: d17e3fb595a9f24fa9e149239a33475d + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=13 + - libudev1 >=257.4 + license: LGPL-2.1-or-later + size: 89551 + timestamp: 1748856210075 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libuuid-2.42.2-h5347b49_0.conda + sha256: 9b1bdce27a7e31f7d241aeecff67a1f3101d52a2b1e33ccc2cdf2613072bf81f + md5: 01bb81d12c957de066ea7362007df642 + depends: + - libgcc >=14 + - __glibc >=2.17,<3.0.a0 + license: BSD-3-Clause + license_family: BSD + size: 40017 + timestamp: 1781625522462 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libva-2.23.0-he1eb515_0.conda + sha256: 255c7d00b54e26f19fad9340db080716bced1d8539606e2b8396c57abd40007c + md5: 25813fe38b3e541fc40007592f12bae5 + depends: + - __glibc >=2.17,<3.0.a0 + - libdrm >=2.4.125,<2.5.0a0 + - libegl >=1.7.0,<2.0a0 + - libgcc >=14 + - libgl >=1.7.0,<2.0a0 + - libglx >=1.7.0,<2.0a0 + - libxcb >=1.17.0,<2.0a0 + - wayland >=1.24.0,<2.0a0 + - wayland-protocols + - xorg-libx11 >=1.8.12,<2.0a0 + - xorg-libxext >=1.3.6,<2.0a0 + - xorg-libxfixes >=6.0.2,<7.0a0 + license: MIT + license_family: MIT + size: 221308 + timestamp: 1765652453244 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libvorbis-1.3.7-h54a6638_2.conda + sha256: ca494c99c7e5ecc1b4cd2f72b5584cef3d4ce631d23511184411abcbb90a21a5 + md5: b4ecbefe517ed0157c37f8182768271c + depends: + - libogg + - libgcc >=14 + - __glibc >=2.17,<3.0.a0 + - libstdcxx >=14 + - libgcc >=14 + - libogg >=1.3.5,<1.4.0a0 + license: BSD-3-Clause + license_family: BSD + size: 285894 + timestamp: 1753879378005 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libvpl-2.15.0-h54a6638_1.conda + sha256: bf0010d93f5b154c59bd9d3cc32168698c1d24f2904729f4693917cce5b27a9f + md5: a41a299c157cc6d0eff05e5fc298cc45 + depends: + - libstdcxx >=14 + - libgcc >=14 + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - intel-media-driver >=25.3.3,<25.4.0a0 + - libva >=2.22.0,<3.0a0 + license: MIT + license_family: MIT + size: 287944 + timestamp: 1757278954789 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libvpx-1.14.1-hac33072_0.conda + sha256: e7d2daf409c807be48310fcc8924e481b62988143f582eb3a58c5523a6763b13 + md5: cde393f461e0c169d9ffb2fc70f81c33 + depends: + - libgcc-ng >=12 + - libstdcxx-ng >=12 + license: BSD-3-Clause + license_family: BSD + size: 1022466 + timestamp: 1717859935011 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libvulkan-loader-1.4.341.0-h5279c79_0.conda + sha256: a68280d57dfd29e3d53400409a39d67c4b9515097eba733aa6fe00c880620e2b + md5: 31ad065eda3c2d88f8215b1289df9c89 + depends: + - __glibc >=2.17,<3.0.a0 + - libstdcxx >=14 + - libgcc >=14 + - xorg-libx11 >=1.8.12,<2.0a0 + - xorg-libxrandr >=1.5.5,<2.0a0 + constrains: + - libvulkan-headers 1.4.341.0.* + license: Apache-2.0 + license_family: APACHE + size: 199795 + timestamp: 1770077125520 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libwebp-base-1.6.0-hd42ef1d_0.conda + sha256: 3aed21ab28eddffdaf7f804f49be7a7d701e8f0e46c856d801270b470820a37b + md5: aea31d2e5b1091feca96fcfe945c3cf9 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + constrains: + - libwebp 1.6.0 + license: BSD-3-Clause + license_family: BSD + size: 429011 + timestamp: 1752159441324 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libxcb-1.17.0-h8a09558_0.conda + sha256: 666c0c431b23c6cec6e492840b176dde533d48b7e6fb8883f5071223433776aa + md5: 92ed62436b625154323d40d5f2f11dd7 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=13 + - pthread-stubs + - xorg-libxau >=1.0.11,<2.0a0 + - xorg-libxdmcp + license: MIT + license_family: MIT + size: 395888 + timestamp: 1727278577118 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libxcrypt-4.4.36-hd590300_1.conda + sha256: 6ae68e0b86423ef188196fff6207ed0c8195dd84273cb5623b85aa08033a410c + md5: 5aa797f8787fe7a17d1b0821485b5adc + depends: + - libgcc-ng >=12 + license: LGPL-2.1-or-later + size: 100393 + timestamp: 1702724383534 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libxkbcommon-1.13.2-hca5e8e5_0.conda + sha256: 046f2ff4acebd8729fac03e99c8c307dfb48b6a32894ba8c11576e78f6e76e43 + md5: dc8b067e22b414172bedd8e3f03f3c95 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libstdcxx >=14 + - libxcb >=1.17.0,<2.0a0 + - libxml2 + - libxml2-16 >=2.14.6 + - xkeyboard-config + - xorg-libxau >=1.0.12,<2.0a0 + license: MIT/X11 Derivative + license_family: MIT + size: 851166 + timestamp: 1780213397575 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libxml2-2.15.3-h49c6c72_0.conda + sha256: 3bc5551720c58591f6ea1146f7d1539c734ed1c40e7b9f5cb8cb7e900c509aba + md5: 995d8c8bad2a3cc8db14675a153dec2b + depends: + - __glibc >=2.17,<3.0.a0 + - icu >=78.3,<79.0a0 + - libgcc >=14 + - libiconv >=1.18,<2.0a0 + - liblzma >=5.8.3,<6.0a0 + - libxml2-16 2.15.3 hca6bf5a_0 + - libzlib >=1.3.2,<2.0a0 + license: MIT + license_family: MIT + size: 46810 + timestamp: 1776376751152 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libxml2-16-2.15.3-hca6bf5a_0.conda + sha256: 3d44f737c5ae52d5af32682cc1530df433f401f8e58a7533926536244127572a + md5: e79d2c2f24b027aa8d5ab1b1ba3061e7 + depends: + - __glibc >=2.17,<3.0.a0 + - icu >=78.3,<79.0a0 + - libgcc >=14 + - libiconv >=1.18,<2.0a0 + - liblzma >=5.8.3,<6.0a0 + - libzlib >=1.3.2,<2.0a0 + constrains: + - libxml2 2.15.3 + license: MIT + license_family: MIT + size: 559775 + timestamp: 1776376739004 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libzlib-1.3.2-h25fd6f3_2.conda + sha256: 55044c403570f0dc26e6364de4dc5368e5f3fc7ff103e867c487e2b5ab2bcda9 + md5: d87ff7921124eccd67248aa483c23fec + depends: + - __glibc >=2.17,<3.0.a0 + constrains: + - zlib 1.3.2 *_2 + license: Zlib + license_family: Other + size: 63629 + timestamp: 1774072609062 +- conda: https://conda.anaconda.org/conda-forge/linux-64/mpg123-1.32.9-hc50e24c_0.conda + sha256: 39c4700fb3fbe403a77d8cc27352fa72ba744db487559d5d44bf8411bb4ea200 + md5: c7f302fd11eeb0987a6a5e1f3aed6a21 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=13 + - libstdcxx >=13 + license: LGPL-2.1-only + license_family: LGPL + size: 491140 + timestamp: 1730581373280 +- conda: https://conda.anaconda.org/conda-forge/linux-64/ncurses-6.6-hdb14827_0.conda + sha256: fc89f74bbe362fb29fa3c037697a89bec140b346a2469a90f7936d1d7ea4d8a3 + md5: fc21868a1a5aacc937e7a18747acb8a5 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + license: X11 AND BSD-3-Clause + size: 918956 + timestamp: 1777422145199 +- conda: https://conda.anaconda.org/conda-forge/linux-64/ocl-icd-2.3.4-hb03c661_1.conda + sha256: 75f3bf733523a338f73d6c276c4a26634877cd970edb558f2769d9fa52b100a9 + md5: c2871ba95727fd1382c05db66048b64c + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - opencl-headers >=2025.6.13 + license: BSD-2-Clause + license_family: BSD + size: 109598 + timestamp: 1780362789611 +- conda: https://conda.anaconda.org/conda-forge/linux-64/opencl-headers-2025.06.13-hecca717_0.conda + sha256: 8de2f0cd8a659b01abf86e7fbb8cea4f28ada62fd288429a2bbc040db1b98dd0 + md5: c930c8052d780caa41216af7de472226 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libstdcxx >=14 + license: Apache-2.0 + license_family: APACHE + size: 55754 + timestamp: 1773844383536 +- conda: https://conda.anaconda.org/conda-forge/linux-64/openh264-2.6.0-h65dd3cf_1.conda + sha256: 5317c5c23762f3fe1c8510565a2bb94c645e1470ff73b386315656404f7eb58a + md5: 69894a95220a17a66272daa701c387bc + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libstdcxx >=14 + license: BSD-2-Clause + license_family: BSD + size: 726478 + timestamp: 1782685945856 +- conda: https://conda.anaconda.org/conda-forge/linux-64/openssl-3.6.3-h35e630c_0.conda + sha256: d48f5c22b9897c01e4dff3680f1f57ceb02711ab9c62f74339b080419dfad34b + md5: 79dd2074b5cd5c5c6b2930514a11e22d + depends: + - __glibc >=2.17,<3.0.a0 + - ca-certificates + - libgcc >=14 + license: Apache-2.0 + license_family: Apache + size: 3159683 + timestamp: 1781069855778 +- conda: https://conda.anaconda.org/conda-forge/linux-64/pango-1.56.4-hda50119_1.conda + sha256: 315b52bfa6d1a820f4806f6490d472581438a28e21df175290477caec18972b0 + md5: d53ffc0edc8eabf4253508008493c5bc + depends: + - __glibc >=2.17,<3.0.a0 + - cairo >=1.18.4,<2.0a0 + - fontconfig >=2.17.1,<3.0a0 + - fonts-conda-ecosystem + - fribidi >=1.0.16,<2.0a0 + - harfbuzz >=13.2.1 + - libexpat >=2.7.4,<3.0a0 + - libfreetype >=2.14.2 + - libfreetype6 >=2.14.2 + - libgcc >=14 + - libglib >=2.86.4,<3.0a0 + - libpng >=1.6.55,<1.7.0a0 + - libzlib >=1.3.2,<2.0a0 + license: LGPL-2.1-or-later + size: 458036 + timestamp: 1774281947855 +- conda: https://conda.anaconda.org/conda-forge/linux-64/pcre2-10.47-haa7fec5_0.conda + sha256: 5e6f7d161356fefd981948bea5139c5aa0436767751a6930cb1ca801ebb113ff + md5: 7a3bff861a6583f1889021facefc08b1 + depends: + - __glibc >=2.17,<3.0.a0 + - bzip2 >=1.0.8,<2.0a0 + - libgcc >=14 + - libzlib >=1.3.1,<2.0a0 + license: BSD-3-Clause + license_family: BSD + size: 1222481 + timestamp: 1763655398280 +- conda: https://conda.anaconda.org/conda-forge/linux-64/pixman-0.46.4-h54a6638_1.conda + sha256: 43d37bc9ca3b257c5dd7bf76a8426addbdec381f6786ff441dc90b1a49143b6a + md5: c01af13bdc553d1a8fbfff6e8db075f0 + depends: + - libgcc >=14 + - libstdcxx >=14 + - libgcc >=14 + - __glibc >=2.17,<3.0.a0 + license: MIT + license_family: MIT + size: 450960 + timestamp: 1754665235234 +- conda: https://conda.anaconda.org/conda-forge/linux-64/pthread-stubs-0.4-hb9d3cd8_1002.conda + sha256: 9c88f8c64590e9567c6c80823f0328e58d3b1efb0e1c539c0315ceca764e0973 + md5: b3c17d95b5a10c6e64a21fa17573e70e + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=13 + license: MIT + license_family: MIT + size: 8252 + timestamp: 1726802366959 +- conda: https://conda.anaconda.org/conda-forge/linux-64/pugixml-1.15-h3f63f65_0.conda + sha256: 23c98a5000356e173568dc5c5770b53393879f946f3ace716bbdefac2a8b23d2 + md5: b11a4c6bf6f6f44e5e143f759ffa2087 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=13 + - libstdcxx >=13 + license: MIT + license_family: MIT + size: 118488 + timestamp: 1736601364156 +- conda: https://conda.anaconda.org/conda-forge/linux-64/pulseaudio-client-17.0-h9a6aba3_3.conda + sha256: 0a0858c59805d627d02bdceee965dd84fde0aceab03a2f984325eec08d822096 + md5: b8ea447fdf62e3597cb8d2fae4eb1a90 + depends: + - __glibc >=2.17,<3.0.a0 + - dbus >=1.16.2,<2.0a0 + - libgcc >=14 + - libglib >=2.86.1,<3.0a0 + - libiconv >=1.18,<2.0a0 + - libsndfile >=1.2.2,<1.3.0a0 + - libsystemd0 >=257.10 + - libxcb >=1.17.0,<2.0a0 + constrains: + - pulseaudio 17.0 *_3 + license: LGPL-2.1-or-later + license_family: LGPL + size: 750785 + timestamp: 1763148198088 +- conda: https://conda.anaconda.org/conda-forge/linux-64/python-3.12.13-hd63d673_0_cpython.conda + sha256: a44655c1c3e1d43ed8704890a91e12afd68130414ea2c0872e154e5633a13d7e + md5: 7eccb41177e15cc672e1babe9056018e + depends: + - __glibc >=2.17,<3.0.a0 + - bzip2 >=1.0.8,<2.0a0 + - ld_impl_linux-64 >=2.36.1 + - libexpat >=2.7.4,<3.0a0 + - libffi >=3.5.2,<3.6.0a0 + - libgcc >=14 + - liblzma >=5.8.2,<6.0a0 + - libnsl >=2.0.1,<2.1.0a0 + - libsqlite >=3.51.2,<4.0a0 + - libuuid >=2.41.3,<3.0a0 + - libxcrypt >=4.4.36 + - libzlib >=1.3.1,<2.0a0 + - ncurses >=6.5,<7.0a0 + - openssl >=3.5.5,<4.0a0 + - readline >=8.3,<9.0a0 + - tk >=8.6.13,<8.7.0a0 + - tzdata + constrains: + - python_abi 3.12.* *_cp312 + license: Python-2.0 + size: 31608571 + timestamp: 1772730708989 +- conda: https://conda.anaconda.org/conda-forge/linux-64/readline-8.3-h853b02a_0.conda + sha256: 12ffde5a6f958e285aa22c191ca01bbd3d6e710aa852e00618fa6ddc59149002 + md5: d7d95fc8287ea7bf33e0e7116d2b95ec + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - ncurses >=6.5,<7.0a0 + license: GPL-3.0-only + license_family: GPL + size: 345073 + timestamp: 1765813471974 +- conda: https://conda.anaconda.org/conda-forge/linux-64/sdl2-2.32.56-h54a6638_0.conda + sha256: 987ad072939fdd51c92ea8d3544b286bb240aefda329f9b03a51d9b7e777f9de + md5: cdd138897d94dc07d99afe7113a07bec + depends: + - libstdcxx >=14 + - libgcc >=14 + - __glibc >=2.17,<3.0.a0 + - libgl >=1.7.0,<2.0a0 + - sdl3 >=3.2.22,<4.0a0 + - libegl >=1.7.0,<2.0a0 + license: Zlib + size: 589145 + timestamp: 1757842881 +- conda: https://conda.anaconda.org/conda-forge/linux-64/sdl3-3.4.10-hdeec2a5_0.conda + sha256: 04fa7dab2b8f688e3fc4b7ae4522fd3935fb0601e3329cda8b40d63c60d6cc05 + md5: 845c0b154836c034f361668bec2a4f20 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libstdcxx >=14 + - xorg-libxcursor >=1.2.3,<2.0a0 + - libusb >=1.0.29,<2.0a0 + - libxkbcommon >=1.13.2,<2.0a0 + - xorg-libx11 >=1.8.13,<2.0a0 + - xorg-libxi >=1.8.3,<2.0a0 + - liburing >=2.14,<2.15.0a0 + - libunwind >=1.8.3,<1.9.0a0 + - xorg-libxtst >=1.2.5,<2.0a0 + - wayland >=1.25.0,<2.0a0 + - dbus >=1.16.2,<2.0a0 + - libgl >=1.7.0,<2.0a0 + - xorg-libxscrnsaver >=1.2.4,<2.0a0 + - xorg-libxext >=1.3.7,<2.0a0 + - libdrm >=2.4.127,<2.5.0a0 + - pulseaudio-client >=17.0,<17.1.0a0 + - libvulkan-loader >=1.4.341.0,<2.0a0 + - libegl >=1.7.0,<2.0a0 + - xorg-libxfixes >=6.0.2,<7.0a0 + - libudev1 >=257.13 + license: Zlib + size: 2148830 + timestamp: 1780262823658 +- conda: https://conda.anaconda.org/conda-forge/linux-64/snappy-1.2.2-h03e3b7b_1.conda + sha256: 48f3f6a76c34b2cfe80de9ce7f2283ecb55d5ed47367ba91e8bb8104e12b8f11 + md5: 98b6c9dc80eb87b2519b97bcf7e578dd + depends: + - libgcc >=14 + - __glibc >=2.17,<3.0.a0 + - libstdcxx >=14 + - libgcc >=14 + license: BSD-3-Clause + license_family: BSD + size: 45829 + timestamp: 1762948049098 +- conda: https://conda.anaconda.org/conda-forge/linux-64/svt-av1-3.1.2-hecca717_0.conda + sha256: 34e2e9c505cd25dba0a9311eb332381b15147cf599d972322a7c197aedfc8ce2 + md5: 9859766c658e78fec9afa4a54891d920 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libstdcxx >=14 + license: BSD-2-Clause + license_family: BSD + size: 2741200 + timestamp: 1756086702093 +- conda: https://conda.anaconda.org/conda-forge/linux-64/tbb-2023.0.0-hab88423_2.conda + sha256: 30cb9355c2fefc20ff1a3d6566b9714d5614086a2524c07721fc344eb20515ae + md5: 7073b15f9364ebc118998601ac6ca6a6 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libhwloc >=2.13.0,<2.13.1.0a0 + - libstdcxx >=14 + license: Apache-2.0 + license_family: APACHE + size: 182331 + timestamp: 1778673758649 +- conda: https://conda.anaconda.org/conda-forge/linux-64/tk-8.6.13-noxft_h366c992_103.conda + sha256: cafeec44494f842ffeca27e9c8b0c27ed714f93ac77ddadc6aaf726b5554ebac + md5: cffd3bdd58090148f4cfcd831f4b26ab + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libzlib >=1.3.1,<2.0a0 + constrains: + - xorg-libx11 >=1.8.12,<2.0a0 + license: TCL + license_family: BSD + size: 3301196 + timestamp: 1769460227866 +- conda: https://conda.anaconda.org/conda-forge/noarch/tzdata-2025c-hc9c84f9_1.conda + sha256: 1d30098909076af33a35017eed6f2953af1c769e273a0626a04722ac4acaba3c + md5: ad659d0a2b3e47e38d829aa8cad2d610 + license: LicenseRef-Public-Domain + size: 119135 + timestamp: 1767016325805 +- conda: https://conda.anaconda.org/conda-forge/linux-64/uv-0.11.25-h26efc2c_0.conda + sha256: 64d5c1592d62e77191e7f61aae811db68d040c5507c5b1cb33010530148177dc + md5: fed7cb43d942f65256b6187fe30484b1 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libstdcxx >=14 + constrains: + - __glibc >=2.17 + license: Apache-2.0 OR MIT + size: 20451374 + timestamp: 1782538835059 +- conda: https://conda.anaconda.org/conda-forge/linux-64/wayland-1.25.0-hd6090a7_0.conda + sha256: ea374d57a8fcda281a0a89af0ee49a2c2e99cc4ac97cf2e2db7064e74e764bdb + md5: 996583ea9c796e5b915f7d7580b51ea6 + depends: + - __glibc >=2.17,<3.0.a0 + - libexpat >=2.7.4,<3.0a0 + - libffi >=3.5.2,<3.6.0a0 + - libgcc >=14 + - libstdcxx >=14 + license: MIT + license_family: MIT + size: 334139 + timestamp: 1773959575393 +- conda: https://conda.anaconda.org/conda-forge/noarch/wayland-protocols-1.49-hd8ed1ab_0.conda + sha256: 04ce686cd187d379344f9b2be7b4da5f431b265dc0944a6b764fab9da9171948 + md5: 0839a3421140d4a9ba93fb988698fc00 + license: MIT + license_family: MIT + size: 147954 + timestamp: 1780946721169 +- conda: https://conda.anaconda.org/conda-forge/linux-64/x264-1!164.3095-h166bdaf_2.tar.bz2 + sha256: 175315eb3d6ea1f64a6ce470be00fa2ee59980108f246d3072ab8b977cb048a5 + md5: 6c99772d483f566d59e25037fea2c4b1 + depends: + - libgcc-ng >=12 + license: GPL-2.0-or-later + license_family: GPL + size: 897548 + timestamp: 1660323080555 +- conda: https://conda.anaconda.org/conda-forge/linux-64/x265-3.5-h924138e_3.tar.bz2 + sha256: 76c7405bcf2af639971150f342550484efac18219c0203c5ee2e38b8956fe2a0 + md5: e7f6ed84d4623d52ee581325c1587a6b + depends: + - libgcc-ng >=10.3.0 + - libstdcxx-ng >=10.3.0 + license: GPL-2.0-or-later + license_family: GPL + size: 3357188 + timestamp: 1646609687141 +- conda: https://conda.anaconda.org/conda-forge/linux-64/xkeyboard-config-2.48-h280c20c_0.conda + sha256: 3b04afd5d1a65d2d27ac2d49a63b01ab8bcd875776779ec63e337370ed38afdc + md5: b233b41be0bf210989d57160ed39b394 + depends: + - libgcc >=14 + - __glibc >=2.17,<3.0.a0 + - xorg-libx11 >=1.8.13,<2.0a0 + license: MIT + license_family: MIT + size: 441670 + timestamp: 1782027360439 +- conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libice-1.1.2-hb9d3cd8_0.conda + sha256: c12396aabb21244c212e488bbdc4abcdef0b7404b15761d9329f5a4a39113c4b + md5: fb901ff28063514abb6046c9ec2c4a45 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=13 + license: MIT + license_family: MIT + size: 58628 + timestamp: 1734227592886 +- conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libsm-1.2.6-he73a12e_0.conda + sha256: 277841c43a39f738927145930ff963c5ce4c4dacf66637a3d95d802a64173250 + md5: 1c74ff8c35dcadf952a16f752ca5aa49 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=13 + - libuuid >=2.38.1,<3.0a0 + - xorg-libice >=1.1.2,<2.0a0 + license: MIT + license_family: MIT + size: 27590 + timestamp: 1741896361728 +- conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libx11-1.8.13-he1eb515_0.conda + sha256: 516d4060139dbb4de49a4dcdc6317a9353fb39ebd47789c14e6fe52de0deee42 + md5: 861fb6ccbc677bb9a9fb2468430b9c6a + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libxcb >=1.17.0,<2.0a0 + license: MIT + license_family: MIT + size: 839652 + timestamp: 1770819209719 +- conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxau-1.0.12-hb03c661_1.conda + sha256: 6bc6ab7a90a5d8ac94c7e300cc10beb0500eeba4b99822768ca2f2ef356f731b + md5: b2895afaf55bf96a8c8282a2e47a5de0 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + license: MIT + license_family: MIT + size: 15321 + timestamp: 1762976464266 +- conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxcursor-1.2.3-hb9d3cd8_0.conda + sha256: 832f538ade441b1eee863c8c91af9e69b356cd3e9e1350fff4fe36cc573fc91a + md5: 2ccd714aa2242315acaf0a67faea780b + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=13 + - xorg-libx11 >=1.8.10,<2.0a0 + - xorg-libxfixes >=6.0.1,<7.0a0 + - xorg-libxrender >=0.9.11,<0.10.0a0 + license: MIT + license_family: MIT + size: 32533 + timestamp: 1730908305254 +- conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxdmcp-1.1.5-hb03c661_1.conda + sha256: 25d255fb2eef929d21ff660a0c687d38a6d2ccfbcbf0cc6aa738b12af6e9d142 + md5: 1dafce8548e38671bea82e3f5c6ce22f + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + license: MIT + license_family: MIT + size: 20591 + timestamp: 1762976546182 +- conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxext-1.3.7-hb03c661_0.conda + sha256: 79c60fc6acfd3d713d6340d3b4e296836a0f8c51602327b32794625826bd052f + md5: 34e54f03dfea3e7a2dcf1453a85f1085 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - xorg-libx11 >=1.8.12,<2.0a0 + license: MIT + license_family: MIT + size: 50326 + timestamp: 1769445253162 +- conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxfixes-6.0.2-hb03c661_0.conda + sha256: 83c4c99d60b8784a611351220452a0a85b080668188dce5dfa394b723d7b64f4 + md5: ba231da7fccf9ea1e768caf5c7099b84 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - xorg-libx11 >=1.8.12,<2.0a0 + license: MIT + license_family: MIT + size: 20071 + timestamp: 1759282564045 +- conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxi-1.8.3-hb03c661_0.conda + sha256: 495f99c8eacfa4ae2d8fed2a7f2105777af89acdc204df145d2bbbc380ac631b + md5: adba2e334082bb218db806d4c12277c9 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - xorg-libx11 >=1.8.13,<2.0a0 + - xorg-libxext >=1.3.7,<2.0a0 + - xorg-libxfixes >=6.0.2,<7.0a0 + license: MIT + license_family: MIT + size: 47717 + timestamp: 1779111857071 +- conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxrandr-1.5.5-hb03c661_0.conda + sha256: 80ed047a5cb30632c3dc5804c7716131d767089f65877813d4ae855ee5c9d343 + md5: e192019153591938acf7322b6459d36e + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - xorg-libx11 >=1.8.12,<2.0a0 + - xorg-libxext >=1.3.6,<2.0a0 + - xorg-libxrender >=0.9.12,<0.10.0a0 + license: MIT + license_family: MIT + size: 30456 + timestamp: 1769445263457 +- conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxrender-0.9.12-hb9d3cd8_0.conda + sha256: 044c7b3153c224c6cedd4484dd91b389d2d7fd9c776ad0f4a34f099b3389f4a1 + md5: 96d57aba173e878a2089d5638016dc5e + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=13 + - xorg-libx11 >=1.8.10,<2.0a0 + license: MIT + license_family: MIT + size: 33005 + timestamp: 1734229037766 +- conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxscrnsaver-1.2.4-hb9d3cd8_0.conda + sha256: 58e8fc1687534124832d22e102f098b5401173212ac69eb9fd96b16a3e2c8cb2 + md5: 303f7a0e9e0cd7d250bb6b952cecda90 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=13 + - xorg-libx11 >=1.8.10,<2.0a0 + - xorg-libxext >=1.3.6,<2.0a0 + license: MIT + license_family: MIT + size: 14412 + timestamp: 1727899730073 +- conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxtst-1.2.5-hb9d3cd8_3.conda + sha256: 752fdaac5d58ed863bbf685bb6f98092fe1a488ea8ebb7ed7b606ccfce08637a + md5: 7bbe9a0cc0df0ac5f5a8ad6d6a11af2f + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=13 + - xorg-libx11 >=1.8.10,<2.0a0 + - xorg-libxext >=1.3.6,<2.0a0 + - xorg-libxi >=1.7.10,<2.0a0 + license: MIT + license_family: MIT + size: 32808 + timestamp: 1727964811275 +- conda: https://conda.anaconda.org/conda-forge/linux-64/zstd-1.5.7-hb78ec9c_6.conda + sha256: 68f0206ca6e98fea941e5717cec780ed2873ffabc0e1ed34428c061e2c6268c7 + md5: 4a13eeac0b5c8e5b8ab496e6c4ddd829 + depends: + - __glibc >=2.17,<3.0.a0 + - libzlib >=1.3.1,<2.0a0 + license: BSD-3-Clause + license_family: BSD + size: 601375 + timestamp: 1764777111296 diff --git a/release-20261107/source/workspace_joint/mira/pixi.toml b/release-20261107/source/workspace_joint/mira/pixi.toml new file mode 100644 index 0000000000000000000000000000000000000000..36c03421ffaae7a18174ec2ea786d121f5e6dbcf --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/pixi.toml @@ -0,0 +1,53 @@ +# Standalone environment for mira. +# +# pixi provides FFmpeg 7 as a system dependency and puts its shared libraries on LD_LIBRARY_PATH so +# torchcodec can load them at runtime (a bare uv/pip env lacks these, which is the libtorchcodec / +# libavutil load error). Python dependencies (incl. torch/torchcodec) are installed editable from +# pyproject.toml via uv. +# +# pixi run setup # one-time: install mira + extras into the env (GPU/CUDA torch) +# pixi run setup-cpu # same, but CPU-only torch (no GPU on this machine) +# pixi run test # pytest +# pixi run verify # format + lint + typecheck + test +# +# `setup` installs a CUDA (cu128) build of torch by default so training runs on the GPU out of the +# box; use `setup-cpu` on a machine without an NVIDIA GPU. torch and torchcodec are pinned to the +# validated pair -- torch 2.8 + torchcodec 0.7.0 (CPU decode) + FFmpeg 7 -- for two reasons: video is +# decoded on the dataloader workers (CPU torchcodec, whose ABI must match torch), and this is the +# combination `torch.compile` is stable on. Newer torch (e.g. 2.11) hits a Triton/inductor +# illegal-memory-access compiling the codec graph, so don't unpin it without re-checking compile. +# +# pip-only users don't need pixi: `pip install mira[decode,viz]` into any environment that +# already has a compatible FFmpeg. + +[workspace] +authors = ["moboehle "] +name = "mira" +version = "0.0.1" +channels = ["conda-forge"] +platforms = ["linux-64"] + +[activation.env] +# Let torchcodec find pixi's FFmpeg shared libraries at runtime. +LD_LIBRARY_PATH = "$PIXI_PROJECT_ROOT/.pixi/envs/default/lib:$LD_LIBRARY_PATH" + +[dependencies] +python = "3.12.*" +ffmpeg = ">=7,<8" +uv = "*" + +[tasks] +# GPU (default): CUDA (cu128) torch + CPU-decode torchcodec (see the header note on the torchcodec +# pin). torchcodec is installed in a second step from the CPU index: --torch-backend cu128 otherwise +# pulls the CUDA-decode torchcodec build, which needs CUDA NPP libs (libnppicc.so.12) that are absent +# on login/CPU nodes, so libtorchcodec fails to load there. --no-deps keeps torch on the cu128 build. +setup = "uv pip install --python $CONDA_PREFIX/bin/python --torch-backend cu128 -e '.[viz,notebook,hf,train,dev]' 'torch==2.8.*' && uv pip install --python $CONDA_PREFIX/bin/python --no-deps torchcodec==0.7.0 --index-url https://download.pytorch.org/whl/cpu" +# CPU-only fallback for machines without an NVIDIA GPU. +setup-cpu = "uv pip install --python $CONDA_PREFIX/bin/python --torch-backend cpu -e '.[decode,viz,notebook,hf,train,dev]' 'torch==2.8.*' torchcodec==0.7.0" +explore = "marimo run examples/explore.py" +edit = "marimo edit --headless --port 2718 examples/explore.py" +test = "pytest -q" +format = "ruff format src tests" +lint = "ruff check src tests" +typecheck = "pyright src tests" +verify = { depends-on = ["format", "lint", "typecheck", "test"] } diff --git a/release-20261107/source/workspace_joint/mira/pyproject.toml b/release-20261107/source/workspace_joint/mira/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..7100766a86c73d2f71192915f0b30ea470afa79c --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/pyproject.toml @@ -0,0 +1,84 @@ +[project] +name = "mira" +version = "0.0.1" +description = "MIRA (Multiplayer Interactive World Models with Representation Autoencoders): a multiplayer world model for Rocket League, with a loader for the 4-player dataset (time-aligned video frames, keyboard actions, and game events)." +readme = "README.md" +requires-python = ">=3.10" +license = "Apache-2.0" +license-files = ["LICENSE"] +dependencies = [ + "pydantic>=2.11", + "numpy>=1.24", + "einops>=0.8", # the codec/world-model layers use it; needed by every install that loads a model +] + +[project.urls] +Homepage = "https://mira-wm.com" +Repository = "https://github.com/mira-wm/mira" + +[project.optional-dependencies] +# Video decoding. torchcodec needs a runtime FFmpeg whose libs match its build; a known-good +# torch/torchcodec/FFmpeg combination is torchcodec 0.7.0 + torch 2.8.0 + FFmpeg 7. torch is not +# pinned here — consumers provide their own torch. +decode = ["torchcodec"] +robotwin = ["h5py", "torchvision"] +wam = [ + "mira[robotwin,hydra,viz]", + "safetensors>=0.5,<1", + "transformers>=4.50,<5", + "sentencepiece>=0.2,<1", + "ftfy>=6,<7", + "regex>=2024.11", + "swanlab>=0.9,<1", +] +hf = ["datasets>=3", "huggingface_hub"] +viz = ["matplotlib", "pillow", "plotly"] +notebook = ["marimo", "matplotlib", "pillow"] +# Hydra config loading for the training/inference scripts. +hydra = ["hydra-core>=1.3", "omegaconf>=2.3"] +# Training: Hydra plus logging/metrics tooling (einops is a base dep). torch is unpinned (consumers +# BYO; the train/inference code targets torch>=2.8). DINOv3 weights load via torch.hub (no pip dep); +# torchmetrics + termcolor are transitive runtime deps of that hub repo. +train = [ + "mira[hydra]", + "mira[robotwin]", + "mira[viz]", # codec.viz needs plotly; training.visualization needs pillow + "tqdm", + "wandb", + "swanlab>=0.9,<1", + "lpips", + "rich", + "setproctitle", + "torchmetrics", + "termcolor", +] +# Offline world-model metrics: Frechet DINO/Inception (DINO loads via torch.hub). Heavy and +# eval-only, deliberately kept out of `train`; the trainer's downstream-metrics eval logs and +# skips when this isn't installed. Reads eval clips (decode) and builds the +# model from its saved Hydra config. +eval = ["mira[decode]", "mira[hydra]", "pytorch-fid", "scipy"] +dev = ["pytest", "ruff", "pyright"] + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.build.targets.wheel] +packages = ["src/mira"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +addopts = "--import-mode=importlib" + +[tool.ruff] +line-length = 110 +extend-exclude = ["examples"] # marimo notebooks have their own (generated) style + +[tool.ruff.lint] +extend-select = ["I"] # import sorting + +[tool.pyright] +include = ["src", "tests"] +pythonVersion = "3.10" +venvPath = ".pixi/envs" +venv = "default" diff --git a/release-20261107/source/workspace_joint/mira/scripts/README.md b/release-20261107/source/workspace_joint/mira/scripts/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2386a65ef59978bbe3b01a952066194a71063027 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/README.md @@ -0,0 +1,14 @@ +# Entry-point scripts + +Hydra applications for training, evaluation, and serving. Each reads its config from `configs/` +(override any key as `key=value`) and runs single-GPU, or multi-GPU under `torchrun`. + +- `train_codec.py` — train the video codec. +- `train_world_model.py` — train the world model (single-player, or add + `model=multi_wrapper_world_model dataset.n_players=4` for 4-player). +- `eval_world_model_offline.py` — offline evaluation of a trained world model (validation loss + + rollout metrics) from a checkpoint. +- `bench_wm_speed.py` — micro-benchmark world-model rollout speed. + +See [`configs/README.md`](../configs/README.md) for the config layout and the top-level +[`README.md`](../README.md) for example commands. diff --git a/release-20261107/source/workspace_joint/mira/scripts/audit_robotwin_wam_data.py b/release-20261107/source/workspace_joint/mira/scripts/audit_robotwin_wam_data.py new file mode 100644 index 0000000000000000000000000000000000000000..87bd32c32f89988e18f8c591e66f57930237092b --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/audit_robotwin_wam_data.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python3 +"""Fail-fast audit of built RoboTwin Stage-W manifests and cached artifacts.""" + +from __future__ import annotations + +import argparse +import ctypes +import json +from collections import Counter +from pathlib import Path + +import torch +from safetensors import safe_open + +from mira.data.robotwin_wam_schema import read_jsonl, sha256_file, sha256_text + + +def _resolve(path_value: str, cache_root: Path) -> Path: + path = Path(path_value) + return path if path.is_absolute() else cache_root / path + + +def _audit_cache(row: dict, cache_root: Path, *, require_real_text: bool) -> None: + cache_path = _resolve(str(row.get("cache_path", "")), cache_root) + if not cache_path.is_file(): + raise FileNotFoundError(cache_path) + with safe_open(cache_path, framework="pt", device="cpu") as handle: + cache_metadata = handle.metadata() or {} + names = set(handle.keys()) + expected = {"world_latent_raw_bf16", "joint_target_state20_f32", "action20_f32", "source_index_i32"} + if names != expected: + raise ValueError(f"{cache_path}: tensor keys {names} != {expected}") + latent = handle.get_tensor("world_latent_raw_bf16") + state = handle.get_tensor("joint_target_state20_f32") + action = handle.get_tensor("action20_f32") + source = handle.get_tensor("source_index_i32") + if latent.ndim != 5 or latent.shape[0] != 3 or tuple(latent.shape[2:]) != (32, 9, 12): + raise ValueError(f"{cache_path}: invalid latent shape {tuple(latent.shape)}") + if state.shape != (source.numel(), 14) or action.shape != (source.numel() - 1, 14): + raise ValueError(f"{cache_path}: invalid state/action/source shapes") + if not torch.equal(action, state[1:]): + raise ValueError(f"{cache_path}: action20 is not the exact next drive target") + if not all(torch.isfinite(value).all() for value in (latent, state, action)): + raise ValueError(f"{cache_path}: non-finite cached tensor") + expected_metadata = { + "episode_sha256": str(row["episode_sha256"]), + "codec_sha256": str(row["codec_sha256"]), + "view_order": "left,global,right", + "state_semantics": "simulator_drive_target_not_measured_qpos", + } + for key, expected in expected_metadata.items(): + if cache_metadata.get(key) != expected: + raise ValueError(f"{cache_path}: metadata {key}={cache_metadata.get(key)!r} != {expected!r}") + + instruction = str(row["instruction"]) + instruction_hash = sha256_text(instruction) + if instruction_hash != row.get("instruction_sha256"): + raise ValueError(f"{cache_path}: instruction hash mismatch") + text_path = _resolve(str(row.get("text_cache_path", "")), cache_root) + if not text_path.is_file(): + raise FileNotFoundError(text_path) + with safe_open(text_path, framework="pt", device="cpu") as handle: + text_metadata = handle.metadata() or {} + if set(handle.keys()) != {"text_hidden_bf16", "text_mask_bool"}: + raise ValueError(f"{text_path}: invalid text tensor keys") + hidden = handle.get_tensor("text_hidden_bf16") + mask = handle.get_tensor("text_mask_bool") + if hidden.ndim != 2 or hidden.shape[1] != 4096 or mask.shape != (hidden.shape[0],): + raise ValueError(f"{text_path}: invalid text shapes {hidden.shape=} {mask.shape=}") + if hidden.dtype != torch.bfloat16 or mask.dtype != torch.bool or not torch.isfinite(hidden).all(): + raise ValueError(f"{text_path}: invalid text dtype or non-finite hidden state") + if not mask.all(): + raise ValueError(f"{text_path}: compact text cache must contain only valid tokens") + if text_metadata.get("instruction_sha256") != instruction_hash: + raise ValueError(f"{text_path}: text metadata instruction hash mismatch") + if require_real_text and ( + bool(row.get("text_cache_debug_only")) or text_metadata.get("debug_only") != "false" + ): + raise ValueError(f"{text_path}: formal audit refuses debug text embeddings") + + +def main() -> None: + ctypes.CDLL(None).prctl(15, b"syncnet_core_a", 0, 0, 0) + parser = argparse.ArgumentParser() + parser.add_argument("--train-manifest", required=True) + parser.add_argument("--val-manifest", required=True) + parser.add_argument("--cache-root") + parser.add_argument("--raw-summary") + parser.add_argument("--cache-stats") + parser.add_argument("--max-cache-checks", type=int, default=100) + parser.add_argument("--require-complete-summary", action="store_true") + parser.add_argument("--report", required=True) + args = parser.parse_args() + + train_path, val_path = Path(args.train_manifest), Path(args.val_manifest) + train, val = read_jsonl(train_path), read_jsonl(val_path) + train_ids = {row["episode_sha256"] for row in train} + val_ids = {row["episode_sha256"] for row in val} + overlap = train_ids & val_ids + if overlap: + raise RuntimeError(f"train/val overlap: {sorted(overlap)[:5]}") + if any(row.get("robot") != "aloha-agilex" for row in train + val): + raise RuntimeError("Stage W manifest contains a non-ALOHA embodiment") + if any(row.get("state_semantics") != "simulator_drive_target_not_measured_qpos" for row in train + val): + raise RuntimeError("state semantics missing or ambiguous") + + summary_path = Path(args.raw_summary) if args.raw_summary else train_path.parent / "summary.json" + summary = json.loads(summary_path.read_text(encoding="utf-8")) if summary_path.is_file() else {} + if args.require_complete_summary and not summary.get("complete_audit", False): + raise RuntimeError( + f"Formal training requires a complete, unbounded raw-data audit: {summary_path}" + ) + cache_stats_path = Path(args.cache_stats) if args.cache_stats else train_path.parent / "stats.json" + cache_stats = ( + json.loads(cache_stats_path.read_text(encoding="utf-8")) if cache_stats_path.is_file() else {} + ) + if args.require_complete_summary: + if not cache_stats.get("complete_cache", False): + raise RuntimeError(f"Formal training requires a complete latent cache: {cache_stats_path}") + if cache_stats.get("text_cache_debug_only", True): + raise RuntimeError(f"Formal training refuses a debug text cache: {cache_stats_path}") + if int(cache_stats.get("episodes", -1)) != len(train) + len(val): + raise RuntimeError(f"Cache stats episode count disagrees with manifests: {cache_stats_path}") + codec_hashes = {str(row.get("codec_sha256")) for row in train + val} + if codec_hashes != {str(cache_stats.get("codec_sha256"))}: + raise RuntimeError(f"Codec hash mismatch between cache stats and manifests: {codec_hashes}") + expected_normalization = [0.024823864160431405, 1.9595992324017892] + if cache_stats.get("codec_latent_mean_std") != expected_normalization: + raise RuntimeError( + f"Codec normalization mismatch: {cache_stats.get('codec_latent_mean_std')}" + ) + + cache_checks = 0 + if args.cache_root: + root = Path(args.cache_root) + for row in (train + val)[: args.max_cache_checks]: + _audit_cache(row, root, require_real_text=bool(args.require_complete_summary)) + cache_checks += 1 + + report = { + "passed": True, + "train_episodes": len(train), + "val_episodes": len(val), + "split_overlap": 0, + "cache_checks": cache_checks, + "train_manifest_sha256": sha256_file(train_path), + "val_manifest_sha256": sha256_file(val_path), + "tasks": dict(Counter(row["task"] for row in train)), + "domains": dict(Counter(row["domain"] for row in train)), + "state_semantics": "simulator_drive_target_not_measured_qpos", + "complete_raw_audit": bool(summary.get("complete_audit", False)), + "complete_cache": bool(cache_stats.get("complete_cache", False)), + "codec_sha256": cache_stats.get("codec_sha256"), + } + path = Path(args.report) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/bench_wm_speed.py b/release-20261107/source/workspace_joint/mira/scripts/bench_wm_speed.py new file mode 100644 index 0000000000000000000000000000000000000000..a8528cdfa708869adf25d426af464b35192e8c04 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/bench_wm_speed.py @@ -0,0 +1,107 @@ +"""Benchmark pure world-model denoising speed (no decode, no metrics). + +Times the autoregressive :func:`mira.inference.rollout.rollout` on one GPU at batch size 1, +for a sweep of ``n_diffusion_steps``. +Works for single-player and 4-player checkpoints (the class is inferred from the saved config):: + + python scripts/bench_wm_speed.py --schedule-type linear \\ + --n-diffusion-steps 1 2 4 8 +""" + +from __future__ import annotations + +import argparse + +import torch + +from mira.inference.loading import load_world_model +from mira.inference.rollout import measure_rollout_speed +from mira.training.checkpoints import resolve_checkpoint +from mira.world_model.config import WorldModelInferenceConfig + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("checkpoint", type=str) + parser.add_argument("--n-diffusion-steps", type=int, nargs="+", default=[1, 2, 4, 8]) + parser.add_argument("--schedule-type", type=str, default="linear", choices=["linear", "linear_quadratic"]) + parser.add_argument("--n-frames", type=int, default=32, help="latent frames to unroll") + parser.add_argument("--compile", action="store_true") + parser.add_argument( + "--noise-level", + type=lambda s: None if s.lower() == "none" else float(s), + default=0.2, + help="kv-cache noise level; 'none' merges the cache update into the last diffusion step.", + ) + return parser.parse_args() + + +CONFIG_FILENAME = "world_model_config.yaml" + + +def main() -> None: + from omegaconf import OmegaConf + + from mira.data.training_loader import create_loader + + args = parse_args() + device = torch.device("cuda") + checkpoint = resolve_checkpoint(args.checkpoint).resolve() + # The dataset index lives in the run config saved two dirs above the checkpoint (the output dir). + cfg = OmegaConf.load(checkpoint.parents[1] / CONFIG_FILENAME) + model, _ = load_world_model(checkpoint, device=device) + model.eval() + if args.compile: + model.world_model.compile() + + frame_size = cfg.dataset.get("frame_size") + dataloader = create_loader( + index_path=cfg.dataset.test_index, + clip_len=model.config.n_context_frames + args.n_frames * model.temporal_downsampling, + target_fps=model.config.video.fps, + n_players=getattr(model, "n_players", 1), + batch_size=1, + num_workers=0, + valid_keys=list(model.config.actions.valid_keys), + action_fps=model.config.actions.target_fps, + frame_size=tuple(frame_size) if frame_size is not None else None, + seed=38, + infinite=True, + ) + batch, _ = next(iter(dataloader)) + batch = batch.to(device) + + latent_fps = model.config.video.fps / model.temporal_downsampling + print( + f"latent fps: {latent_fps:.2f} (video {model.config.video.fps} fps, " + f"temporal downsampling {model.temporal_downsampling})" + ) + + with torch.no_grad(), torch.autocast(device_type="cuda", dtype=torch.bfloat16): + # Warmup (compile / cudnn autotune) with the largest step count. + warm_cfg = WorldModelInferenceConfig( + n_diffusion_steps=max(args.n_diffusion_steps), + schedule_type=args.schedule_type, + noise_level=args.noise_level, + ) + measure_rollout_speed(model, batch, warm_cfg, n_frames=4) + + for steps in args.n_diffusion_steps: + config = WorldModelInferenceConfig( + n_diffusion_steps=steps, + schedule_type=args.schedule_type, + noise_level=args.noise_level, + ) + result = measure_rollout_speed(model, batch, config, n_frames=args.n_frames) + s_per_frame = result["denoise_ms_per_latent_frame"] / 1000 + print( + f"steps={steps}: {result['denoise_ms_per_latent_frame']:7.1f} ms/latent-frame " + f"({result['denoise_latent_fps']:6.2f} latent fps, " + f"{(1 / s_per_frame) / latent_fps:5.2f}x realtime)" + ) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/benchmark_robotwin_latent_views.py b/release-20261107/source/workspace_joint/mira/scripts/benchmark_robotwin_latent_views.py new file mode 100644 index 0000000000000000000000000000000000000000..3d0940b4fe66b4fd5a5a64ae9ff8fcab86b65ae7 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/benchmark_robotwin_latent_views.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Compare sequential and three-view-batched codec cache generation on one episode.""" + +from __future__ import annotations + +import argparse +import io +import json +import time +import zipfile +from pathlib import Path + +import h5py +import torch +from safetensors.torch import load_file + +from mira.codec.codec_model import VideoCodec +from mira.data.robotwin_wam_schema import half_up_source_indices, read_jsonl +from precompute_robotwin_latents import ( + _encode_episode_batched_views, + _encode_episode_sequential_views, +) + + +def _timed_encode(function, codec, episode, source, device: str): + torch.cuda.reset_peak_memory_stats(device) + torch.cuda.synchronize(device) + started = time.perf_counter() + latents, overlap_error = function(codec, episode, source, device=device) + torch.cuda.synchronize(device) + elapsed = time.perf_counter() - started + peak_gib = torch.cuda.max_memory_allocated(device) / (1024**3) + return latents, overlap_error, elapsed, peak_gib + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--dataset-root", required=True) + parser.add_argument("--manifest", required=True) + parser.add_argument("--codec-checkpoint", required=True) + parser.add_argument("--row-index", type=int, default=0) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--cpu-threads", type=int, default=8) + parser.add_argument("--existing-cache-root") + args = parser.parse_args() + + torch.set_num_threads(args.cpu_threads) + torch.set_num_interop_threads(1) + root = Path(args.dataset_root).expanduser().resolve() + row = read_jsonl(Path(args.manifest).expanduser().resolve())[args.row_index] + source = half_up_source_indices(int(row["n_source_frames"])) + if source.numel() % 2: + source = source[:-1] + + codec = VideoCodec.load_from_checkpoint(args.codec_checkpoint, device="cpu") + codec.eval().requires_grad_(False) + codec.encoder.to(args.device) + with zipfile.ZipFile(root / str(row["archive"])) as archive: + payload = archive.read(str(row["member"])) + with h5py.File(io.BytesIO(payload), "r") as episode: + sequential, sequential_overlap, sequential_seconds, sequential_peak = _timed_encode( + _encode_episode_sequential_views, codec, episode, source, args.device + ) + batched, batched_overlap, batched_seconds, batched_peak = _timed_encode( + _encode_episode_batched_views, codec, episode, source, args.device + ) + + difference = (sequential.float() - batched.float()).abs() + result = { + "row_index": args.row_index, + "archive": row["archive"], + "member": row["member"], + "n_source_frames": row["n_source_frames"], + "latent_shape": list(sequential.shape), + "sequential_seconds": sequential_seconds, + "batched_seconds": batched_seconds, + "speedup": sequential_seconds / batched_seconds, + "sequential_peak_allocated_gib": sequential_peak, + "batched_peak_allocated_gib": batched_peak, + "sequential_overlap_max_abs": sequential_overlap, + "batched_overlap_max_abs": batched_overlap, + "latent_exact": torch.equal(sequential, batched), + "latent_max_abs": float(difference.max()), + "latent_mean_abs": float(difference.mean()), + "latent_p99_abs": float(torch.quantile(difference.flatten(), 0.99)), + } + if args.existing_cache_root: + digest = str(row["episode_sha256"]) + cache_path = ( + Path(args.existing_cache_root).expanduser().resolve() + / "episodes" + / digest[:2] + / digest[2:4] + / f"{digest}.safetensors" + ) + cached = load_file(cache_path)["world_latent_raw_bf16"] + cache_difference = (sequential.float() - cached.float()).abs() + result.update( + existing_cache_path=str(cache_path), + sequential_matches_existing_cache=torch.equal(sequential, cached), + existing_cache_max_abs=float(cache_difference.max()), + existing_cache_mean_abs=float(cache_difference.mean()), + ) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/build_action_future_cache.py b/release-20261107/source/workspace_joint/mira/scripts/build_action_future_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..a9f2bf60bb7d3adba9e9a12680ea72465e9b6b1b --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/build_action_future_cache.py @@ -0,0 +1,324 @@ +#!/usr/bin/env python3 +"""Generate deterministic pooled 10-step World predictions for Action training.""" + +from __future__ import annotations + +import argparse +import ctypes +import hashlib +import json +import os +import shutil +from collections import OrderedDict +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F +from safetensors.torch import load_file + +from mira.action.world_checkpoint import ( + apply_ema_to_model, + hash_tensor_state, + load_world_online_and_ema, +) +from mira.data.robotwin_wam_loader import RoboTwinWorldBatch +from mira.data.robotwin_wam_schema import read_jsonl, sha256_file + + +def _set_process_name(shard: int) -> None: + ctypes.CDLL(None).prctl(15, f"syncnet_act_f{shard}".encode()[:15], 0, 0, 0) + + +def _seed(selection: dict, split: str, window_id: str) -> int: + payload = ( + f"{selection['selected_state_dict_sha256']}:{split}:{window_id}:" + "world_steps=10:base_seed=2026" + ) + return int.from_bytes(hashlib.sha256(payload.encode()).digest()[:8], "big") + + +class ConditionReader: + def __init__(self, state_stats: str | Path) -> None: + stats = json.loads(Path(state_stats).read_text(encoding="utf-8")) + self.mean = torch.tensor(stats["mean"], dtype=torch.float32) + self.std = torch.tensor(stats["std"], dtype=torch.float32).clamp_min( + float(stats.get("normalization_std_floor", 1.0e-2)) + ) + self.clip = float(stats.get("normalization_clip", 5)) + self.episodes: OrderedDict[str, dict[str, torch.Tensor]] = OrderedDict() + self.text: OrderedDict[str, dict[str, torch.Tensor]] = OrderedDict() + + @staticmethod + def _load( + path: str, + cache: OrderedDict[str, dict[str, torch.Tensor]], + limit: int, + ) -> dict[str, torch.Tensor]: + if path in cache: + value = cache.pop(path) + cache[path] = value + return value + value = load_file(path, device="cpu") + cache[path] = value + while len(cache) > limit: + cache.popitem(last=False) + return value + + def _normalize(self, value: torch.Tensor) -> torch.Tensor: + return ((value.float() - self.mean) / self.std).clamp(-self.clip, self.clip) + + def batch(self, row: dict, device: torch.device) -> RoboTwinWorldBatch: + episode = self._load(row["cache_path"], self.episodes, 2) + text = self._load(row["text_cache_path"], self.text, 64) + latent_start = int(row["latent_start"]) + state_start = 2 * latent_start + latent = episode["world_latent_raw_bf16"] + context = latent[:, latent_start : latent_start + 10] + future = latent[:, latent_start + 10 : latent_start + 20] + state = episode["joint_target_state20_f32"] + action = episode["action20_f32"] + history = self._normalize(state[state_start : state_start + 20]).reshape(20, 2, 7) + valid = torch.ones(20, dtype=torch.bool) + if state_start == 0: + previous = torch.zeros(20, 14) + previous[1:] = action[:19] + valid[0] = False + else: + previous = action[state_start - 1 : state_start + 19] + action_history = self._normalize(previous).reshape(20, 2, 7) + return RoboTwinWorldBatch( + world_context_raw=context[None], + world_future_raw=future[None], + joint_target_history=history[None], + action_history=action_history[None], + history_valid=valid[None], + text_hidden=text["text_hidden_bf16"][None], + text_mask=text["text_mask_bool"][None], + future_valid=torch.ones(1, 10, dtype=torch.bool), + view_valid=torch.ones(1, 3, dtype=torch.bool), + ).to(device) + + +def _collate_world_batches(batches: list[RoboTwinWorldBatch]) -> RoboTwinWorldBatch: + if not batches: + raise ValueError("Cannot collate an empty World batch") + max_text = max(batch.text_hidden.shape[1] for batch in batches) + text = torch.zeros(len(batches), max_text, 4096, dtype=torch.bfloat16) + text_mask = torch.zeros(len(batches), max_text, dtype=torch.bool) + for index, batch in enumerate(batches): + length = batch.text_hidden.shape[1] + text[index, :length] = batch.text_hidden[0] + text_mask[index, :length] = batch.text_mask[0] + return RoboTwinWorldBatch( + world_context_raw=torch.cat([batch.world_context_raw for batch in batches]), + world_future_raw=torch.cat([batch.world_future_raw for batch in batches]), + joint_target_history=torch.cat( + [batch.joint_target_history for batch in batches] + ), + action_history=torch.cat([batch.action_history for batch in batches]), + history_valid=torch.cat([batch.history_valid for batch in batches]), + text_hidden=text, + text_mask=text_mask, + future_valid=torch.cat([batch.future_valid for batch in batches]), + view_valid=torch.cat([batch.view_valid for batch in batches]), + ) + + +def _build_shard(args: argparse.Namespace) -> None: + _set_process_name(args.shard_index) + selection = json.loads(Path(args.world_selection).read_text(encoding="utf-8")) + rows = [ + row + for row in read_jsonl(args.action_manifest) + if int(row["future_cache_shard"]) == args.shard_index + ] + rows.sort(key=lambda row: int(row["future_cache_row"])) + if [int(row["future_cache_row"]) for row in rows] != list(range(len(rows))): + raise ValueError("Future cache rows are not contiguous within shard") + root = Path(args.output_dir).expanduser().resolve() + final = root / f"shard-{args.shard_index:05d}" + if (final / "COMPLETE").is_file() and not args.overwrite: + print(f"Reusing complete future-cache shard {final}") + return + temporary = root / f".shard-{args.shard_index:05d}.tmp" + temporary.mkdir(parents=True, exist_ok=True) + tensor_path = temporary / "future_pred10.f16" + bitmap_path = temporary / "completed.u8" + shape = (len(rows), 3, 10, 32, 3, 4) + values = np.memmap(tensor_path, mode="r+" if tensor_path.exists() else "w+", dtype=np.float16, shape=shape) + bitmap = np.memmap( + bitmap_path, + mode="r+" if bitmap_path.exists() else "w+", + dtype=np.uint8, + shape=(len(rows),), + ) + checkpoint = Path(selection["checkpoint"]).expanduser().resolve() + if sha256_file(checkpoint / "distributed" / ".metadata") != selection[ + "checkpoint_metadata_sha256" + ]: + raise ValueError("World DCP metadata changed after branch selection") + if sha256_file(checkpoint / "trainer_state.json") != selection["trainer_state_sha256"]: + raise ValueError("World trainer metadata changed after branch selection") + model, ema, _ = load_world_online_and_ema(checkpoint) + branch = selection["selected_branch"] + actual_hash = ( + hash_tensor_state(model.state_dict()) + if branch == "online" + else hash_tensor_state(ema.state) + ) + expected_branch_hash = selection[ + "online_state_dict_sha256" if branch == "online" else "ema_state_dict_sha256" + ] + if actual_hash != expected_branch_hash or actual_hash != selection["selected_state_dict_sha256"]: + raise ValueError("Loaded World branch does not match the selected tensor-state hash") + if branch == "ema": + apply_ema_to_model(model, ema) + device = torch.device(args.device) + model = model.to(device=device, dtype=torch.bfloat16).eval().requires_grad_(False) + reader = ConditionReader(args.state_stats) + pending = [index for index in range(len(rows)) if not bitmap[index]] + for batch_start in range(0, len(pending), args.batch_size): + indices = pending[batch_start : batch_start + args.batch_size] + examples = [ + reader.batch(rows[index], torch.device("cpu")) for index in indices + ] + batch = _collate_world_batches(examples).to(device) + noise = torch.cat( + [ + torch.randn( + batch.world_future_raw[index : index + 1].shape, + device=device, + dtype=torch.bfloat16, + generator=torch.Generator(device=device).manual_seed( + _seed( + selection, + rows[row_index]["split"], + rows[row_index]["window_id"], + ) + ), + ) + for index, row_index in enumerate(indices) + ] + ) + with torch.inference_mode(), torch.autocast(device_type="cuda", dtype=torch.bfloat16): + prediction_raw = model.sample_future(batch, steps=10, noise=noise) + prediction = (prediction_raw.float() - float(selection["latent_mean"])) / float( + selection["latent_std"] + ) + pooled = F.adaptive_avg_pool2d( + prediction.reshape(len(indices) * 3 * 10, 32, 9, 12), + (3, 4), + ).reshape(len(indices), 3, 10, 32, 3, 4) + if not torch.isfinite(pooled).all(): + raise RuntimeError( + f"Non-finite World prediction in rows " + f"{[rows[index]['window_id'] for index in indices]}" + ) + pooled_numpy = pooled.cpu().numpy().astype(np.float16) + for local_index, row_index in enumerate(indices): + values[row_index] = pooled_numpy[local_index] + bitmap[row_index] = 1 + completed = int(bitmap.sum()) + if completed % args.flush_every < len(indices) or completed == len(rows): + values.flush() + bitmap.flush() + print( + f"shard={args.shard_index} completed={completed}/{len(rows)} " + f"batch_size={len(indices)}", + flush=True, + ) + values.flush() + bitmap.flush() + if not bool(np.asarray(bitmap).all()) or not np.isfinite(np.asarray(values)).all(): + raise RuntimeError("Future-cache shard failed completion/finite audit") + metadata = { + "format_version": 1, + "shard": args.shard_index, + "rows": len(rows), + "shape_per_row": [3, 10, 32, 3, 4], + "dtype": "float16", + "tensor_sha256": sha256_file(tensor_path), + "window_ids_sha256": hashlib.sha256( + "\n".join(row["window_id"] for row in rows).encode() + ).hexdigest(), + } + (temporary / "metadata.json").write_text(json.dumps(metadata, indent=2) + "\n", encoding="utf-8") + (temporary / "COMPLETE").write_text("complete\n", encoding="utf-8") + if final.exists(): + if not args.overwrite: + raise FileExistsError(final) + shutil.rmtree(final) + os.replace(temporary, final) + print(json.dumps(metadata, indent=2)) + + +def _finalize(args: argparse.Namespace) -> None: + root = Path(args.output_dir).expanduser().resolve() + rows = read_jsonl(args.action_manifest) + selection = json.loads(Path(args.world_selection).read_text(encoding="utf-8")) + shard_metadata = [] + for shard in range(args.num_shards): + shard_root = root / f"shard-{shard:05d}" + if not (shard_root / "COMPLETE").is_file(): + raise ValueError(f"Missing complete future-cache shard: {shard_root}") + shard_metadata.append( + json.loads((shard_root / "metadata.json").read_text(encoding="utf-8")) + ) + if sum(int(value["rows"]) for value in shard_metadata) != len(rows): + raise ValueError("Future-cache shard count does not match Action manifest") + metadata = { + "format_version": 1, + "action_manifest": str(Path(args.action_manifest).resolve()), + "action_manifest_sha256": sha256_file(args.action_manifest), + "world_selection": str(Path(args.world_selection).resolve()), + "world_selection_sha256": sha256_file(args.world_selection), + "world_state_dict_sha256": selection["selected_state_dict_sha256"], + "world_branch": selection["selected_branch"], + "world_steps": 10, + "world_schedule": "linear_quadratic", + "world_solver": "euler", + "seed_rule": "sha256(world_sha,split,window_id,world_steps=10,base_seed=2026)", + "view_order": ["left", "global", "right"], + "pooling": "adaptive_avg_pool2d_3x4", + "latent_space": "world_standardized", + "shape_per_row": [3, 10, 32, 3, 4], + "dtype": "float16", + "shards": args.num_shards, + "rows": len(rows), + "shard_metadata": shard_metadata, + } + root.mkdir(parents=True, exist_ok=True) + temporary = root / "metadata.json.tmp" + temporary.write_text(json.dumps(metadata, indent=2) + "\n", encoding="utf-8") + os.replace(temporary, root / "metadata.json") + (root / "COMPLETE").write_text("complete\n", encoding="utf-8") + print(json.dumps(metadata, indent=2)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--action-manifest", required=True) + parser.add_argument("--state-stats", required=True) + parser.add_argument("--world-selection", required=True) + parser.add_argument("--output-dir", required=True) + parser.add_argument("--num-shards", type=int, required=True) + parser.add_argument("--shard-index", type=int, default=0) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--flush-every", type=int, default=10) + parser.add_argument("--batch-size", type=int, default=1) + parser.add_argument("--overwrite", action="store_true") + parser.add_argument("--finalize-only", action="store_true") + args = parser.parse_args() + if args.batch_size < 1: + raise ValueError("batch-size must be positive") + if args.finalize_only: + _finalize(args) + else: + if not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid future-cache shard index") + _build_shard(args) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/build_joint_eval_language_manifest.py b/release-20261107/source/workspace_joint/mira/scripts/build_joint_eval_language_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..e3527a830b62ab3b751acbdf01c4b83b229fc825 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/build_joint_eval_language_manifest.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Build a joint manifest with RoboTwin seen-language pools from training scenes. + +No evaluation episode, seed, or rollout is read. Episode/action data are not copied. +""" + +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict +import hashlib +import json +import os +from pathlib import Path +import random +import shutil +import sys +import zipfile + +from mira.data.robotwin_wam_schema import read_jsonl, sha256_file, sha256_text, write_jsonl_atomic + + +def unique_text(values): + return list(dict.fromkeys(value.strip() for value in values if isinstance(value, str) and value.strip())) + + +def main() -> None: + parser = argparse.ArgumentParser() + workspace = Path(__file__).resolve().parents[2] + parser.add_argument("--source-manifest-dir", type=Path, default=workspace / "datasets/RoboTwin2.0/mira_manifests/joint_anchor_v2") + parser.add_argument("--dataset-root", type=Path, default=workspace / "datasets/RoboTwin2.0") + parser.add_argument("--robotwin-root", type=Path, default=workspace / "transfer/robotwin-official-20260921") + parser.add_argument("--output-dir", type=Path, default=workspace / "datasets/RoboTwin2.0/mira_manifests/joint_eval_language_v3") + parser.add_argument("--seen-candidates", type=int, default=100) + args = parser.parse_args() + if args.seen_candidates < 1: + parser.error("--seen-candidates must be positive") + source = args.source_manifest_dir.resolve() + target = args.output_dir.resolve() + if source == target: + parser.error("output must differ from the source manifest") + if target.exists(): + raise FileExistsError(f"Refusing to overwrite prepared manifest: {target}") + output = target.with_name(f".{target.name}.building-{os.getpid()}") + robotwin = args.robotwin_root.resolve() + sys.path.insert(0, str(robotwin / "description/utils")) + from generate_episode_instructions import generate_episode_descriptions + + task_dir = robotwin / "description/task_instruction" + goals = {p.stem: str(json.loads(p.read_text())["full_description"]).strip() + for p in task_dir.glob("*.json")} + summaries = {} + source_summary = json.loads((source / "summary.json").read_text()) + if not source_summary.get("complete_audit") or source_summary.get("bounded_smoke_manifest"): + raise ValueError("Source must be the complete audited joint manifest") + output.mkdir(parents=True, exist_ok=True) + train_hashes = set() + val_hashes = set() + for split in ("train", "val"): + rows = read_jsonl(source / f"{split}.jsonl") + by_archive = defaultdict(list) + for row in rows: + by_archive[str(row["archive"])].append(row) + changed = [] + sizes = Counter() + missing_scene = 0 + for archive_name in sorted(by_archive): + with zipfile.ZipFile(args.dataset_root / archive_name) as archive: + first_member = str(by_archive[archive_name][0]["member"]) + scene_name = first_member.split("/data/", 1)[0] + "/scene_info.json" + if scene_name not in archive.namelist(): + raise ValueError(f"Missing scene_info: {archive_name}") + scenes = json.loads(archive.read(scene_name)) + for row in by_archive[archive_name]: + task = str(row["task"]) + goal = goals[task] + if not goal: + raise ValueError(f"Missing full_description for {task}") + episode_key = f"episode_{int(row['episode'])}" + scene_entry = scenes.get(episode_key) + if not isinstance(scene_entry, dict): + missing_scene += 1 + raise ValueError(f"Missing {episode_key} in {archive_name}") + scene = scene_entry.get("info", {}) + if not isinstance(scene, dict): + raise ValueError(f"Invalid scene info for {archive_name}:{episode_key}") + random_state = random.getstate() + try: + seed = int.from_bytes(hashlib.sha256( + f"eval-language-v1\0{row['episode_sha256']}".encode() + ).digest()[:8], "big") + random.seed(seed) + generated = generate_episode_descriptions(task, [scene], args.seen_candidates) + finally: + random.setstate(random_state) + seen = unique_text(generated[0].get("seen", [])) if generated else [] + if not seen: + raise ValueError(f"No RoboTwin seen instructions for {archive_name}:{episode_key}") + updated = dict(row) + updated["instruction"] = seen[0] + updated["instruction_sha256"] = sha256_text(seen[0]) + updated["instruction_pool_v2"] = { + "seen": seen, "full_goal": [goal] + } + changed.append(updated) + sizes[len(seen)] += 1 + write_jsonl_atomic(output / f"{split}.jsonl", changed) + hashes = train_hashes if split == "train" else val_hashes + hashes.update(row["episode_sha256"] for row in changed) + summaries[split] = { + "episodes": len(changed), "tasks": len({row["task"] for row in changed}), + "seen_variants_min": min(sizes), "seen_variants_max": max(sizes), + "seen_variants_histogram": dict(sorted(sizes.items())), + "missing_scene": missing_scene, + "manifest_sha256": sha256_file(output / f"{split}.jsonl"), + "source_manifest_sha256": sha256_file(source / f"{split}.jsonl"), + } + print(f"{split}: {len(changed)} episodes; seen variants {min(sizes)}..{max(sizes)}", flush=True) + if train_hashes & val_hashes: + raise ValueError("Training/validation episode overlap") + shutil.copy2(source / "dataset_stats.json", output / "dataset_stats.json") + task_digests = {p.name: sha256_file(p) for p in sorted(task_dir.glob("*.json"))} + summary = { + **source_summary, + "instruction_pipeline": "robotwin_eval_seen_v2", + "instruction_generation": { + "generator": "description/utils/generate_episode_instructions.py:generate_episode_descriptions", + "seen_candidates_per_episode": args.seen_candidates, + "split": "seen_only; unseen templates never used", + "seed": "sha256(eval-language-v1\\0episode_sha256) first 64 bits", + "source": "training/validation archive scene_info only; no eval episodes or seeds", + "training_sources": ["seen", "full_goal"], + "full_goal_source": "description/task_instruction/.json:full_description", + "task_instruction_sha256": task_digests, + }, + "source_joint_manifest_dir": str(source), + "language_audit": summaries, + "output_manifest_sha256": {split: item["manifest_sha256"] for split, item in summaries.items()}, + "instruction_catalog": "RoboTwin seen task_instruction catalog with per-episode scene_info", + "instruction_fallback": "none; build fails if no seen instruction can be grounded", + } + temporary = output / ".summary.json.tmp" + temporary.write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n") + temporary.replace(output / "summary.json") + os.replace(output, target) + print(f"wrote {target}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/build_robotwin_action_manifest.py b/release-20261107/source/workspace_joint/mira/scripts/build_robotwin_action_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..881a0b2a96bd68b73028e67afac67cf74dec1ce2 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/build_robotwin_action_manifest.py @@ -0,0 +1,341 @@ +#!/usr/bin/env python3 +"""Derive immutable Action windows and train-only normalization from the World cache.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import warnings +from pathlib import Path +from typing import Iterator + +import numpy as np +from safetensors.torch import load_file + +from mira.data.robotwin_wam_loader import DeterministicBalancedSampler, RoboTwinWAMDataset +from mira.data.robotwin_wam_schema import half_up_source_indices, read_jsonl, sha256_file + + +def _set_process_name() -> None: + import ctypes + + ctypes.CDLL(None).prctl(15, b"syncnet_act_m", 0, 0, 0) + + +def _window_id(episode_sha: str, latent_start: int) -> str: + return hashlib.sha256(f"{episode_sha}:{latent_start}".encode()).hexdigest() + + +def _selected_indices( + dataset: RoboTwinWAMDataset, + *, + maximum: int | None, + seed: int, +) -> Iterator[int]: + if maximum is None or maximum >= len(dataset): + yield from range(len(dataset)) + return + sampler = DeterministicBalancedSampler(dataset, seed=seed) + selected: set[int] = set() + for index in sampler: + if index in selected: + continue + selected.add(index) + yield index + if len(selected) == maximum: + return + + +class StreamingMoments: + def __init__(self, dimensions: int, *, sample_modulus: int = 127) -> None: + self.count = 0 + self.sum = np.zeros(dimensions, dtype=np.float64) + self.sum_sq = np.zeros(dimensions, dtype=np.float64) + self.minimum = np.full(dimensions, np.inf, dtype=np.float64) + self.maximum = np.full(dimensions, -np.inf, dtype=np.float64) + self.reservoir: list[np.ndarray] = [] + self.reservoir_limit = 250_000 + self.sampled_rows = 0 + self.seen_rows = 0 + self.sample_modulus = int(sample_modulus) + if self.sample_modulus < 1: + raise ValueError("sample_modulus must be positive") + + def update(self, value: np.ndarray) -> None: + value = np.asarray(value, dtype=np.float64).reshape(-1, self.sum.shape[0]) + if not np.isfinite(value).all(): + raise ValueError("Action target contains NaN/Inf") + self.count += value.shape[0] + self.sum += value.sum(axis=0) + self.sum_sq += np.square(value).sum(axis=0) + self.minimum = np.minimum(self.minimum, value.min(axis=0)) + self.maximum = np.maximum(self.maximum, value.max(axis=0)) + indices = np.arange( + self.seen_rows, + self.seen_rows + value.shape[0], + dtype=np.uint64, + ) + # SplitMix64 gives a deterministic position-independent ~1/modulus sample without + # a Python loop over the roughly 30M exposed action rows in the formal manifest. + keys = indices + np.uint64(0x9E3779B97F4A7C15) + keys = (keys ^ (keys >> np.uint64(30))) * np.uint64(0xBF58476D1CE4E5B9) + keys = (keys ^ (keys >> np.uint64(27))) * np.uint64(0x94D049BB133111EB) + keys ^= keys >> np.uint64(31) + selected = value[(keys % np.uint64(self.sample_modulus)) == 0] + if len(selected) and self.sampled_rows < self.reservoir_limit: + selected = selected[: self.reservoir_limit - self.sampled_rows] + self.reservoir.append(selected.astype(np.float32, copy=True)) + self.sampled_rows += selected.shape[0] + self.seen_rows += value.shape[0] + + def finalize(self, *, strict_outliers: bool = True) -> dict: + mean = self.sum / self.count + variance = np.maximum(self.sum_sq / self.count - np.square(mean), 0) + std = np.sqrt(variance) + if np.any(std <= 1.0e-6): + raise ValueError(f"Degenerate Action standard deviation: {std.tolist()}") + sample = np.concatenate(self.reservoir, axis=0).astype(np.float64) + quantile_values = np.quantile(sample, [0.001, 0.01, 0.5, 0.99, 0.999], axis=0) + outlier_ratio = (np.abs((sample - mean) / std) > 5).mean(axis=0) + outlier_gate_passed = bool(np.all(outlier_ratio <= 1.0e-4)) + if strict_outliers and not outlier_gate_passed: + warnings.warn( + "Action global |z|>5 ratio exceeds the review threshold. The values are " + "retained and clipped during normalization because a multi-task mixture is " + "not Gaussian; inspect normalized_abs_gt_5_ratio_estimate in action_stats.json.", + stacklevel=2, + ) + grippers = {} + for dimension, name in ((6, "left"), (13, "right")): + values = sample[:, dimension] + centers = np.quantile(values, [0.1, 0.9]) + for _ in range(20): + assignment = np.abs(values[:, None] - centers[None]).argmin(axis=1) + updated = np.array( + [ + values[assignment == cluster].mean() + if np.any(assignment == cluster) + else centers[cluster] + for cluster in range(2) + ] + ) + if np.allclose(updated, centers): + break + centers = updated + centers.sort() + coverage = float( + (np.min(np.abs(values[:, None] - centers[None]), axis=1) <= 0.02).mean() + ) + grippers[name] = { + "mode": "binary" if coverage >= 0.995 else "continuous", + "low": float(centers[0]), + "high": float(centers[1]), + "threshold": float(centers.mean()), + "mode_coverage_atol_0.02": coverage, + } + return { + "format_version": 1, + "semantics": "absolute_simulator_drive_target_not_measured_qpos", + "dimension_order": [ + "left_joint_0", + "left_joint_1", + "left_joint_2", + "left_joint_3", + "left_joint_4", + "left_joint_5", + "left_gripper", + "right_joint_0", + "right_joint_1", + "right_joint_2", + "right_joint_3", + "right_joint_4", + "right_joint_5", + "right_gripper", + ], + "count": self.count, + "mean": mean.tolist(), + "std": std.tolist(), + "minimum": self.minimum.tolist(), + "maximum": self.maximum.tolist(), + "quantiles": { + name: values.tolist() + for name, values in zip( + ("q0.001", "q0.01", "q0.5", "q0.99", "q0.999"), + quantile_values, + ) + }, + "quantile_method": ( + f"deterministic_splitmix64_mod_{self.sample_modulus}_{len(sample)}" + ), + "normalized_abs_gt_5_ratio_estimate": outlier_ratio.tolist(), + "normalized_abs_gt_5_review_threshold": 1.0e-4, + "normalized_abs_gt_5_review_passed": outlier_gate_passed, + "outlier_policy": "retain_valid_drive_targets_and_clip_normalized_to_5", + "normalization_std_floor": 1.0e-6, + "normalization_clip": 5.0, + "gripper": grippers, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--train-world-manifest", required=True) + parser.add_argument("--val-world-manifest", required=True) + parser.add_argument("--state-stats", required=True) + parser.add_argument("--output-dir", required=True) + parser.add_argument("--future-shards", type=int, default=8) + parser.add_argument("--max-train-windows", type=int) + parser.add_argument("--max-val-windows", type=int) + parser.add_argument("--seed", type=int, default=2026) + parser.add_argument("--smoke-small-stats", action="store_true") + args = parser.parse_args() + _set_process_name() + if args.future_shards < 1: + raise ValueError("future-shards must be positive") + output = Path(args.output_dir).expanduser().resolve() + output.mkdir(parents=True, exist_ok=True) + moments = StreamingMoments( + 14, + sample_modulus=1 if args.smoke_small_stats else 127, + ) + task_chunk_sums: dict[str, np.ndarray] = {} + task_chunk_counts: dict[str, int] = {} + summaries: dict[str, dict] = {} + + for split, manifest, maximum in ( + ("train", args.train_world_manifest, args.max_train_windows), + ("val", args.val_world_manifest, args.max_val_windows), + ): + dataset = RoboTwinWAMDataset( + manifest, + args.state_stats, + require_real_text=True, + episode_cache_size=1, + ) + manifest_rows = read_jsonl(manifest) + path = output / f"{split}.jsonl" + temporary = path.with_suffix(".jsonl.tmp") + count = 0 + task_domain: dict[str, int] = {} + loaded_path = None + episode_tensors = None + with temporary.open("w", encoding="utf-8") as handle: + for dataset_index in _selected_indices( + dataset, + maximum=maximum, + seed=args.seed + (0 if split == "train" else 1_000_000), + ): + episode_index, latent_start = dataset._locate(dataset_index) + source_row = manifest_rows[episode_index] + source20 = half_up_source_indices(int(source_row["n_source_frames"])) + start20 = 2 * latent_start + context_indices = source20[start20 : start20 + 20].tolist() + action_indices = source20[start20 + 20 : start20 + 40].tolist() + if len(context_indices) != 20 or len(action_indices) != 20: + raise RuntimeError("World manifest yielded a truncated Action window") + cache_path = str(source_row["cache_path"]) + if cache_path != loaded_path: + episode_tensors = load_file(cache_path, device="cpu") + loaded_path = cache_path + assert episode_tensors is not None + target = episode_tensors["joint_target_state20_f32"][ + start20 + 20 : start20 + 40 + ] + if target.shape != (20, 14): + raise RuntimeError("Action target does not contain exactly 20x14 values") + if split == "train": + moments.update(target.numpy()) + task = str(source_row["task"]) + task_chunk_sums.setdefault( + task, np.zeros((20, 14), dtype=np.float64) + ) + task_chunk_sums[task] += target.numpy().astype(np.float64) + task_chunk_counts[task] = task_chunk_counts.get(task, 0) + 1 + shard = count % args.future_shards + cache_row = count // args.future_shards + row = { + "format_version": 1, + "window_id": _window_id(source_row["episode_sha256"], latent_start), + "split": split, + "task": source_row["task"], + "domain": source_row["domain"], + "robot": source_row["robot"], + "episode_sha256": source_row["episode_sha256"], + "latent_start": latent_start, + "cache_path": cache_path, + "text_cache_path": source_row["text_cache_path"], + "text_cache_debug_only": bool(source_row.get("text_cache_debug_only", False)), + "state_semantics": source_row["state_semantics"], + "context_source_idx": context_indices, + "future_video_source_idx": action_indices, + "action_source_idx": action_indices, + "future_cache_shard": shard, + "future_cache_row": cache_row, + } + handle.write(json.dumps(row, sort_keys=True) + "\n") + key = f"{source_row['task']}/{source_row['domain']}" + task_domain[key] = task_domain.get(key, 0) + 1 + count += 1 + os.replace(temporary, path) + summaries[split] = { + "windows": count, + "manifest": str(path), + "manifest_sha256": sha256_file(path), + "task_domain_counts": task_domain, + } + + stats = moments.finalize(strict_outliers=not args.smoke_small_stats) + stats["per_task_mean_chunk"] = { + task: (value / task_chunk_counts[task]).tolist() + for task, value in sorted(task_chunk_sums.items()) + } + stats["per_task_window_count"] = dict(sorted(task_chunk_counts.items())) + stats["global_mean_chunk"] = ( + sum(task_chunk_sums.values()) / sum(task_chunk_counts.values()) + ).tolist() + stats["smoke_only"] = bool(args.smoke_small_stats) + stats["train_action_manifest_sha256"] = summaries["train"]["manifest_sha256"] + stats["state_stats_sha256"] = sha256_file(args.state_stats) + source_state_stats = json.loads(Path(args.state_stats).read_text(encoding="utf-8")) + source_minimum = np.asarray(source_state_stats["minimum"], dtype=np.float64) + source_maximum = np.asarray(source_state_stats["maximum"], dtype=np.float64) + action_minimum = np.asarray(stats["minimum"], dtype=np.float64) + action_maximum = np.asarray(stats["maximum"], dtype=np.float64) + range_contained = bool( + np.all(action_minimum >= source_minimum - 1.0e-6) + and np.all(action_maximum <= source_maximum + 1.0e-6) + ) + if not range_contained: + raise ValueError( + "Action targets exceed the audited source drive-target range; refusing training" + ) + stats["source_drive_target_range_contained"] = range_contained + (output / "action_stats.json").write_text( + json.dumps(stats, indent=2) + "\n", + encoding="utf-8", + ) + summary = { + "format_version": 1, + "seed": args.seed, + "future_shards": args.future_shards, + "source_world_manifests": { + "train": { + "path": str(Path(args.train_world_manifest).resolve()), + "sha256": sha256_file(args.train_world_manifest), + }, + "val": { + "path": str(Path(args.val_world_manifest).resolve()), + "sha256": sha256_file(args.val_world_manifest), + }, + }, + "splits": summaries, + "action_stats_sha256": sha256_file(output / "action_stats.json"), + } + (output / "summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/build_robotwin_manifest.py b/release-20261107/source/workspace_joint/mira/scripts/build_robotwin_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..4ad151af15eb82d44285cfc8a847512d95f590f7 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/build_robotwin_manifest.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +"""Build stable train/validation manifests for the local RoboTwin 2.0 zip archives.""" + +from __future__ import annotations + +import argparse +import ctypes +import json + +from mira.data.robotwin_loader import build_robotwin_manifests + + +def _set_process_name() -> None: + libc = ctypes.CDLL(None) + libc.prctl(15, b"syncnet_manifest", 0, 0, 0) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--dataset-root", required=True) + parser.add_argument("--output-dir", required=True) + parser.add_argument("--val-fraction", type=float, default=0.02) + parser.add_argument("--seed", type=int, default=2026) + args = parser.parse_args() + + _set_process_name() + summary = build_robotwin_manifests( + args.dataset_root, + args.output_dir, + val_fraction=args.val_fraction, + seed=args.seed, + ) + print(json.dumps(summary, indent=2, ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/build_robotwin_wam_manifest.py b/release-20261107/source/workspace_joint/mira/scripts/build_robotwin_wam_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..c7269e4daacc4cdbb2e4740891ab62e09088498a --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/build_robotwin_wam_manifest.py @@ -0,0 +1,280 @@ +#!/usr/bin/env python3 +"""Build an audited ALOHA-only Stage-W manifest from the codec episode split. + +Every emitted episode has three synchronized cameras, an exactly reconstructable 14D drive-target +vector, and at least one complete ``10 context + 10 future`` latent window. A bounded +``--max-episodes-per-split`` mode exists only for smoke tests; its summary is marked incomplete and +the formal launcher rejects it. +""" + +from __future__ import annotations + +import argparse +import ctypes +import io +import json +import zipfile +from collections import Counter, defaultdict +from pathlib import Path +from typing import Any + +import h5py +import numpy as np +import torch + +from mira.data.robotwin_loader import RoboTwinEpisode, load_robotwin_manifest +from mira.data.robotwin_wam_schema import ( + CAMERA_PATHS, + RAW_COMPONENT_PATHS, + RAW_VECTOR_PATH, + WAMEpisode, + half_up_source_indices, + reconstruct_joint_vector, + sha256_file, + sha256_text, + write_jsonl_atomic, +) + + +def _set_process_name() -> None: + ctypes.CDLL(None).prctl(15, b"syncnet_core_m", 0, 0, 0) + + +def _scene_info(handle: zipfile.ZipFile, entry: RoboTwinEpisode) -> dict[str, Any]: + root = entry.member.split("/data/", 1)[0] + name = f"{root}/scene_info.json" + try: + payload = json.loads(handle.read(name)) + except (KeyError, json.JSONDecodeError): + return {} + value = payload.get(f"episode_{entry.episode}", {}) + return value.get("info", {}) if isinstance(value, dict) else {} + + +def _display_object(value: Any) -> str: + raw = str(value or "object").split("/", 1)[0] + raw = raw.split("_", 1)[-1] + return raw.replace("-", " ").replace("_", " ") + + +def _instruction(entry: RoboTwinEpisode, scene: dict[str, Any], catalog: dict[str, str]) -> str: + arm = str(scene.get("{a}", "appropriate")) + obj = _display_object(scene.get("{A}")) + template = catalog.get(entry.task) + if template is None: + # Even without an optional official template catalog, retain the per-episode grounding + # supplied by RoboTwin's scene_info instead of collapsing every episode to a task slug. + template = f"{entry.task.replace('_', ' ')} using the {{a}} to manipulate {{A}}" + text = template.replace("{a}", f"{arm} arm").replace("{A}", obj) + # The wrapper is the exact prompt form used by the audited Fast-WAM reference. + return f"A video recorded from a robot's point of view executing the following instruction: {text}" + + +class StreamingStats: + def __init__(self, dim: int) -> None: + self.count = 0 + self.sum = np.zeros(dim, dtype=np.float64) + self.sum_sq = np.zeros(dim, dtype=np.float64) + self.minimum = np.full(dim, np.inf) + self.maximum = np.full(dim, -np.inf) + + def update(self, values: np.ndarray) -> None: + values = values.astype(np.float64, copy=False) + self.count += values.shape[0] + self.sum += values.sum(axis=0) + self.sum_sq += np.square(values).sum(axis=0) + self.minimum = np.minimum(self.minimum, values.min(axis=0)) + self.maximum = np.maximum(self.maximum, values.max(axis=0)) + + def result(self) -> dict[str, Any]: + if self.count == 0: + raise ValueError("No training state values were audited") + mean = self.sum / self.count + variance = np.maximum(self.sum_sq / self.count - np.square(mean), 0) + return { + "semantics": "simulator_drive_target_not_measured_qpos", + "dimension_order": [ + "left_joint_0", "left_joint_1", "left_joint_2", "left_joint_3", + "left_joint_4", "left_joint_5", "left_gripper", + "right_joint_0", "right_joint_1", "right_joint_2", "right_joint_3", + "right_joint_4", "right_joint_5", "right_gripper", + ], + "count": self.count, + "mean": mean.tolist(), + "std": np.sqrt(variance).tolist(), + "minimum": self.minimum.tolist(), + "maximum": self.maximum.tolist(), + "normalization_std_floor": 1.0e-2, + "normalization_clip": 5.0, + } + + +def _inspect( + payload: bytes, + entry: RoboTwinEpisode, + split: str, + instruction: str, + stats: StreamingStats | None, + min_latents: int = 20, +) -> WAMEpisode: + with h5py.File(io.BytesIO(payload), "r") as episode: + required = [*CAMERA_PATHS, RAW_VECTOR_PATH, *RAW_COMPONENT_PATHS] + missing = [name for name in required if name not in episode] + if missing: + raise ValueError(f"missing fields {missing}") + lengths = {name: len(episode[name]) for name in required} + if len(set(lengths.values())) != 1: + raise ValueError(f"unsynchronized field lengths: {lengths}") + n_source = next(iter(lengths.values())) + source_indices = half_up_source_indices(n_source) + # Codec temporal stride is exactly two. Never synthesize a padded latent cell. + if source_indices.numel() % 2 and min_latents >= 20: + source_indices = source_indices[:-1] + n_latents = source_indices.numel() // 2 + if n_latents < min_latents: + raise ValueError(f"only {n_latents} codec latents; requested minimum {min_latents}") + + vector = torch.from_numpy(np.asarray(episode[RAW_VECTOR_PATH], dtype=np.float32)) + components = [torch.from_numpy(np.asarray(episode[path], dtype=np.float32)) for path in RAW_COMPONENT_PATHS] + rebuilt = reconstruct_joint_vector(components) + max_error = float((vector - rebuilt).abs().max()) + if max_error > 1.0e-6: + raise ValueError(f"joint_action/vector differs from components (max error {max_error})") + if not torch.isfinite(vector).all(): + raise ValueError("non-finite joint drive target") + if stats is not None: + stats.update(vector.index_select(0, source_indices.long()).numpy()) + + return WAMEpisode( + archive=entry.archive, + member=entry.member, + task=entry.task, + robot=entry.robot, + domain=entry.domain, + episode=entry.episode, + n_source_frames=n_source, + n_video20_frames=int(source_indices.numel()), + n_latents=int(n_latents), + instruction=instruction, + instruction_sha256=sha256_text(instruction), + episode_sha256=sha256_text(entry.key), + split=split, + ) + + +def _load_catalog(path: str | None) -> dict[str, str]: + if path is None: + return {} + value = json.loads(Path(path).read_text(encoding="utf-8")) + if not isinstance(value, dict) or not all(isinstance(k, str) and isinstance(v, str) for k, v in value.items()): + raise ValueError("instruction catalog must be a JSON object mapping task to template") + return value + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--dataset-root", required=True) + parser.add_argument("--train-manifest", required=True) + parser.add_argument("--val-manifest", required=True) + parser.add_argument("--output-dir", required=True) + parser.add_argument("--embodiment", default="aloha-agilex") + parser.add_argument("--instruction-catalog") + parser.add_argument("--max-episodes-per-split", type=int) + parser.add_argument("--min-latents", type=int, default=20, + help="Joint masked-tail training uses 1; legacy complete-window training requires 20") + args = parser.parse_args() + if args.min_latents < 1: + parser.error("--min-latents must be positive") + _set_process_name() + + root = Path(args.dataset_root).expanduser().resolve() + output = Path(args.output_dir).expanduser().resolve() + output.mkdir(parents=True, exist_ok=True) + catalog = _load_catalog(args.instruction_catalog) + source_paths = {"train": Path(args.train_manifest).resolve(), "val": Path(args.val_manifest).resolve()} + train_stats = StreamingStats(14) + emitted: dict[str, list[WAMEpisode]] = {"train": [], "val": []} + rejected: list[dict[str, Any]] = [] + + for split, source_path in source_paths.items(): + entries = load_robotwin_manifest(source_path, robots=[args.embodiment]) + if args.max_episodes_per_split is not None: + entries = entries[: args.max_episodes_per_split] + grouped: dict[str, list[RoboTwinEpisode]] = defaultdict(list) + for entry in entries: + grouped[entry.archive].append(entry) + for archive, archive_entries in sorted(grouped.items()): + with zipfile.ZipFile(root / archive) as handle: + for entry in archive_entries: + try: + scene = _scene_info(handle, entry) + instruction = _instruction(entry, scene, catalog) + item = _inspect( + handle.read(entry.member), + entry, + split, + instruction, + train_stats if split == "train" else None, + min_latents=args.min_latents, + ) + except (KeyError, OSError, ValueError, RuntimeError, zipfile.BadZipFile) as exc: + rejected.append({"split": split, "key": entry.key, "error": f"{type(exc).__name__}: {exc}"}) + continue + emitted[split].append(item) + + train_keys = {item.episode_sha256 for item in emitted["train"]} + val_keys = {item.episode_sha256 for item in emitted["val"]} + overlap = sorted(train_keys & val_keys) + if overlap: + raise RuntimeError(f"Episode-level train/val leakage: {overlap[:5]}") + + for split in ("train", "val"): + write_jsonl_atomic(output / f"{split}.jsonl", [item.to_dict() for item in emitted[split]]) + write_jsonl_atomic(output / "rejected.jsonl", rejected) + + stats_payload = train_stats.result() + stats_payload["train_manifest_sha256"] = sha256_file(output / "train.jsonl") + stats_tmp = output / ".dataset_stats.json.tmp" + stats_tmp.write_text(json.dumps(stats_payload, indent=2) + "\n", encoding="utf-8") + stats_tmp.replace(output / "dataset_stats.json") + + distribution = {} + for split, rows in emitted.items(): + distribution[split] = { + "tasks": Counter(row.task for row in rows), + "domains": Counter(row.domain for row in rows), + "task_domain": Counter(f"{row.task}|{row.domain}" for row in rows), + } + summary = { + "format_version": 1, + "min_latents": args.min_latents, + "complete_audit": args.max_episodes_per_split is None, + "bounded_smoke_manifest": args.max_episodes_per_split is not None, + "embodiment": args.embodiment, + "state_semantics": "simulator_drive_target_not_measured_qpos", + "action_semantics": "next_20hz_drive_target", + "source_fps": 30, + "video_fps": 20, + "latent_fps": 10, + "view_order": ["left", "global", "right"], + "emitted": {split: len(rows) for split, rows in emitted.items()}, + "rejected": len(rejected), + "split_overlap": 0, + "source_manifests": {k: str(v) for k, v in source_paths.items()}, + "source_manifest_sha256": {k: sha256_file(v) for k, v in source_paths.items()}, + "output_manifest_sha256": { + split: sha256_file(output / f"{split}.jsonl") for split in ("train", "val") + }, + "instruction_catalog": str(Path(args.instruction_catalog).resolve()) if args.instruction_catalog else None, + "instruction_fallback": "task slug plus per-episode scene arm/object", + "distribution": distribution, + } + summary_path = output / "summary.json" + temporary = output / ".summary.json.tmp" + temporary.write_text(json.dumps(summary, indent=2, ensure_ascii=False, default=dict) + "\n", encoding="utf-8") + temporary.replace(summary_path) + print(json.dumps(summary, indent=2, ensure_ascii=False, default=dict)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/eval_action_head_offline.py b/release-20261107/source/workspace_joint/mira/scripts/eval_action_head_offline.py new file mode 100644 index 0000000000000000000000000000000000000000..04630a6eafd3e61fed6302fc0164ae1d206cd392 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/eval_action_head_offline.py @@ -0,0 +1,403 @@ +#!/usr/bin/env python3 +"""Paired fixed-noise offline diagnostics for an Action Head checkpoint.""" + +from __future__ import annotations + +import ctypes +import hashlib +import json +import logging +from contextlib import nullcontext +from pathlib import Path +from typing import Any + +import hydra +import numpy as np +import torch +import torch.distributed as dist +import torch.distributed.checkpoint as dcp +import torch.nn.functional as F +from omegaconf import DictConfig, OmegaConf +from torch import Tensor +from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( + CheckpointImpl, + checkpoint_wrapper, +) +from torch.distributed.checkpoint.state_dict import ( + get_model_state_dict, + set_model_state_dict, +) +from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard + +from mira.action.config import ActionHeadConfig +from mira.action.data import RoboTwinActionBatch, RoboTwinActionDataset, collate_robotwin_action +from mira.action.flow_matching import ( + masked_action_flow_loss, + sample_action_euler, + sample_flow_batch, +) +from mira.action.joint_action_flow import JointBimanualActionFlow +from mira.action.visualization import save_action_trajectory_case +from mira.data.robotwin_wam_schema import sha256_file +from mira.training.distributed import set_up_distributed +from mira.training.ema import ModelEMA + +logger = logging.getLogger(__name__) + + +def _set_process_name(rank: int) -> None: + ctypes.CDLL(None).prctl(15, f"syncnet_act_e{rank}".encode()[:15], 0, 0, 0) + + +def _conditions( + batch: RoboTwinActionBatch, + future: Tensor, + drop: Tensor, +) -> dict[str, Tensor]: + return { + "current_latent": batch.current_latent, + "future_latent": future, + "joint_target_history": batch.joint_target_history, + "action_history": batch.action_history, + "history_valid": batch.history_valid, + "text_hidden": batch.text_hidden, + "text_mask": batch.text_mask, + "future_drop_mask": drop, + } + + +def _seed(checkpoint_step: int, window_id: str) -> int: + payload = f"action-offline:{checkpoint_step}:{window_id}:2026" + return int.from_bytes(hashlib.sha256(payload.encode()).digest()[:8], "big") + + +def _bootstrap_improvement(values: np.ndarray, seed: int = 2026) -> dict[str, Any]: + if not len(values): + return {"mean": float("nan"), "ci95": [float("nan"), float("nan")]} + rng = np.random.default_rng(seed) + choices = rng.integers(0, len(values), size=(10_000, len(values))) + means = values[choices].mean(axis=1) + return { + "mean": float(values.mean()), + "ci95": [float(value) for value in np.quantile(means, [0.025, 0.975])], + } + + +def _partner_indices(dataset: RoboTwinActionDataset) -> tuple[list[int], list[int]]: + same_task = [] + cross_task = [] + for index, row in enumerate(dataset.rows): + same = next( + ( + other + for other, candidate in enumerate(dataset.rows) + if other != index and candidate["task"] == row["task"] + ), + index, + ) + cross = next( + other + for other, candidate in enumerate(dataset.rows) + if candidate["task"] != row["task"] + ) + same_task.append(same) + cross_task.append(cross) + return same_task, cross_task + + +def _load_model( + checkpoint: Path, + device: torch.device, + branch: str, +) -> tuple[JointBimanualActionFlow, ModelEMA, dict[str, Any]]: + metadata = json.loads((checkpoint / "trainer_state.json").read_text(encoding="utf-8")) + config = ActionHeadConfig.model_validate(metadata["resolved_config"]["model"]) + model = JointBimanualActionFlow(config).to(device) + policy = MixedPrecisionPolicy( + param_dtype=torch.bfloat16, + reduce_dtype=torch.float32, + output_dtype=torch.bfloat16, + ) + if config.activation_checkpointing: + model.external_activation_checkpointing = True + for index, block in enumerate(model.blocks): + model.blocks[index] = checkpoint_wrapper( + block, + checkpoint_impl=CheckpointImpl.NO_REENTRANT, + preserve_rng_state=True, + ) + for block in model.blocks: + fully_shard(block, mp_policy=policy, reshard_after_forward=True) + fully_shard(model, mp_policy=policy, reshard_after_forward=True) + ema = ModelEMA( + model, + decay=float(metadata["resolved_config"]["training"]["optimizer"]["ema_decay"]), + unbias=False, + ) + state = {"model": get_model_state_dict(model), "ema": ema.state_dict()} + dcp.load(state, checkpoint_id=checkpoint / "distributed") + set_model_state_dict(model, state["model"]) + ema.load_state_dict(state["ema"]) + if branch not in {"online", "ema"}: + raise ValueError(f"Unsupported Action branch: {branch}") + return model, ema, metadata + + +def _verify_artifacts(cfg: DictConfig, metadata: dict[str, Any]) -> None: + expected = metadata["artifact_identity"] + actual = { + "val_manifest_sha256": sha256_file(cfg.data.val_manifest), + "action_stats_sha256": sha256_file(cfg.data.action_stats), + } + if "val_future_metadata_sha256" in expected: + actual["val_future_metadata_sha256"] = sha256_file( + Path(cfg.data.val_future_cache) / "metadata.json" + ) + for name, value in actual.items(): + if value != expected[name]: + raise ValueError( + f"Offline evaluation artifact mismatch for {name}: " + f"checkpoint={expected[name]} actual={value}" + ) + future_metadata = json.loads( + (Path(cfg.data.val_future_cache) / "metadata.json").read_text(encoding="utf-8") + ) + if future_metadata["world_state_dict_sha256"] != expected["world_state_dict_sha256"]: + raise ValueError("Offline future cache was generated by a different World branch") + + +@hydra.main( + version_base=None, + config_path="../configs", + config_name="eval_action_head_offline", +) +def main(cfg: DictConfig) -> None: + settings = set_up_distributed() + rank, world_size = settings.rank, settings.world_size + _set_process_name(rank) + if world_size != int(cfg.distributed.expected_world_size): + raise ValueError( + f"Expected {cfg.distributed.expected_world_size} evaluation ranks, got {world_size}" + ) + device = torch.device("cuda", settings.device) + torch.manual_seed(int(cfg.seed) + rank) + torch.cuda.manual_seed(int(cfg.seed) + rank) + logging.basicConfig( + level=logging.INFO if rank == 0 else logging.WARNING, + format=f"[%(asctime)s][%(levelname)s][rank={rank}] %(message)s", + ) + checkpoint = Path(cfg.checkpoint).expanduser().resolve() + model, ema, metadata = _load_model(checkpoint, device, str(cfg.branch)) + _verify_artifacts(cfg, metadata) + dataset = RoboTwinActionDataset( + cfg.data.val_manifest, + state_stats=cfg.data.state_stats, + action_stats=cfg.data.action_stats, + future_cache=cfg.data.val_future_cache, + latent_mean=float(cfg.data.latent_mean), + latent_std=float(cfg.data.latent_std), + require_real_text=True, + ) + same_partner, cross_partner = _partner_indices(dataset) + count = min(int(cfg.cases), len(dataset)) + selected = np.linspace(0, len(dataset) - 1, count, dtype=np.int64).tolist() + local_indices = selected[rank::world_size] + stats = json.loads(Path(cfg.data.action_stats).read_text(encoding="utf-8")) + action_mean = torch.tensor(stats["mean"], dtype=torch.float32, device=device) + action_std = torch.tensor(stats["std"], dtype=torch.float32, device=device) + output = Path(cfg.output_dir).expanduser().resolve() + if rank == 0: + output.mkdir(parents=True, exist_ok=True) + (output / "resolved_config.yaml").write_text( + OmegaConf.to_yaml(cfg, resolve=True), + encoding="utf-8", + ) + dist.barrier() + + rows: list[dict[str, Any]] = [] + model.eval() + branch_context = ema.average_parameters() if str(cfg.branch) == "ema" else nullcontext() + with branch_context, torch.inference_mode(): + for local_case, dataset_index in enumerate(local_indices): + sample = dataset[dataset_index] + batch, sample_metadata = collate_robotwin_action([sample]) + batch = batch.to(device) + meta = sample_metadata[0] + current = F.adaptive_avg_pool2d( + batch.current_latent.reshape(3, 32, 9, 12), + (3, 4), + ).reshape(1, 3, 1, 32, 3, 4) + persistence = current.expand(-1, -1, 10, -1, -1, -1) + same = dataset[same_partner[dataset_index]]["future_pred_pooled"][None].to(device) + cross = dataset[cross_partner[dataset_index]]["future_pred_pooled"][None].to(device) + predicted = batch.future_pred_pooled + interventions: dict[str, tuple[Tensor, Tensor]] = { + "correct_pred10": (predicted, torch.zeros(1, dtype=torch.bool, device=device)), + "gt_future": (batch.future_gt_pooled, torch.zeros(1, dtype=torch.bool, device=device)), + "null_future": (predicted, torch.ones(1, dtype=torch.bool, device=device)), + "same_task_shuffle": (same, torch.zeros(1, dtype=torch.bool, device=device)), + "cross_task_shuffle": (cross, torch.zeros(1, dtype=torch.bool, device=device)), + "reverse_time": (predicted.flip(2), torch.zeros(1, dtype=torch.bool, device=device)), + "persistence": (persistence, torch.zeros(1, dtype=torch.bool, device=device)), + } + for view, view_name in enumerate(("left", "global", "right")): + dropped = predicted.clone() + dropped[:, view] = 0 + interventions[f"zero_{view_name}_view"] = ( + dropped, + torch.zeros(1, dtype=torch.bool, device=device), + ) + + case_predictions: dict[str, Tensor] = {} + case_attention: dict[str, dict[str, Tensor]] = {} + seed = _seed(int(metadata["completed_steps"]), str(meta["window_id"])) + for condition, (future, drop) in interventions.items(): + generator = torch.Generator(device=device).manual_seed(seed) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + prediction, attention = sample_action_euler( + model, + conditions=_conditions(batch, future, drop), + batch_size=1, + steps=int(cfg.action_steps), + generator=generator, + return_attention=True, + ) + case_predictions[condition] = prediction.float() + case_attention[condition] = attention + + flow_generator = torch.Generator(device=device).manual_seed(seed + 1) + flow = sample_flow_batch( + batch.action_target, + alpha=1.5, + scale=0.999, + generator=flow_generator, + ) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + flow_output = model( + flow.noisy_action, + flow.flow_time, + **_conditions( + batch, + batch.future_pred_pooled, + torch.zeros(1, dtype=torch.bool, device=device), + ), + ) + flow_loss, _ = masked_action_flow_loss( + flow_output["velocity"], + flow.target_velocity, + batch.action_valid, + ) + target = batch.action_target.float() + correct = case_predictions["correct_pred10"] + record: dict[str, Any] = { + "dataset_index": dataset_index, + "window_id": meta["window_id"], + "task": meta["task"], + "domain": meta["domain"], + "flow_loss": float(flow_loss), + "conditions": {}, + } + for condition, prediction in case_predictions.items(): + error = (prediction - target).abs() + delta = prediction - correct + record["conditions"][condition] = { + "mae_full_normalized": float(error.mean()), + "mae_first10_normalized": float(error[:, :10].mean()), + "endpoint_mae_raw": float( + ((prediction[:, -1] - target[:, -1]).abs() * action_std).mean() + ), + "delta_from_correct_l2": float(delta.square().mean().sqrt()), + "attention_current_mass": float( + case_attention[condition]["attention/current_mass"] + ), + "attention_future_mass": float( + case_attention[condition]["attention/future_mass"] + ), + } + for baseline, value in ( + ("repeat_last", batch.repeat_last_baseline), + ("per_task_mean", batch.per_task_mean_baseline), + ): + error = (value.float() - target).abs() + record["conditions"][baseline] = { + "mae_full_normalized": float(error.mean()), + "mae_first10_normalized": float(error[:, :10].mean()), + "endpoint_mae_raw": float( + ((value[:, -1] - target[:, -1]).abs() * action_std).mean() + ), + } + rows.append(record) + + if rank == 0 and local_case < int(cfg.visualization_cases): + for condition in ("correct_pred10", "null_future", "cross_task_shuffle"): + save_action_trajectory_case( + output / "trajectories", + case_index=local_case, + prediction=case_predictions[condition][0], + target=target[0], + action_mean=action_mean, + action_std=action_std, + metadata=meta, + attention=case_attention[condition], + condition=condition, + ) + + gathered: list[list[dict[str, Any]] | None] = [None] * world_size + dist.all_gather_object(gathered, rows) + if rank == 0: + combined = sorted( + [row for shard in gathered for row in (shard or [])], + key=lambda row: int(row["dataset_index"]), + ) + condition_names = sorted(combined[0]["conditions"]) + summary: dict[str, Any] = { + "format_version": 1, + "checkpoint": str(checkpoint), + "checkpoint_step": int(metadata["completed_steps"]), + "branch": str(cfg.branch), + "cases": len(combined), + "action_steps": int(cfg.action_steps), + "best_of_k": 1, + "same_initial_noise_across_interventions": True, + "flow_loss": float(np.mean([row["flow_loss"] for row in combined])), + "conditions": {}, + "paired_improvement_over_intervention": {}, + } + correct = np.asarray( + [ + row["conditions"]["correct_pred10"]["mae_first10_normalized"] + for row in combined + ] + ) + for condition in condition_names: + values = np.asarray( + [ + row["conditions"][condition]["mae_first10_normalized"] + for row in combined + ] + ) + summary["conditions"][condition] = { + metric: float( + np.mean([row["conditions"][condition][metric] for row in combined]) + ) + for metric in combined[0]["conditions"][condition] + } + if condition != "correct_pred10": + summary["paired_improvement_over_intervention"][condition] = ( + _bootstrap_improvement(values - correct) + ) + (output / "per_case.json").write_text( + json.dumps(combined, indent=2) + "\n", + encoding="utf-8", + ) + (output / "summary.json").write_text( + json.dumps(summary, indent=2) + "\n", + encoding="utf-8", + ) + logger.info("Offline Action evaluation: %s", json.dumps(summary)) + dist.barrier() + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/eval_action_v6_checkpoint.py b/release-20261107/source/workspace_joint/mira/scripts/eval_action_v6_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..76c62ce73717077767cf3918e702e8ec46f47847 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/eval_action_v6_checkpoint.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Deterministic multi-GPU offline probe for an Action-v6 EMA checkpoint. + +This reuses the training validator and its fixed validation windows/noise. It +does not train, mutate, or resave the checkpoint. +""" + +from __future__ import annotations + +import argparse +import copy +import json +from pathlib import Path + +import torch +import torch.distributed as dist + +from mira.data.world_v6 import set_world_v6_process_name +from mira.inference.robotwin_v6_runtime import _load_model_and_ema +from mira.training.action_v6.config import ActionV6RunConfig +from mira.training.action_v6.factory import build_action_stage +from mira.training.action_v6.train import _dataset, _validate +from mira.training.distributed import set_up_distributed + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--output", required=True) + args = parser.parse_args() + + settings = set_up_distributed() + rank, world_size = settings.rank, settings.world_size + if world_size != 8: + raise RuntimeError(f"the formal offline probe requires 8 ranks, got {world_size}") + device = torch.device("cuda", settings.device) + set_world_v6_process_name(f"tagshotx_action_diag_r{rank}") + + checkpoint = Path(args.checkpoint).expanduser().resolve() + output = Path(args.output).expanduser().resolve() + metadata = json.loads((checkpoint / "trainer_state.json").read_text(encoding="utf-8")) + resolved = copy.deepcopy(metadata["resolved_config"]) + # Step 10k predates the explicit protocol fields that were added before + # the audited compressed continuation. Restore their original semantics + # for read-only comparison; later checkpoints already carry these fields. + resolved["training"].setdefault("protocol", "preregistered_100k") + resolved["checkpoint"].setdefault("resume_from", None) + resolved["validation"].setdefault("enabled", True) + config = ActionV6RunConfig.model_validate(resolved) + # The training validator intentionally limits a non-training invocation to + # fixed light_batches while still computing the full sampled-action metric + # family. This is a diagnostic probe, not an exhaustive checkpoint score. + eval_config = config.model_copy( + update={"runtime": config.runtime.model_copy(update={"phase": "eval"})} + ) + + if rank == 0: + output.mkdir(parents=True, exist_ok=True) + dist.barrier() + + torch.manual_seed(eval_config.validation.fixed_seed) + torch.cuda.manual_seed(eval_config.validation.fixed_seed) + torch.backends.cuda.matmul.allow_tf32 = True + stage = build_action_stage(eval_config).to(device).eval() + load_info = _load_model_and_ema(stage, checkpoint) + validation = _dataset(eval_config, "val", cache=True) + metrics, cases = _validate( + stage, + validation, + eval_config, + device=device, + rank=rank, + world_size=world_size, + completed=int(metadata["completed_steps"]), + branch="ema", + full=True, + output=output, + ) + if rank == 0: + evaluated_windows = min( + len(validation), + eval_config.validation.light_batches + * world_size + * eval_config.training.micro_batch_per_gpu, + ) + result = { + "status": "complete", + "kind": "fixed_light_sampled_action_probe", + "checkpoint": str(checkpoint), + "checkpoint_step": int(metadata["completed_steps"]), + "branch": "ema", + "checkpoint_fingerprint": load_info["checkpoint_fingerprint"], + "validation_windows_total": len(validation), + "validation_windows_evaluated": evaluated_windows, + "fixed_seed": eval_config.validation.fixed_seed, + "metrics": metrics, + "saved_cases": [str(path) for path in cases], + } + (output / "offline_probe.json").write_text( + json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + print(json.dumps(result, indent=2, sort_keys=True), flush=True) + dist.barrier() + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/eval_bihub_wam_offline.py b/release-20261107/source/workspace_joint/mira/scripts/eval_bihub_wam_offline.py new file mode 100644 index 0000000000000000000000000000000000000000..4aefc6c71d17f235949837c101513317f3e47c47 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/eval_bihub_wam_offline.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Audit saved fixed-case Stage-W rollouts against GT and persistence, optionally decode MP4s.""" + +from __future__ import annotations + +import argparse +import ctypes +import json +from pathlib import Path + +import torch + +from mira.codec.codec_model import VideoCodec +from mira.inference.bihub_world_rollout import ( + decode_comparison_video, + latent_rollout_metrics, + summarize_rollout_metrics, +) +from mira.training.visualization import write_video_ffmpeg + + +def _select(root: Path, latest_only: bool) -> list[Path]: + files = sorted(root.glob("case-*/step-*.pth")) + if not latest_only: + return files + latest: dict[str, Path] = {} + for path in files: + latest[path.parent.name] = path + return sorted(latest.values()) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--case-root", required=True) + parser.add_argument("--output-dir", required=True) + parser.add_argument("--codec-checkpoint") + parser.add_argument("--decode-missing", action="store_true") + parser.add_argument("--latest-only", action="store_true") + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--fps", type=float, default=20) + args = parser.parse_args() + ctypes.CDLL(None).prctl(15, b"syncnet_core_e", 0, 0, 0) + + root = Path(args.case_root).expanduser().resolve() + output = Path(args.output_dir).expanduser().resolve() + output.mkdir(parents=True, exist_ok=True) + files = _select(root, args.latest_only) + if not files: + raise FileNotFoundError(f"No case-*/step-*.pth artifacts under {root}") + if args.decode_missing and not args.codec_checkpoint: + raise ValueError("--decode-missing requires --codec-checkpoint") + + decoder = None + device = torch.device(args.device) + rows: list[dict] = [] + for path in files: + value = torch.load(path, map_location="cpu", weights_only=False) + metrics = latent_rollout_metrics( + value["context_raw"], value["target_raw"], value["prediction_raw"] + ) + row = { + "case": path.parent.name, + "step": int(path.stem.split("-", 1)[1]), + "artifact": str(path), + "instruction": value.get("metadata", {}).get("instruction"), + **metrics, + } + rows.append(row) + video_path = output / f"{path.parent.name}-{path.stem}.mp4" + if args.decode_missing and not video_path.exists(): + if decoder is None: + codec = VideoCodec.load_from_checkpoint(args.codec_checkpoint, device="cpu") + decoder = codec.decoder.eval().requires_grad_(False).to(device) + del codec + video = decode_comparison_video( + decoder, + value["context_raw"], + value["target_raw"], + value["prediction_raw"], + device=device, + ) + temporary = video_path.with_name(f".{video_path.name}.tmp.mp4") + write_video_ffmpeg(temporary, video, fps=args.fps, preset="fast") + temporary.replace(video_path) + + metrics_tmp = output / ".metrics.jsonl.tmp" + with metrics_tmp.open("w", encoding="utf-8") as handle: + for row in rows: + handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n") + metrics_tmp.replace(output / "metrics.jsonl") + summary = summarize_rollout_metrics(rows) + summary["source_root"] = str(root) + summary["decoded"] = bool(args.decode_missing) + summary_tmp = output / ".summary.json.tmp" + summary_tmp.write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + summary_tmp.replace(output / "summary.json") + print(json.dumps(summary, indent=2, ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/eval_world_model_offline.py b/release-20261107/source/workspace_joint/mira/scripts/eval_world_model_offline.py new file mode 100644 index 0000000000000000000000000000000000000000..3c80d210d3d0e550c5c6347e572df13592fc8b61 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/eval_world_model_offline.py @@ -0,0 +1,364 @@ +"""Run the world-model training-time evals offline from a saved checkpoint. + +This reproduces, standalone, the two evaluations that ``train_world_model.py`` runs periodically: + + 1. Validation loss (mirrors ``run_validation``): diffusion loss on the test set. + 2. World-model metrics (mirrors the metrics loop): DINO / latent drift + Frechet DINO/Inception + curves + per-frame PSNR/LPIPS/SSIM, with optional rollout viz clips saved to disk. + +The dataset / model config is read from the ``world_model_config.yaml`` saved alongside the +checkpoint, so the eval matches the training run; how the metrics eval is run comes from +``configs/eval_world_model.yaml``. Single-process (no torchrun); video-only (no audio metrics). + +The checkpoint may be a local path or a W&B run -- anything ``resolve_checkpoint`` accepts. Usage:: + + python scripts/eval_world_model_offline.py /path/to/checkpoint-1000/checkpoint.pth + python scripts/eval_world_model_offline.py --num-samples 512 --skip-validation + python scripts/eval_world_model_offline.py --viz 8 --output-dir out --no-compile +""" + +from __future__ import annotations + +import argparse +import logging +import time +from collections import defaultdict +from collections.abc import Iterator +from pathlib import Path +from typing import TYPE_CHECKING, Any + +import torch + +from mira.data.batch import VideoActionBatch +from mira.inference.rollout import measure_rollout_speed +from mira.training.metrics.distributed_metric import DistributedMetric +from mira.training.metrics.world_model_metrics import WorldModelMetricsConfig +from mira.world_model.config import WorldModelInferenceConfig + +if TYPE_CHECKING: + # Single- and multi-player models are duck-typed under LatentWorldModel (the wrapper exposes the + # same forward/inference/visualize/decode_to_video surface); n_players is read with getattr. + from mira.world_model.latent_world_model import LatentWorldModel + +logger = logging.getLogger(__name__) + +CONFIG_FILENAME = "world_model_config.yaml" +EVAL_CONFIG = Path(__file__).resolve().parents[1] / "configs" / "eval_world_model.yaml" +SPEED_BENCH_FRAMES = 32 + + +def _autocast(device: torch.device | int | str): + """bfloat16 autocast on CUDA, a no-op elsewhere (so the eval pieces run on CPU too).""" + from contextlib import nullcontext + + if torch.cuda.is_available(): + return torch.autocast(device_type="cuda", dtype=torch.bfloat16) + return nullcontext() + + +def load_run_config(checkpoint_path: Path): + """Load the training run's config saved alongside the checkpoint (two dirs above the .pth).""" + from omegaconf import OmegaConf # noqa: PLC0415 + + config_path = checkpoint_path.parents[1] / CONFIG_FILENAME + if not config_path.exists(): + raise FileNotFoundError( + f"Could not find {CONFIG_FILENAME} at {config_path}. It is expected two directories " + "above the checkpoint (the training output dir)." + ) + return OmegaConf.load(config_path) + + +def load_eval_metrics_config( + *, + num_samples: int | None = None, + no_compile: bool = False, + inference: WorldModelInferenceConfig | None = None, +) -> WorldModelMetricsConfig: + """Build the eval :class:`WorldModelMetricsConfig` from ``configs/eval_world_model.yaml``. + + CLI overrides (sample count, compile, inference knobs) are applied on top. + """ + from hydra.utils import instantiate # noqa: PLC0415 + from omegaconf import OmegaConf # noqa: PLC0415 + + raw = OmegaConf.load(EVAL_CONFIG) + config: WorldModelMetricsConfig = instantiate(raw.world_model_metrics) + if num_samples is not None: + config.num_samples = num_samples + if no_compile: + config.compile = False + if inference is not None: + config.inference = inference + return config + + +def run_validation_loss( + model: "LatentWorldModel", + val_iter: Iterator[tuple[VideoActionBatch, Any]], + device: torch.device | int | str, + n_batches: int, +) -> dict[str, float]: + """Mirror ``train_world_model.run_validation``: average the forward diffusion loss on the test set.""" + import tqdm # noqa: PLC0415 + + model.eval() + metric_trackers: dict[str, DistributedMetric] = defaultdict(lambda: DistributedMetric(device=device)) + t1 = time.time() + for _ in tqdm.trange(max(1, n_batches), desc="Validation loss"): + batch, _ = next(val_iter) + batch = batch.to(device) + with torch.no_grad(), _autocast(device): + for k, v in model(batch).items(): + metric_trackers[k].update(v) + + metrics = {k: tracker.compute_and_reset().item() for k, tracker in metric_trackers.items()} + logger.info("Validation loss took %.1fs over %d batches", time.time() - t1, max(1, n_batches)) + return metrics + + +def save_viz_videos( + model: "LatentWorldModel", + inference_outputs, + metadata: list, + output_dir: Path, + sample_idx: int, +) -> None: + """Render one rollout to disk as a predicted-over-ground-truth grid (video-only, no audio).""" + from mira.training.visualization import ( # noqa: PLC0415 + draw_text_on_first_frame, + videos_to_grid, + write_video_ffmpeg, + ) + + n_players = getattr(model, "n_players", 1) + captions = [f"{m.match_id}:{m.perspective}" for m in metadata] + grouped = [" + ".join(captions[i : i + n_players]) for i in range(0, len(captions), n_players)] + + viz_video = model.visualize(inference_outputs)["viz_video"] + viz_video = draw_text_on_first_frame(viz_video, grouped) + + output_dir.mkdir(parents=True, exist_ok=True) + write_video_ffmpeg( + output_dir / f"viz_{sample_idx:03d}.mp4", + videos_to_grid(viz_video.cpu()), + fps=model.config.video.fps, + ) + + +def run_world_model_metrics( + model: "LatentWorldModel", + metrics_iter: Iterator[tuple[VideoActionBatch, list]], + device: torch.device | int | str, + *, + wm_metrics_config: WorldModelMetricsConfig, + num_eval_batches: int, + num_viz: int = 0, + output_dir: Path | None = None, + compile_models: bool = False, +) -> dict[str, float]: + """Mirror the training metrics loop: unroll, score, optionally save viz, then aggregate.""" + import tqdm # noqa: PLC0415 + + from mira.training.metrics.world_model_metrics import WorldModelMetrics # noqa: PLC0415 + + if compile_models and not getattr(model, "_offline_eval_compiled", False): + model.world_model.compile() + model.decode_to_video = torch.compile(model.decode_to_video) + # Guard so the sweep doesn't re-wrap decode on every call; setattr sidesteps nn.Module's + # typed __setattr__ (which only accepts Tensor/Module values). + setattr(model, "_offline_eval_compiled", True) + + wm_metrics = WorldModelMetrics(config=wm_metrics_config, iter_dataloader=metrics_iter, device=device) + model.eval() + t_start = time.time() + for batch_idx in tqdm.trange(num_eval_batches, desc="World model metrics"): + inference_outputs, metadata = wm_metrics.process_batch(model) + if batch_idx < num_viz and output_dir is not None: + save_viz_videos(model, inference_outputs, metadata, output_dir, batch_idx) + + scalar_result, _frechet_curves = wm_metrics.compute() + elapsed = time.time() - t_start + logger.info("World model metrics took %.1fs over %d batches", elapsed, num_eval_batches) + if num_viz > 0 and output_dir is not None: + logger.info("Saved %d viz clip(s) to %s", min(num_viz, num_eval_batches), output_dir) + return {k: float(v) for k, v in scalar_result.items()} + + +def measure_denoise_speed( + model: "LatentWorldModel", + batch: VideoActionBatch, + config: WorldModelInferenceConfig | None = None, + n_frames: int = SPEED_BENCH_FRAMES, +) -> dict[str, float]: + """Time the pure denoising rollout (no decode / metrics) at batch size 1, after a short warmup.""" + config = config or WorldModelInferenceConfig() + with torch.no_grad(), _autocast(model.device): + measure_rollout_speed(model, batch, config, n_frames=min(4, n_frames)) # warmup + return measure_rollout_speed(model, batch, config, n_frames=n_frames) + + +def _frame_size(cfg) -> tuple[int, int] | None: + fs = cfg.dataset.get("frame_size") + return tuple(fs) if fs is not None else None # type: ignore[return-value] + + +def _build_loader(cfg, model: "LatentWorldModel", *, clip_len: int, batch_size: int, seed: int): + """Build a held-out eval loader from the checkpoint's dataset config (fixed seed, no replays).""" + from mira.data.training_loader import create_loader # noqa: PLC0415 + + n_players = getattr(model, "n_players", 1) + return create_loader( + index_path=cfg.dataset.test_index, + clip_len=clip_len, + target_fps=model.config.video.fps, + action_fps=model.config.actions.target_fps, + n_players=n_players, + batch_size=batch_size, + num_workers=cfg.dataloader.num_workers, + shuffle_buffer_size=cfg.dataloader.shuffle_buffer_size, + frame_size=_frame_size(cfg), + valid_keys=list(model.config.actions.valid_keys), + seed=seed, + exclude_replays=True, + infinite=True, + ) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("checkpoint", type=str, help="Checkpoint path or W&B run URL.") + parser.add_argument("--num-samples", type=int, default=None, help="World-model-metrics samples.") + parser.add_argument("--val-n-samples", type=int, default=None, help="Validation-loss samples.") + parser.add_argument("--skip-validation", action="store_true", help="Skip the validation-loss eval.") + parser.add_argument("--skip-metrics", action="store_true", help="Skip the world-model-metrics eval.") + parser.add_argument("--viz", type=int, default=0, metavar="N", help="Render N rollout viz clips.") + parser.add_argument( + "--output-dir", + type=Path, + default=None, + help="Where to write viz clips (default: /offline_eval).", + ) + parser.add_argument("--no-compile", action="store_true", help="Disable torch.compile.") + parser.add_argument( + "--n-diffusion-steps", type=int, default=None, help="Override rollout diffusion steps." + ) + parser.add_argument("--schedule-type", type=str, default=None, choices=["linear", "linear_quadratic"]) + parser.add_argument( + "--noise-level", + type=lambda s: None if s.lower() == "none" else float(s), + default=argparse.SUPPRESS, + help="kv-cache noise level; 'none' merges the cache update into the last diffusion step.", + ) + return parser.parse_args() + + +def _inference_overrides( + args_dict: dict[str, Any], base: WorldModelInferenceConfig +) -> WorldModelInferenceConfig: + """Apply the CLI rollout knobs onto the eval config's inference defaults (only those provided).""" + updates: dict[str, Any] = {} + if args_dict.get("n_diffusion_steps") is not None: + updates["n_diffusion_steps"] = args_dict["n_diffusion_steps"] + if args_dict.get("schedule_type") is not None: + updates["schedule_type"] = args_dict["schedule_type"] + if "noise_level" in args_dict: # argparse.SUPPRESS: present only when the flag was passed + updates["noise_level"] = args_dict["noise_level"] + return base.model_copy(update=updates) if updates else base + + +def main() -> None: + logging.basicConfig(level=logging.INFO, format="%(message)s") + args = parse_args() + args_dict = vars(args) # so `in args` works for the SUPPRESS-defaulted noise_level + + from mira.inference.loading import load_world_model # noqa: PLC0415 + from mira.training.checkpoints import resolve_checkpoint # noqa: PLC0415 + + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + checkpoint = resolve_checkpoint(args.checkpoint).resolve() + cfg = load_run_config(checkpoint) + output_dir = args.output_dir or (checkpoint.parent / "offline_eval") + + model, _ = load_world_model(checkpoint, device=device) + model = model.eval() + logger.info("Loaded world model from %s on %s", checkpoint, device) + + eval_config = load_eval_metrics_config( + num_samples=args.num_samples, + no_compile=args.no_compile, + ) + eval_config.inference = _inference_overrides(args_dict, eval_config.inference) + compile_models = (not args.no_compile) and bool(cfg.run.get("compile")) + + results: dict[str, float] = {} + + if not args.skip_validation: + batch_size = (cfg.validation.batch_size or cfg.run.batch_size) * getattr(model, "n_players", 1) + n_samples = args.val_n_samples if args.val_n_samples is not None else cfg.validation.val_n_samples + val_loader = _build_loader( + cfg, model, clip_len=model.config.video.timesteps * 2, batch_size=batch_size, seed=37 + ) + results |= { + f"test/{k}": v + for k, v in run_validation_loss( + model, iter(val_loader), device, n_batches=max(1, n_samples // batch_size) + ).items() + } + + if not args.skip_metrics: + # Apply the eval's context override before deriving the clip length, so the loader, the + # rollout, and the metric indexing all agree on n_context_frames (see set_inference_context). + if eval_config.n_context_frames is not None: + model.set_inference_context(eval_config.n_context_frames) + stride = eval_config.eval_temporal_downsampling or model.temporal_downsampling + metrics_loader = _build_loader( + cfg, + model, + clip_len=model.config.n_context_frames + eval_config.num_unrolled_frames * stride, + batch_size=eval_config.per_device_batch_size, + seed=38, + ) + num_eval_batches = max(1, eval_config.num_samples // eval_config.per_device_batch_size) + results |= { + f"metrics/{k}": v + for k, v in run_world_model_metrics( + model, + iter(metrics_loader), + device, + wm_metrics_config=eval_config, + num_eval_batches=num_eval_batches, + num_viz=args.viz, + output_dir=output_dir, + compile_models=compile_models, + ).items() + } + # Pure denoising speed (bs=1, no decode/metrics). + try: + speed_batch = _build_loader( + cfg, + model, + clip_len=model.config.n_context_frames + SPEED_BENCH_FRAMES * model.temporal_downsampling, + batch_size=1, + seed=39, + ) + batch, _ = next(iter(speed_batch)) + batch = batch.to(device) + model.codec.preprocess_batch(batch) + results |= { + f"metrics/{k}": v + for k, v in measure_denoise_speed(model, batch, eval_config.inference).items() + } + except Exception: + logger.exception("Denoise-speed measurement failed; skipping it.") + + logger.info("%s", "=" * 60) + logger.info("Offline eval results:") + for k, v in results.items(): + logger.info(" %s: %.4f", k, v) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/export_joint_world_action.py b/release-20261107/source/workspace_joint/mira/scripts/export_joint_world_action.py new file mode 100644 index 0000000000000000000000000000000000000000..be25832a1ce93973a26870422358c6dee562d51c --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/export_joint_world_action.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +"""CPU-only paired deployment export; checkpoint optimizer and frozen models are excluded.""" +import argparse +import json +from pathlib import Path +import torch.distributed.checkpoint as dcp + +from mira.joint.deployment import build_joint, save_pair +from mira.joint.training_utils import apply_ema_to_state +from mira.training.world_v8.checkpoint import checkpoint_fingerprint + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('checkpoint', type=Path) + parser.add_argument('output', type=Path) + parser.add_argument('--weights', choices=('model', 'ema'), default='model', + help='Export the live weights or the EMA weights saved with the checkpoint') + args = parser.parse_args() + metadata = json.loads((args.checkpoint / 'trainer_state.json').read_text()) + if metadata['architecture'] != 'bihub-joint-world-action-anchor-v2': + raise ValueError('Only corrected anchor-v2 joint checkpoints can be exported here') + model = build_joint(metadata['resolved_config']) + state = {'model': model.state_dict()} + if args.weights == 'ema': + if not metadata.get('ema', {}).get('saved'): + raise ValueError('Checkpoint was saved without EMA weights') + state['ema'] = {name: parameter.detach().clone() for name, parameter in model.named_parameters()} + dcp.load(state, checkpoint_id=args.checkpoint / 'distributed') + weights = state['model'] if args.weights == 'model' else apply_ema_to_state(state['model'], state['ema']) + model.load_state_dict(weights, strict=True) + # The weight source is part of the deployment identity; EMA and live exports never share a fingerprint. + fingerprint = checkpoint_fingerprint(args.checkpoint) + ('' if args.weights == 'model' else ':ema') + metadata = {**metadata, 'exported_weights': args.weights} + save_pair(model.state_dict(), metadata, args.output, fingerprint) + print(args.output / 'deployment.json') + + +if __name__ == '__main__': + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/filter_robotwin_manifests.py b/release-20261107/source/workspace_joint/mira/scripts/filter_robotwin_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..78ee0aa7a367ea856997649071ca4e21b9b624a9 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/filter_robotwin_manifests.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +"""Build RoboTwin manifests compatible with a fixed-length codec clip.""" + +from __future__ import annotations + +import argparse +import ctypes +import json +import logging + +from mira.data.robotwin_loader import build_robotwin_compatible_manifests + + +def _set_process_name() -> None: + libc = ctypes.CDLL(None) + libc.prctl(15, b"syncnet_filter", 0, 0, 0) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--dataset-root", required=True) + parser.add_argument("--train-manifest", required=True) + parser.add_argument("--val-manifest", required=True) + parser.add_argument("--output-dir", required=True) + parser.add_argument("--clip-len", type=int, required=True) + parser.add_argument("--source-fps", type=int, required=True) + parser.add_argument("--target-fps", type=int, required=True) + parser.add_argument("--probes-per-archive", type=int, default=3) + parser.add_argument("--workers", type=int, default=8) + parser.add_argument("--force", action="store_true") + args = parser.parse_args() + + _set_process_name() + logging.basicConfig(level=logging.INFO, format="[%(asctime)s][%(name)s][%(levelname)s] - %(message)s") + summary = build_robotwin_compatible_manifests( + args.dataset_root, + args.train_manifest, + args.val_manifest, + args.output_dir, + clip_len=args.clip_len, + source_fps=args.source_fps, + target_fps=args.target_fps, + probes_per_archive=args.probes_per_archive, + workers=args.workers, + force=args.force, + ) + print(json.dumps(summary, indent=2, ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/launch_action_head.sh b/release-20261107/source/workspace_joint/mira/scripts/launch_action_head.sh new file mode 100644 index 0000000000000000000000000000000000000000..a82fd840c6076a08da807bb496488cfe3db23ef3 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/launch_action_head.sh @@ -0,0 +1,466 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Every network-capable child inherits an explicit direct-connection environment. +unset http_proxy https_proxy all_proxy ftp_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY FTP_PROXY +export NO_PROXY='*' +export no_proxy='*' + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +WORKSPACE="$(cd "$ROOT/.." && pwd)" +PYTHON="${MIRA_PYTHON:-/private/software/conda/envs/mira/bin/python}" +WORLD_CHECKPOINT="${MIRA_ACTION_WORLD_CHECKPOINT:-$WORKSPACE/outputs/robotwin_3view_world_1b/checkpoint-80000}" +LATENT_ROOT="${MIRA_LATENT_ROOT:-$WORKSPACE/artifacts/latent_cache/c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615}" +STATE_STATS="${MIRA_ACTION_STATE_STATS:-$WORKSPACE/datasets/RoboTwin2.0/mira_wam_aloha/dataset_stats.json}" +SMOKE_ROOT="${MIRA_ACTION_SMOKE_ROOT:-$WORKSPACE/artifacts/action_stage_smoke}" +FORMAL_ROOT="${MIRA_ACTION_FORMAL_ROOT:-$WORKSPACE/artifacts/action_stage}" +SMOKE_OUTPUT="${MIRA_ACTION_SMOKE_OUTPUT:-$WORKSPACE/outputs/robotwin_joint_action_flow_smoke}" +FORMAL_OUTPUT="${MIRA_ACTION_FORMAL_OUTPUT:-$WORKSPACE/outputs/robotwin_joint_action_flow}" +ALLOWED_GPUS="${MIRA_ACTION_GPUS:-6,7}" +LOG_ROOT="$WORKSPACE/outputs/action_head_logs" +TMUX_SOCKET="${MIRA_TMUX_SOCKET:-hc}" +TMUX_SESSION="${MIRA_TMUX_SESSION:-hc}" +mkdir -p "$LOG_ROOT" + +usage() { + echo "usage: $0 {prepare-smoke-manifest|select-smoke-world|build-smoke-future|prepare-smoke|smoke|smoke-resume-check|smoke-batch8-probe|canary-2gpu-equivalent|eval-smoke|smoke-pipeline|tmux-smoke|prepare-formal-manifest|select-formal-world|build-formal-future|eval-formal|train-formal|tmux-formal|train-formal-2gpu|train-formal-2gpu-warmup|pipeline-formal-2gpu|wait-warmup-pipeline-2gpu|tmux-formal-2gpu|tmux-formal-2gpu-warmup|tmux-pipeline-formal-2gpu|tmux-wait-warmup-pipeline-2gpu}" +} + +require_file() { + if [[ ! -f "$1" ]]; then + echo "required file not found: $1" >&2 + exit 2 + fi +} + +require_two_allowed_gpus() { + if [[ "$ALLOWED_GPUS" != "6,7" ]]; then + echo "This coexistence smoke is locked to physical GPUs 6,7; got MIRA_ACTION_GPUS=$ALLOWED_GPUS" >&2 + exit 2 + fi + local free + free="$(nvidia-smi --query-gpu=memory.free --format=csv,noheader,nounits -i 6,7)" + echo "Physical GPU 6,7 free memory before Action operation:" + nvidia-smi --query-gpu=index,memory.used,memory.free,utilization.gpu --format=csv,noheader -i 6,7 + while read -r value; do + if ((value < 30000)); then + echo "Less than 30 GiB is free on an authorized GPU; refusing a coexistence smoke." >&2 + exit 3 + fi + done <<<"$free" +} + +require_two_warmup_headroom() { + if [[ "$ALLOWED_GPUS" != "6,7" ]]; then + echo "The coexistence run is locked to physical GPUs 6,7." >&2 + exit 2 + fi + local free + free="$(nvidia-smi --query-gpu=memory.free --format=csv,noheader,nounits -i 6,7)" + echo "Physical GPU 6,7 state before GT-only Action warm-up:" + nvidia-smi --query-gpu=index,memory.used,memory.free,utilization.gpu --format=csv,noheader -i 6,7 + while read -r value; do + if ((value < 10000)); then + echo "Less than 10 GiB is free; refusing the measured 7.56-GiB Action workload." >&2 + exit 3 + fi + done <<<"$free" +} + +export_smoke_paths() { + export MIRA_ACTION_WORLD_SELECTION="$SMOKE_ROOT/world/world_selection.json" + export MIRA_ACTION_STATE_ENCODER="$SMOKE_ROOT/world/selected_state_encoder.pt" + export MIRA_ACTION_TRAIN_MANIFEST="$SMOKE_ROOT/manifests/train.jsonl" + export MIRA_ACTION_VAL_MANIFEST="$SMOKE_ROOT/manifests/val.jsonl" + export MIRA_ACTION_STATS="$SMOKE_ROOT/manifests/action_stats.json" + export MIRA_ACTION_TRAIN_FUTURE="$SMOKE_ROOT/future_pred10/train" + export MIRA_ACTION_VAL_FUTURE="$SMOKE_ROOT/future_pred10/val" + export MIRA_ACTION_OUTPUT_DIR="$SMOKE_OUTPUT" + export SWANLAB_TOKEN_FILE="${SWANLAB_TOKEN_FILE:-$WORKSPACE/z_oranger/token.txt}" +} + +prepare_smoke_manifest() { + require_file "$LATENT_ROOT/manifest_train.jsonl" + require_file "$LATENT_ROOT/manifest_val.jsonl" + require_file "$STATE_STATS" + mkdir -p "$SMOKE_ROOT/manifests" + cd "$ROOT" + "$PYTHON" scripts/build_robotwin_action_manifest.py \ + --train-world-manifest "$LATENT_ROOT/manifest_train.jsonl" \ + --val-world-manifest "$LATENT_ROOT/manifest_val.jsonl" \ + --state-stats "$STATE_STATS" \ + --output-dir "$SMOKE_ROOT/manifests" \ + --future-shards 2 \ + --max-train-windows "${MIRA_ACTION_SMOKE_TRAIN_WINDOWS:-8}" \ + --max-val-windows "${MIRA_ACTION_SMOKE_VAL_WINDOWS:-4}" \ + --smoke-small-stats +} + +select_smoke_world() { + require_two_allowed_gpus + require_file "$WORLD_CHECKPOINT/trainer_state.json" + require_file "$LATENT_ROOT/manifest_val.jsonl" + mkdir -p "$SMOKE_ROOT/world" + cd "$ROOT" + CUDA_VISIBLE_DEVICES=6 "$PYTHON" scripts/select_action_world_weights.py \ + --checkpoint "$WORLD_CHECKPOINT" \ + --val-manifest "$LATENT_ROOT/manifest_val.jsonl" \ + --state-stats "$STATE_STATS" \ + --output-dir "$SMOKE_ROOT/world" \ + --device cuda:0 \ + --cases "${MIRA_ACTION_SMOKE_WORLD_CASES:-2}" +} + +build_split_future() { + local split="$1" + local manifest="$SMOKE_ROOT/manifests/$split.jsonl" + local output="$SMOKE_ROOT/future_pred10/$split" + require_file "$manifest" + require_file "$SMOKE_ROOT/world/world_selection.json" + rm -f "$output/COMPLETE" + mkdir -p "$output" + local pids=() + local rank + for rank in 0 1; do + local physical=$((rank + 6)) + CUDA_VISIBLE_DEVICES="$physical" "$PYTHON" scripts/build_action_future_cache.py \ + --action-manifest "$manifest" \ + --state-stats "$STATE_STATS" \ + --world-selection "$SMOKE_ROOT/world/world_selection.json" \ + --output-dir "$output" \ + --num-shards 2 \ + --shard-index "$rank" \ + --device cuda:0 \ + --flush-every 1 \ + >"$LOG_ROOT/smoke-future-$split-rank$rank.log" 2>&1 & + pids+=("$!") + done + local failed=0 + for rank in 0 1; do + if ! wait "${pids[$rank]}"; then + echo "Future-cache $split shard $rank failed; see $LOG_ROOT/smoke-future-$split-rank$rank.log" >&2 + failed=1 + fi + done + if ((failed)); then + exit 1 + fi + "$PYTHON" scripts/build_action_future_cache.py \ + --action-manifest "$manifest" \ + --state-stats "$STATE_STATS" \ + --world-selection "$SMOKE_ROOT/world/world_selection.json" \ + --output-dir "$output" \ + --num-shards 2 \ + --finalize-only +} + +build_smoke_future() { + require_two_allowed_gpus + build_split_future train + build_split_future val +} + +prepare_smoke() { + prepare_smoke_manifest + select_smoke_world + build_smoke_future +} + +run_smoke() { + require_two_allowed_gpus + export_smoke_paths + require_file "$MIRA_ACTION_TRAIN_FUTURE/COMPLETE" + require_file "$MIRA_ACTION_VAL_FUTURE/COMPLETE" + rm -rf "$SMOKE_OUTPUT" + cd "$ROOT" + export MIRA_LAUNCHER_PROCESS_NAME=syncnet_act_l + CUDA_VISIBLE_DEVICES="$ALLOWED_GPUS" "$PYTHON" scripts/syncnet_torchrun.py \ + --standalone --nproc_per_node=2 scripts/train_action_head.py \ + --config-name train_action_head_smoke +} + +run_smoke_resume_check() { + require_two_allowed_gpus + export_smoke_paths + require_file "$SMOKE_OUTPUT/checkpoint-6/trainer_state.json" + cd "$ROOT" + export MIRA_LAUNCHER_PROCESS_NAME=syncnet_act_l + CUDA_VISIBLE_DEVICES="$ALLOWED_GPUS" "$PYTHON" scripts/syncnet_torchrun.py \ + --standalone --nproc_per_node=2 scripts/train_action_head.py \ + --config-name train_action_head_smoke \ + run.auto_resume=true training.steps=7 validation.every=7 checkpoint.every=7 +} + +run_smoke_batch8_probe() { + require_two_allowed_gpus + export_smoke_paths + export MIRA_ACTION_OUTPUT_DIR="$WORKSPACE/outputs/robotwin_joint_action_flow_batch8_probe" + rm -rf "$MIRA_ACTION_OUTPUT_DIR" + cd "$ROOT" + export MIRA_LAUNCHER_PROCESS_NAME=syncnet_act_l + CUDA_VISIBLE_DEVICES="$ALLOWED_GPUS" "$PYTHON" scripts/syncnet_torchrun.py \ + --standalone --nproc_per_node=2 scripts/train_action_head.py \ + --config-name train_action_head_smoke \ + training.steps=2 \ + training.per_device_batch=8 \ + training.effective_global_batch=16 \ + training.optimizer.warmup_steps=2 \ + training.future_curriculum.gt_only_until=0 \ + training.future_curriculum.transition_end=0 \ + validation.every=999 validation.at_end=false \ + visualization.every=999 checkpoint.every=999 checkpoint.save_final=false +} + +run_equivalent_2gpu_canary() { + require_two_allowed_gpus + export_smoke_paths + export MIRA_ACTION_OUTPUT_DIR="$WORKSPACE/outputs/robotwin_joint_action_flow_2gpu_canary" + rm -rf "$MIRA_ACTION_OUTPUT_DIR" + cd "$ROOT" + export MIRA_LAUNCHER_PROCESS_NAME=syncnet_act_l + CUDA_VISIBLE_DEVICES="$ALLOWED_GPUS" "$PYTHON" scripts/syncnet_torchrun.py \ + --standalone --nproc_per_node=2 scripts/train_action_head.py \ + --config-name train_action_head_smoke \ + training.steps=2 \ + training.per_device_batch=8 \ + training.gradient_accumulation_steps=8 \ + training.effective_global_batch=128 \ + training.optimizer.warmup_steps=2 \ + training.future_curriculum.gt_only_until=0 \ + training.future_curriculum.transition_end=0 \ + validation.every=999 validation.at_end=false \ + visualization.every=999 checkpoint.every=999 checkpoint.save_final=false +} + +prepare_formal_manifest() { + mkdir -p "$FORMAL_ROOT/manifests" + cd "$ROOT" + "$PYTHON" scripts/build_robotwin_action_manifest.py \ + --train-world-manifest "$LATENT_ROOT/manifest_train.jsonl" \ + --val-world-manifest "$LATENT_ROOT/manifest_val.jsonl" \ + --state-stats "$STATE_STATS" \ + --output-dir "$FORMAL_ROOT/manifests" \ + --future-shards 8 +} + +select_formal_world() { + echo "Formal paired selection is intentionally not run on only GPUs 6,7 by default." + echo "Set MIRA_ACTION_FORMAL_SELECTION_GPU to one authorized GPU to proceed." + local gpu="${MIRA_ACTION_FORMAL_SELECTION_GPU:-}" + if [[ -z "$gpu" || ("$gpu" != "6" && "$gpu" != "7") ]]; then + exit 2 + fi + mkdir -p "$FORMAL_ROOT/world" + cd "$ROOT" + CUDA_VISIBLE_DEVICES="$gpu" "$PYTHON" scripts/select_action_world_weights.py \ + --checkpoint "$WORLD_CHECKPOINT" \ + --val-manifest "$LATENT_ROOT/manifest_val.jsonl" \ + --state-stats "$STATE_STATS" \ + --output-dir "$FORMAL_ROOT/world" \ + --device cuda:0 \ + --cases "${MIRA_ACTION_FORMAL_WORLD_CASES:-64}" +} + +build_formal_split_future() { + local split="$1" + local manifest="$FORMAL_ROOT/manifests/$split.jsonl" + local output="$FORMAL_ROOT/future_pred10/$split" + require_file "$manifest" + require_file "$FORMAL_ROOT/world/world_selection.json" + rm -f "$output/COMPLETE" + mkdir -p "$output" + local pids=() + local worker + for worker in 0 1; do + local physical=$((worker + 6)) + ( + local shard + for ((shard=worker; shard<8; shard+=2)); do + CUDA_VISIBLE_DEVICES="$physical" "$PYTHON" scripts/build_action_future_cache.py \ + --action-manifest "$manifest" \ + --state-stats "$STATE_STATS" \ + --world-selection "$FORMAL_ROOT/world/world_selection.json" \ + --output-dir "$output" \ + --num-shards 8 \ + --shard-index "$shard" \ + --device cuda:0 \ + --batch-size "${MIRA_ACTION_FUTURE_BATCH_SIZE:-20}" \ + --flush-every 100 + done + ) >"$LOG_ROOT/formal-future-$split-worker$worker.log" 2>&1 & + pids+=("$!") + done + local failed=0 + for worker in 0 1; do + if ! wait "${pids[$worker]}"; then + echo "Formal future-cache $split worker $worker failed; see logs." >&2 + failed=1 + fi + done + if ((failed)); then + exit 1 + fi + "$PYTHON" scripts/build_action_future_cache.py \ + --action-manifest "$manifest" \ + --state-stats "$STATE_STATS" \ + --world-selection "$FORMAL_ROOT/world/world_selection.json" \ + --output-dir "$output" \ + --num-shards 8 \ + --finalize-only +} + +build_formal_future() { + require_two_allowed_gpus + build_formal_split_future train + build_formal_split_future val +} + +eval_smoke() { + require_two_allowed_gpus + export_smoke_paths + export MIRA_ACTION_EVAL_CHECKPOINT="${MIRA_ACTION_EVAL_CHECKPOINT:-$SMOKE_OUTPUT/checkpoint-7}" + export MIRA_ACTION_EVAL_OUTPUT="${MIRA_ACTION_EVAL_OUTPUT:-$WORKSPACE/outputs/robotwin_joint_action_flow_smoke_eval}" + require_file "$MIRA_ACTION_EVAL_CHECKPOINT/trainer_state.json" + rm -rf "$MIRA_ACTION_EVAL_OUTPUT" + cd "$ROOT" + export MIRA_LAUNCHER_PROCESS_NAME=syncnet_act_e + CUDA_VISIBLE_DEVICES="$ALLOWED_GPUS" "$PYTHON" scripts/syncnet_torchrun.py \ + --standalone --nproc_per_node=2 scripts/eval_action_head_offline.py \ + cases=4 action_steps=2 visualization_cases=1 +} + +eval_formal() { + require_two_allowed_gpus + export MIRA_ACTION_EVAL_CHECKPOINT="${MIRA_ACTION_EVAL_CHECKPOINT:-$FORMAL_OUTPUT/checkpoint-100000}" + export MIRA_ACTION_EVAL_OUTPUT="${MIRA_ACTION_EVAL_OUTPUT:-${FORMAL_OUTPUT}_offline_eval}" + require_file "$MIRA_ACTION_EVAL_CHECKPOINT/trainer_state.json" + cd "$ROOT" + export MIRA_LAUNCHER_PROCESS_NAME=syncnet_act_e + CUDA_VISIBLE_DEVICES="$ALLOWED_GPUS" "$PYTHON" scripts/syncnet_torchrun.py \ + --standalone --nproc_per_node=2 scripts/eval_action_head_offline.py +} + +train_formal() { + local formal_gpus="${MIRA_ACTION_FORMAL_GPUS:-}" + local count + count="$(awk -F, '{print NF}' <<<"$formal_gpus")" + if [[ -z "$formal_gpus" || "$count" -ne 8 ]]; then + echo "Formal Action training requires an explicit 8-GPU MIRA_ACTION_FORMAL_GPUS list." >&2 + echo "The current GPU 6,7 authorization is sufficient only for smoke testing." >&2 + exit 2 + fi + export MIRA_ACTION_OUTPUT_DIR="$FORMAL_OUTPUT" + export MIRA_LAUNCHER_PROCESS_NAME=syncnet_act_l + cd "$ROOT" + CUDA_VISIBLE_DEVICES="$formal_gpus" "$PYTHON" scripts/syncnet_torchrun.py \ + --standalone --nproc_per_node=8 scripts/train_action_head.py +} + +train_formal_2gpu() { + require_two_allowed_gpus + require_file "$FORMAL_ROOT/future_pred10/train/COMPLETE" + require_file "$FORMAL_ROOT/future_pred10/val/COMPLETE" + export MIRA_ACTION_OUTPUT_DIR="${MIRA_ACTION_OUTPUT_DIR:-$WORKSPACE/outputs/robotwin_joint_action_flow_2gpu}" + export MIRA_LAUNCHER_PROCESS_NAME=syncnet_act_l + export SWANLAB_TOKEN_FILE="${SWANLAB_TOKEN_FILE:-$WORKSPACE/z_oranger/token.txt}" + cd "$ROOT" + CUDA_VISIBLE_DEVICES="$ALLOWED_GPUS" "$PYTHON" scripts/syncnet_torchrun.py \ + --standalone --nproc_per_node=2 scripts/train_action_head.py \ + --config-name train_action_head_2gpu +} + +train_formal_2gpu_warmup() { + require_two_warmup_headroom + require_file "$FORMAL_ROOT/manifests/train.jsonl" + require_file "$FORMAL_ROOT/manifests/val.jsonl" + require_file "$FORMAL_ROOT/manifests/action_stats.json" + require_file "$FORMAL_ROOT/world/world_selection.json" + export MIRA_ACTION_OUTPUT_DIR="${MIRA_ACTION_OUTPUT_DIR:-$WORKSPACE/outputs/robotwin_joint_action_flow_2gpu}" + export MIRA_LAUNCHER_PROCESS_NAME=syncnet_act_l + export SWANLAB_TOKEN_FILE="${SWANLAB_TOKEN_FILE:-$WORKSPACE/z_oranger/token.txt}" + cd "$ROOT" + CUDA_VISIBLE_DEVICES="$ALLOWED_GPUS" "$PYTHON" scripts/syncnet_torchrun.py \ + --standalone --nproc_per_node=2 scripts/train_action_head.py \ + --config-name train_action_head_2gpu \ + data.allow_incomplete_future_cache=true \ + run.stop_at_step_if_future_incomplete=5000 +} + +pipeline_formal_2gpu() { + build_formal_future + train_formal_2gpu +} + +wait_warmup_pipeline_2gpu() { + local checkpoint="$WORKSPACE/outputs/robotwin_joint_action_flow_2gpu/checkpoint-5000/trainer_state.json" + echo "Waiting for GT-only Action checkpoint: $checkpoint" + while [[ ! -f "$checkpoint" ]]; do + if ! pgrep -x syncnet_act_r0 >/dev/null; then + echo "GT-only Action worker exited before checkpoint-5000 was committed." >&2 + exit 4 + fi + sleep 60 + done + echo "GT-only checkpoint is complete; switching GPUs 6,7 to future-cache generation." + export MIRA_ACTION_FUTURE_BATCH_SIZE="${MIRA_ACTION_FUTURE_BATCH_SIZE:-32}" + build_formal_future + echo "Predicted-future cache is complete; resuming Action training from checkpoint-5000." + train_formal_2gpu +} + +ensure_tmux_session() { + if ! tmux -L "$TMUX_SOCKET" has-session -t "$TMUX_SESSION" 2>/dev/null; then + tmux -L "$TMUX_SOCKET" new-session -d -s "$TMUX_SESSION" -n control + fi +} + +case "${1:-}" in + prepare-smoke-manifest) prepare_smoke_manifest ;; + select-smoke-world) select_smoke_world ;; + build-smoke-future) build_smoke_future ;; + prepare-smoke) prepare_smoke ;; + smoke) run_smoke ;; + smoke-resume-check) run_smoke_resume_check ;; + smoke-batch8-probe) run_smoke_batch8_probe ;; + canary-2gpu-equivalent) run_equivalent_2gpu_canary ;; + eval-smoke) eval_smoke ;; + smoke-pipeline) prepare_smoke; run_smoke ;; + tmux-smoke) + tmux -L "$TMUX_SOCKET" new-window -t "$TMUX_SESSION" -n action-smoke \ + "cd '$ROOT' && exec -a syncnet_act_p bash scripts/launch_action_head.sh smoke-pipeline 2>&1 | tee '$LOG_ROOT/smoke-pipeline.log'" + ;; + prepare-formal-manifest) prepare_formal_manifest ;; + select-formal-world) select_formal_world ;; + build-formal-future) build_formal_future ;; + eval-formal) eval_formal ;; + train-formal) train_formal ;; + train-formal-2gpu) train_formal_2gpu ;; + train-formal-2gpu-warmup) train_formal_2gpu_warmup ;; + pipeline-formal-2gpu) pipeline_formal_2gpu ;; + wait-warmup-pipeline-2gpu) wait_warmup_pipeline_2gpu ;; + tmux-formal) + tmux -L "$TMUX_SOCKET" new-window -t "$TMUX_SESSION" -n action-train \ + "cd '$ROOT' && exec -a syncnet_act_p bash scripts/launch_action_head.sh train-formal 2>&1 | tee -a '$LOG_ROOT/formal-train.log'" + ;; + tmux-formal-2gpu) + ensure_tmux_session + tmux -L "$TMUX_SOCKET" new-window -t "$TMUX_SESSION" -n action-train-2g \ + "cd '$ROOT' && exec -a syncnet_act_p bash scripts/launch_action_head.sh train-formal-2gpu 2>&1 | tee -a '$LOG_ROOT/formal-train-2gpu.log'" + ;; + tmux-formal-2gpu-warmup) + ensure_tmux_session + tmux -L "$TMUX_SOCKET" new-window -t "$TMUX_SESSION" -n action-warmup-2g \ + "cd '$ROOT' && exec -a syncnet_act_p bash scripts/launch_action_head.sh train-formal-2gpu-warmup 2>&1 | tee -a '$LOG_ROOT/formal-train-2gpu.log'" + ;; + tmux-pipeline-formal-2gpu) + ensure_tmux_session + tmux -L "$TMUX_SOCKET" new-window -t "$TMUX_SESSION" -n action-pipe-2g \ + "cd '$ROOT' && exec -a syncnet_act_p bash scripts/launch_action_head.sh pipeline-formal-2gpu 2>&1 | tee -a '$LOG_ROOT/formal-pipeline-2gpu.log'" + ;; + tmux-wait-warmup-pipeline-2gpu) + ensure_tmux_session + tmux -L "$TMUX_SOCKET" new-window -t "$TMUX_SESSION" -n action-auto-2g \ + "cd '$ROOT' && exec -a syncnet_act_p bash scripts/launch_action_head.sh wait-warmup-pipeline-2gpu 2>&1 | tee -a '$LOG_ROOT/formal-auto-2gpu.log'" + ;; + *) usage; exit 2 ;; +esac diff --git a/release-20261107/source/workspace_joint/mira/scripts/launch_action_v10_h1_50.sh b/release-20261107/source/workspace_joint/mira/scripts/launch_action_v10_h1_50.sh new file mode 100644 index 0000000000000000000000000000000000000000..178ba090fea479400c959961a8e8fc369bc75d91 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/launch_action_v10_h1_50.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +set -euo pipefail + +export PYTHONPATH=src +PYTHON=/public/inz/envs/multi-wam-mira/bin/python +LOG_ROOT=../../z_tmp/logs +mkdir -p "$LOG_ROOT" + +case "${1:-}" in + cache) + export MIRA_V6_PROCESS_PREFIX=tagshotx_a10c + "$PYTHON" -m torch.distributed.run --standalone --nproc-per-node=8 \ + -m mira.training.action_v10.build_predicted_cache \ + --config configs/action_v10_h1_50/base.yaml \ + 2>&1 | tee -a "$LOG_ROOT/action_v10_predicted_cache.log" + ;; + gt) + export MIRA_V6_PROCESS_PREFIX=tagshotx_a10g + "$PYTHON" -m torch.distributed.run --standalone --nproc-per-node=8 \ + -m mira.training.action_v6.train \ + --config configs/action_v10_h1_50/train_gt10k.yaml \ + 2>&1 | tee -a "$LOG_ROOT/action_v10_gt10k.log" + ;; + predicted) + "$PYTHON" -m mira.training.action_v10.preflight \ + --config configs/action_v10_h1_50/train_pred20k.yaml --require-cache \ + 2>&1 | tee "$LOG_ROOT/action_v10_predicted_preflight.log" + export MIRA_V6_PROCESS_PREFIX=tagshotx_a10p + "$PYTHON" -m torch.distributed.run --standalone --nproc-per-node=8 \ + -m mira.training.action_v6.train \ + --config configs/action_v10_h1_50/train_pred20k.yaml \ + 2>&1 | tee -a "$LOG_ROOT/action_v10_pred20k.log" + ;; + predicted10k) + "$PYTHON" -m mira.training.action_v10.preflight \ + --config configs/action_v10_h1_50/train_pred10k_from4139.yaml --require-cache \ + 2>&1 | tee "$LOG_ROOT/action_v10_pred10k_preflight.log" + export MIRA_V6_PROCESS_PREFIX=tagshotx_a10p + "$PYTHON" -m torch.distributed.run --standalone --nproc-per-node=8 \ + -m mira.training.action_v6.train \ + --config configs/action_v10_h1_50/train_pred10k_from4139.yaml \ + 2>&1 | tee -a "$LOG_ROOT/action_v10_pred10k_from4139.log" + ;; + watch) + while [[ ! -f ../outputs/robotwin_bihub_wam_v10_action_h1_50/action-checkpoint-10000/trainer_state.json ]]; do + sleep 60 + done + while [[ ! -f ../artifacts/action_v10/predicted_future/d0d815eacd8d9fd5/predicted_future_cache_identity.json ]]; do + sleep 60 + done + exec bash scripts/launch_action_v10_h1_50.sh predicted + ;; + *) + echo "usage: $0 {cache|gt|predicted|predicted10k|watch}" >&2 + exit 2 + ;; +esac diff --git a/release-20261107/source/workspace_joint/mira/scripts/launch_action_v11_pred8k.sh b/release-20261107/source/workspace_joint/mira/scripts/launch_action_v11_pred8k.sh new file mode 100644 index 0000000000000000000000000000000000000000..295815b82d0242ff1613f4237b8a824f03cb85f3 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/launch_action_v11_pred8k.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +set -euo pipefail + +unset http_proxy https_proxy all_proxy ftp_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY FTP_PROXY NO_PROXY no_proxy +export NO_PROXY='*' +export no_proxy='*' +export HF_HUB_OFFLINE=1 +export TRANSFORMERS_OFFLINE=1 + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" +if [[ -n "${MIRA_PYTHON:-}" ]]; then + PYTHON="$MIRA_PYTHON" +else + source "${MIRA_CONDA_BASHRC:-/public/inz/.bashrc}" >/dev/null 2>&1 || true + conda activate "${MIRA_CONDA_ENV:-multi-wam-mira}" + PYTHON="$CONDA_PREFIX/bin/python" +fi +[[ -x "$PYTHON" ]] || { echo "Missing executable Python: $PYTHON" >&2; exit 2; } +LOG_ROOT=../artifacts/action_v11/logs +mkdir -p "$LOG_ROOT" + +cache() { + CUDA_VISIBLE_DEVICES="${MIRA_A11_GPUS:-0,1,2,3,4,5,6,7}" \ + MIRA_V6_PROCESS_PREFIX=filter_x_a11c \ + MIRA_LAUNCHER_PROCESS_NAME=filter_x_a11cl \ + MIRA_PREDICTED_CACHE_MICRO_BATCH=16 \ + "$PYTHON" scripts/syncnet_torchrun.py --standalone --nproc_per_node=8 \ + -m mira.training.action_v10.build_predicted_cache \ + --config configs/action_v11_pred8k/base.yaml +} + +preflight() { + local config="$1" + CUDA_VISIBLE_DEVICES="${MIRA_A11_GPUS:-0,1,2,3,4,5,6,7}" \ + "$PYTHON" -m mira.training.action_v10.preflight \ + --config "$config" --require-cache +} + +train() { + local config="$1" + CUDA_VISIBLE_DEVICES="${MIRA_A11_GPUS:-0,1,2,3,4,5,6,7}" \ + MIRA_V6_PROCESS_PREFIX=filter_x_a11 \ + MIRA_LAUNCHER_PROCESS_NAME=filter_x_a11l \ + "$PYTHON" scripts/syncnet_torchrun.py --standalone --nproc_per_node=8 \ + -m mira.training.action_v6.train --config "$config" +} + +case "${1:-}" in + cache) + cache 2>&1 | tee "$LOG_ROOT/predicted_cache.log" + ;; + smoke) + preflight configs/action_v11_pred8k/smoke.yaml 2>&1 | tee "$LOG_ROOT/preflight-smoke.log" + train configs/action_v11_pred8k/smoke.yaml 2>&1 | tee "$LOG_ROOT/smoke.log" + ;; + formal) + preflight configs/action_v11_pred8k/train.yaml 2>&1 | tee "$LOG_ROOT/preflight-formal.log" + train configs/action_v11_pred8k/train.yaml 2>&1 | tee "$LOG_ROOT/formal.log" + ;; + pipeline) + cache 2>&1 | tee "$LOG_ROOT/predicted_cache.log" + preflight configs/action_v11_pred8k/smoke.yaml 2>&1 | tee "$LOG_ROOT/preflight-smoke.log" + train configs/action_v11_pred8k/smoke.yaml 2>&1 | tee "$LOG_ROOT/smoke.log" + preflight configs/action_v11_pred8k/train.yaml 2>&1 | tee "$LOG_ROOT/preflight-formal.log" + train configs/action_v11_pred8k/train.yaml 2>&1 | tee "$LOG_ROOT/formal.log" + ;; + *) + echo "usage: $0 {cache|smoke|formal|pipeline}" >&2 + exit 2 + ;; +esac diff --git a/release-20261107/source/workspace_joint/mira/scripts/launch_action_v12_epoch.sh b/release-20261107/source/workspace_joint/mira/scripts/launch_action_v12_epoch.sh new file mode 100644 index 0000000000000000000000000000000000000000..7ce23740e57eb1131597948d561924bd33f6d0b8 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/launch_action_v12_epoch.sh @@ -0,0 +1,87 @@ +#!/usr/bin/env bash +set -euo pipefail + +unset http_proxy https_proxy all_proxy ftp_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY FTP_PROXY NO_PROXY no_proxy +export NO_PROXY='*' +export no_proxy='*' +export HF_HUB_OFFLINE=1 +export TRANSFORMERS_OFFLINE=1 + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" +source "${MIRA_CONDA_BASHRC:-/public/inz/.bashrc}" >/dev/null 2>&1 || true +conda activate "${MIRA_CONDA_ENV:-multi-wam-mira}" +PYTHON="$CONDA_PREFIX/bin/python" +LOG_ROOT=../artifacts/action_v12/logs +REPORT_ROOT=../artifacts/action_v12/reports +mkdir -p "$LOG_ROOT" "$REPORT_ROOT" + +cache() { + local config="$1" + local prefix="$2" + CUDA_VISIBLE_DEVICES="${MIRA_A12_GPUS:-0,1,2,3,4,5,6,7}" \ + MIRA_V6_PROCESS_PREFIX="$prefix" \ + MIRA_LAUNCHER_PROCESS_NAME="${prefix}l" \ + MIRA_PREDICTED_CACHE_MICRO_BATCH="${MIRA_A12_CACHE_BATCH:-96}" \ + "$PYTHON" scripts/syncnet_torchrun.py --standalone --nproc_per_node=8 \ + -m mira.training.action_v10.build_predicted_cache --config "$config" +} + +preflight() { + local config="$1" + local report="$2" + CUDA_VISIBLE_DEVICES="${MIRA_A12_GPUS:-0,1,2,3,4,5,6,7}" \ + "$PYTHON" -m mira.training.action_v12.preflight \ + --config "$config" --report "$report" +} + +train() { + local config="$1" + local prefix="$2" + CUDA_VISIBLE_DEVICES="${MIRA_A12_GPUS:-0,1,2,3,4,5,6,7}" \ + MIRA_V6_PROCESS_PREFIX="$prefix" \ + MIRA_LAUNCHER_PROCESS_NAME="${prefix}l" \ + "$PYTHON" scripts/syncnet_torchrun.py --standalone --nproc_per_node=8 \ + -m mira.training.action_v6.train --config "$config" +} + +case "${1:-}" in + cache-smoke) + cache configs/action_v12_epoch/smoke.yaml filter_x_a12cs \ + 2>&1 | tee "$LOG_ROOT/cache-smoke.log" + ;; + cache-smoke96) + MIRA_A12_CACHE_BATCH=96 cache \ + configs/action_v12_epoch/cache_smoke96.yaml filter_x_a12c96 \ + 2>&1 | tee "$LOG_ROOT/cache-smoke96.log" + ;; + smoke) + preflight configs/action_v12_epoch/smoke.yaml "$REPORT_ROOT/preflight-smoke.json" \ + 2>&1 | tee "$LOG_ROOT/preflight-smoke.log" + train configs/action_v12_epoch/smoke.yaml filter_x_a12s \ + 2>&1 | tee "$LOG_ROOT/smoke.log" + ;; + cache) + cache configs/action_v12_epoch/train.yaml filter_x_a12c \ + 2>&1 | tee -a "$LOG_ROOT/cache-formal.log" + ;; + formal) + [[ "${MIRA_ACTION_V12_ALLOW_FORMAL:-}" == YES ]] || { + echo 'Set MIRA_ACTION_V12_ALLOW_FORMAL=YES after cache, smoke, and preflight pass.' >&2 + exit 2 + } + preflight configs/action_v12_epoch/train.yaml "$REPORT_ROOT/preflight-formal.json" \ + 2>&1 | tee "$LOG_ROOT/preflight-formal.log" + train configs/action_v12_epoch/train.yaml filter_x_a12 \ + 2>&1 | tee -a "$LOG_ROOT/formal.log" + ;; + pipeline) + cache configs/action_v12_epoch/train.yaml filter_x_a12c \ + 2>&1 | tee -a "$LOG_ROOT/cache-formal.log" + MIRA_ACTION_V12_ALLOW_FORMAL=YES bash scripts/launch_action_v12_epoch.sh formal + ;; + *) + echo "usage: $0 {cache-smoke|cache-smoke96|smoke|cache|formal|pipeline}" >&2 + exit 2 + ;; +esac diff --git a/release-20261107/source/workspace_joint/mira/scripts/launch_action_v13_continue4epoch.sh b/release-20261107/source/workspace_joint/mira/scripts/launch_action_v13_continue4epoch.sh new file mode 100644 index 0000000000000000000000000000000000000000..68feaca91b4336cf6a6fb14a2b3330eb7123223d --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/launch_action_v13_continue4epoch.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +set -euo pipefail + +unset http_proxy https_proxy all_proxy ftp_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY FTP_PROXY NO_PROXY no_proxy +export NO_PROXY='*' +export no_proxy='*' +export HF_HUB_OFFLINE=1 +export TRANSFORMERS_OFFLINE=1 + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" +source "${MIRA_CONDA_BASHRC:-/public/inz/.bashrc}" >/dev/null 2>&1 || true +conda activate "${MIRA_CONDA_ENV:-multi-wam-mira}" +PYTHON="$CONDA_PREFIX/bin/python" +LOG_ROOT=../artifacts/action_v13/logs +REPORT_ROOT=../artifacts/action_v13/reports +mkdir -p "$LOG_ROOT" "$REPORT_ROOT" + +preflight() { + local config="$1" + local report="$2" + CUDA_VISIBLE_DEVICES="${MIRA_A13_GPUS:-0,1,2,3,4,5,6,7}" \ + "$PYTHON" -m mira.training.action_v12.preflight \ + --config "$config" --report "$report" +} + +train() { + local config="$1" + local prefix="$2" + CUDA_VISIBLE_DEVICES="${MIRA_A13_GPUS:-0,1,2,3,4,5,6,7}" \ + MIRA_V6_PROCESS_PREFIX="$prefix" \ + MIRA_LAUNCHER_PROCESS_NAME="${prefix}l" \ + "$PYTHON" scripts/syncnet_torchrun.py --standalone --nproc_per_node=8 \ + -m mira.training.action_v6.train --config "$config" +} + +case "${1:-}" in + smoke) + preflight configs/action_v13_continue4epoch/smoke.yaml \ + "$REPORT_ROOT/preflight-smoke.json" 2>&1 | tee "$LOG_ROOT/preflight-smoke.log" + train configs/action_v13_continue4epoch/smoke.yaml filter_x_a13s \ + 2>&1 | tee "$LOG_ROOT/smoke.log" + ;; + perf-smoke) + preflight configs/action_v13_continue4epoch/perf_smoke.yaml \ + "$REPORT_ROOT/preflight-perf-smoke.json" 2>&1 | tee "$LOG_ROOT/preflight-perf-smoke.log" + train configs/action_v13_continue4epoch/perf_smoke.yaml filter_x_a13p \ + 2>&1 | tee "$LOG_ROOT/perf-smoke.log" + ;; + perf-smoke4) + preflight configs/action_v13_continue4epoch/perf_smoke4.yaml \ + "$REPORT_ROOT/preflight-perf-smoke4.json" 2>&1 | tee "$LOG_ROOT/preflight-perf-smoke4.log" + train configs/action_v13_continue4epoch/perf_smoke4.yaml filter_x_a13p4 \ + 2>&1 | tee "$LOG_ROOT/perf-smoke4.log" + ;; + formal) + [[ "${MIRA_ACTION_V13_ALLOW_FORMAL:-}" == YES ]] || { + echo 'Set MIRA_ACTION_V13_ALLOW_FORMAL=YES after smoke and formal preflight pass.' >&2 + exit 2 + } + preflight configs/action_v13_continue4epoch/train.yaml \ + "$REPORT_ROOT/preflight-formal.json" 2>&1 | tee "$LOG_ROOT/preflight-formal.log" + train configs/action_v13_continue4epoch/train.yaml filter_x_a13 \ + 2>&1 | tee -a "$LOG_ROOT/formal.log" + ;; + *) + echo "usage: $0 {smoke|perf-smoke|perf-smoke4|formal}" >&2 + exit 2 + ;; +esac diff --git a/release-20261107/source/workspace_joint/mira/scripts/launch_action_v6_continue100k.sh b/release-20261107/source/workspace_joint/mira/scripts/launch_action_v6_continue100k.sh new file mode 100644 index 0000000000000000000000000000000000000000..c49c106d2094b4186724246d46d553d400ca8042 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/launch_action_v6_continue100k.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -euo pipefail + +MIRA_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +MIRA_PYTHON="${MIRA_PYTHON:-/public/inz/envs/multi-wam-mira/bin/python}" +LOG="${MIRA_ACTION_CONTINUE_LOG:-z_tmp/tagshotx_action_continue100k.log}" + +cd "$MIRA_ROOT" +[[ -x "$MIRA_PYTHON" ]] || { echo "missing Python: $MIRA_PYTHON" >&2; exit 2; } +[[ -s configs/action_v6/train_continue100k.yaml ]] || { echo "missing continuation config" >&2; exit 2; } +[[ "$(nvidia-smi -L | wc -l)" -ge 8 ]] || { echo "Action continuation requires eight GPUs" >&2; exit 2; } + +unset HTTP_PROXY HTTPS_PROXY ALL_PROXY FTP_PROXY http_proxy https_proxy all_proxy ftp_proxy +export NO_PROXY="*" +export HF_HUB_OFFLINE=1 +export TRANSFORMERS_OFFLINE=1 +export MIRA_LAUNCHER_PROCESS_NAME=tagshotx100_l +export MIRA_V6_PROCESS_PREFIX=tagshotx100 + +mkdir -p "$(dirname "$LOG")" +set +e +"$MIRA_PYTHON" scripts/syncnet_torchrun.py \ + --standalone \ + --nproc_per_node=8 \ + -m mira.training.action_v6.train \ + --config configs/action_v6/train_continue100k.yaml \ + >> "$LOG" 2>&1 +rc=$? +set -e +printf 'exit_code=%s\n' "$rc" >> "$LOG" +exit "$rc" diff --git a/release-20261107/source/workspace_joint/mira/scripts/launch_bihub_wam_world.sh b/release-20261107/source/workspace_joint/mira/scripts/launch_bihub_wam_world.sh new file mode 100644 index 0000000000000000000000000000000000000000..77be0eb7c25f81e77710bd872bdc2b693fc00308 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/launch_bihub_wam_world.sh @@ -0,0 +1,263 @@ +#!/usr/bin/env bash +set -euo pipefail + +# All network-capable subprocesses inherit an explicit direct-connection environment. +unset http_proxy https_proxy all_proxy ftp_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY FTP_PROXY NO_PROXY no_proxy +export NO_PROXY='*' +export no_proxy='*' + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +WORKSPACE="$(cd "$ROOT/.." && pwd)" +PYTHON="${MIRA_PYTHON:-/private/software/conda/envs/mira/bin/python}" +DATASET_ROOT="${ROBOTWIN_DATASET_ROOT:-$WORKSPACE/datasets/RoboTwin2.0}" +CODEC_CHECKPOINT="${MIRA_CODEC_CHECKPOINT:-$WORKSPACE/outputs/mira_robotwin_codec/checkpoint-125000/checkpoint.pth}" +MODEL_ROOT="${MIRA_TEXT_MODEL_ROOT:-$WORKSPACE/models/wan-umt5-xxl}" +ARTIFACTS="${MIRA_WAM_ARTIFACTS:-$WORKSPACE/artifacts}" +SMOKE_ROOT="$ARTIFACTS/wam_smoke" +SMOKE_OUTPUT="${MIRA_WAM_OUTPUT_DIR:-$WORKSPACE/outputs/robotwin_3view_world_1b_smoke}" +FORMAL_OUTPUT="${MIRA_WAM_OUTPUT_DIR:-$WORKSPACE/outputs/robotwin_3view_world_1b}" +FORMAL_MANIFEST="$DATASET_ROOT/mira_wam_aloha" +CODEC_SPLIT="$DATASET_ROOT/mira_manifests/codec_40f_30to20" +NPROC="${MIRA_WAM_NPROC:-8}" +TMUX_SOCKET="${MIRA_TMUX_SOCKET:-hc}" +TMUX_SESSION="${MIRA_TMUX_SESSION:-hc}" +LOG_ROOT="$WORKSPACE/outputs/world_model_logs" +mkdir -p "$LOG_ROOT" + +usage() { + echo "usage: $0 {prepare-smoke|smoke|tmux-smoke|prepare-formal-manifest|prepare-formal-text|prepare-formal-latents|formal-pipeline|continue-formal-pipeline|train|tmux-train}" +} + +set_shell_process_name() { + # argv[0] alone does not change /proc/PID/comm for bash; this makes process + # inspection and targeted shutdown unambiguous (Linux comm is 15 chars). + printf '%s' "$1" >"/proc/$$/comm" 2>/dev/null || true +} + +require_file() { + if [[ ! -f "$1" ]]; then + echo "required file not found: $1" >&2 + exit 2 + fi +} + +codec_sha() { + local sidecar="$CODEC_CHECKPOINT.sha256" + if [[ ! -f "$sidecar" ]]; then + sha256sum "$CODEC_CHECKPOINT" | awk '{print $1}' > "$sidecar" + fi + tr -d '[:space:]' < "$sidecar" +} + +formal_latents_ready() { + local cache_root="$ARTIFACTS/latent_cache/$(codec_sha)" + [[ -s "$cache_root/manifest_train.jsonl" ]] \ + && [[ -s "$cache_root/manifest_val.jsonl" ]] \ + && [[ -s "$cache_root/stats.json" ]] \ + && "$PYTHON" -c 'import json,sys; value=json.load(open(sys.argv[1])); raise SystemExit(0 if value.get("complete_cache") else 1)' "$cache_root/stats.json" +} + +latest_text_index() { + find "$1" -mindepth 2 -maxdepth 2 -name index.json -type f -printf '%T@ %p\n' | sort -nr | head -1 | cut -d' ' -f2- +} + +show_gpu_coexistence() { + echo "Existing named training processes (informational; nothing is killed):" + ps -eo pid,comm,args | grep -E 'syncnet_(codec|core)' | grep -v grep || true + nvidia-smi --query-gpu=index,name,memory.total,memory.used,memory.free --format=csv,noheader +} + +prepare_smoke() { + require_file "$CODEC_CHECKPOINT" + mkdir -p "$SMOKE_ROOT/raw_manifest" "$SMOKE_ROOT/text_cache" "$SMOKE_ROOT/latent_cache" + cd "$ROOT" + "$PYTHON" scripts/build_robotwin_wam_manifest.py \ + --dataset-root "$DATASET_ROOT" \ + --train-manifest "$CODEC_SPLIT/train.jsonl" \ + --val-manifest "$CODEC_SPLIT/val.jsonl" \ + --output-dir "$SMOKE_ROOT/raw_manifest" \ + --max-episodes-per-split 1 + "$PYTHON" scripts/precompute_instruction_embeddings.py \ + --manifests "$SMOKE_ROOT/raw_manifest/train.jsonl" "$SMOKE_ROOT/raw_manifest/val.jsonl" \ + --output-root "$SMOKE_ROOT/text_cache" \ + --model-root "$MODEL_ROOT" \ + --debug-deterministic + local text_index + text_index="$(latest_text_index "$SMOKE_ROOT/text_cache")" + "$PYTHON" scripts/precompute_robotwin_latents.py \ + --dataset-root "$DATASET_ROOT" \ + --manifests "$SMOKE_ROOT/raw_manifest/train.jsonl" "$SMOKE_ROOT/raw_manifest/val.jsonl" \ + --codec-checkpoint "$CODEC_CHECKPOINT" \ + --codec-sha256 "$(codec_sha)" \ + --text-cache-index "$text_index" \ + --output-root "$SMOKE_ROOT/latent_cache" \ + --device cuda:0 \ + --max-episodes-per-manifest 1 + local cache_root="$SMOKE_ROOT/latent_cache/$(codec_sha)" + "$PYTHON" scripts/audit_robotwin_wam_data.py \ + --train-manifest "$cache_root/manifest_train.jsonl" \ + --val-manifest "$cache_root/manifest_val.jsonl" \ + --raw-summary "$SMOKE_ROOT/raw_manifest/summary.json" \ + --cache-root / \ + --max-cache-checks 2 \ + --report "$SMOKE_ROOT/cache_audit.json" + echo "Smoke artifacts are ready under $SMOKE_ROOT" +} + +run_smoke() { + local cache_root="$SMOKE_ROOT/latent_cache/$(codec_sha)" + require_file "$cache_root/manifest_train.jsonl" + require_file "$cache_root/manifest_val.jsonl" + show_gpu_coexistence + cd "$ROOT" + export ROBOTWIN_DATASET_ROOT="$DATASET_ROOT" + export MIRA_CODEC_CHECKPOINT="$CODEC_CHECKPOINT" + export MIRA_WAM_RAW_MANIFEST_DIR="$SMOKE_ROOT/raw_manifest" + export MIRA_WAM_TRAIN_MANIFEST="$cache_root/manifest_train.jsonl" + export MIRA_WAM_VAL_MANIFEST="$cache_root/manifest_val.jsonl" + export MIRA_WAM_OUTPUT_DIR="$SMOKE_OUTPUT" + export SWANLAB_TOKEN_FILE="${SWANLAB_TOKEN_FILE:-$WORKSPACE/z_oranger/token.txt}" + export MIRA_LAUNCHER_PROCESS_NAME="syncnet_core_l" + exec "$PYTHON" scripts/syncnet_torchrun.py --standalone --nproc_per_node="$NPROC" \ + scripts/train_bihub_wam_world.py --config-name train_bihub_wam_world_smoke +} + +prepare_formal_manifest() { + cd "$ROOT" + "$PYTHON" scripts/build_robotwin_wam_manifest.py \ + --dataset-root "$DATASET_ROOT" \ + --train-manifest "$CODEC_SPLIT/train.jsonl" \ + --val-manifest "$CODEC_SPLIT/val.jsonl" \ + --output-dir "$FORMAL_MANIFEST" +} + +prepare_formal_text() { + require_file "$MODEL_ROOT/models_t5_umt5-xxl-enc-bf16.pth" + cd "$ROOT" + "$PYTHON" scripts/precompute_instruction_embeddings.py \ + --manifests "$FORMAL_MANIFEST/train.jsonl" "$FORMAL_MANIFEST/val.jsonl" \ + --output-root "$ARTIFACTS/text_cache" \ + --model-root "$MODEL_ROOT" \ + --device cuda:0 +} + +prepare_formal_latents() { + local text_index + text_index="$(latest_text_index "$ARTIFACTS/text_cache")" + require_file "$text_index" + local hash + hash="$(codec_sha)" + local cache_log="$LOG_ROOT/cache-$(date -u +%Y%m%dT%H%M%SZ)" + local progress_log="$LOG_ROOT/cache-progress.jsonl" + mkdir -p "$cache_log" + : >"$progress_log" + printf '%s\n' "$cache_log" >"$LOG_ROOT/CURRENT_CACHE_LOG_DIR" + echo "Latent cache logs: $cache_log" + echo "Combined progress: $progress_log" + cd "$ROOT" + local pids=() + local view_batch_args=() + if [[ "${MIRA_WAM_CACHE_BATCH_VIEWS:-0}" == "1" ]]; then + view_batch_args+=(--batch-views) + fi + local rank + for ((rank = 0; rank < NPROC; rank++)); do + "$PYTHON" scripts/precompute_robotwin_latents.py \ + --dataset-root "$DATASET_ROOT" \ + --manifests "$FORMAL_MANIFEST/train.jsonl" "$FORMAL_MANIFEST/val.jsonl" \ + --codec-checkpoint "$CODEC_CHECKPOINT" \ + --codec-sha256 "$hash" \ + --text-cache-index "$text_index" \ + --output-root "$ARTIFACTS/latent_cache" \ + --device "cuda:$rank" \ + --shard-index "$rank" \ + --num-shards "$NPROC" \ + --log-every "${MIRA_WAM_CACHE_LOG_EVERY:-1}" \ + --progress-jsonl "$progress_log" \ + --cpu-threads "${MIRA_WAM_CACHE_CPU_THREADS:-8}" \ + "${view_batch_args[@]}" \ + >"$cache_log/rank-$rank.log" 2>&1 & + pids+=("$!") + done + local failed=0 + for ((rank = 0; rank < NPROC; rank++)); do + if ! wait "${pids[$rank]}"; then + echo "latent-cache shard $rank failed; see $cache_log/rank-$rank.log" >&2 + failed=1 + fi + done + if ((failed)); then + echo "At least one latent-cache shard failed; refusing to create final manifests." >&2 + exit 1 + fi + "$PYTHON" scripts/merge_robotwin_latent_cache_shards.py \ + --manifests "$FORMAL_MANIFEST/train.jsonl" "$FORMAL_MANIFEST/val.jsonl" \ + --output-root "$ARTIFACTS/latent_cache" \ + --codec-sha256 "$hash" \ + --num-shards "$NPROC" +} + +run_formal() { + local cache_root="$ARTIFACTS/latent_cache/$(codec_sha)" + require_file "$cache_root/manifest_train.jsonl" + require_file "$cache_root/manifest_val.jsonl" + "$PYTHON" scripts/audit_robotwin_wam_data.py \ + --train-manifest "$cache_root/manifest_train.jsonl" \ + --val-manifest "$cache_root/manifest_val.jsonl" \ + --raw-summary "$FORMAL_MANIFEST/summary.json" \ + --cache-root / \ + --max-cache-checks 100 \ + --require-complete-summary \ + --report "$cache_root/preflight_audit.json" + show_gpu_coexistence + cd "$ROOT" + export ROBOTWIN_DATASET_ROOT="$DATASET_ROOT" + export MIRA_CODEC_CHECKPOINT="$CODEC_CHECKPOINT" + export MIRA_WAM_RAW_MANIFEST_DIR="$FORMAL_MANIFEST" + export MIRA_WAM_TRAIN_MANIFEST="$cache_root/manifest_train.jsonl" + export MIRA_WAM_VAL_MANIFEST="$cache_root/manifest_val.jsonl" + export MIRA_WAM_OUTPUT_DIR="$FORMAL_OUTPUT" + export SWANLAB_TOKEN_FILE="${SWANLAB_TOKEN_FILE:-$WORKSPACE/z_oranger/token.txt}" + export MIRA_LAUNCHER_PROCESS_NAME="syncnet_core_l" + exec "$PYTHON" scripts/syncnet_torchrun.py --standalone --nproc_per_node="$NPROC" \ + scripts/train_bihub_wam_world.py +} + +run_formal_pipeline() { + set_shell_process_name syncnet_core_p + prepare_formal_manifest + prepare_formal_text + prepare_formal_latents + run_formal +} + +continue_formal_pipeline() { + set_shell_process_name syncnet_core_p + require_file "$FORMAL_MANIFEST/train.jsonl" + require_file "$FORMAL_MANIFEST/val.jsonl" + require_file "$FORMAL_MANIFEST/summary.json" + if formal_latents_ready; then + echo "Complete content-addressed latent cache found; skipping ZIP/HDF5 preprocessing." + else + prepare_formal_latents + fi + run_formal +} + +case "${1:-}" in + prepare-smoke) prepare_smoke ;; + smoke) run_smoke ;; + tmux-smoke) + tmux -L "$TMUX_SOCKET" new-window -t "$TMUX_SESSION" -n core-smoke "cd '$ROOT' && export MIRA_WAM_OUTPUT_DIR='$SMOKE_OUTPUT' && exec -a syncnet_core_pipe bash scripts/launch_bihub_wam_world.sh smoke 2>&1 | tee -a '$LOG_ROOT/smoke.log'" + ;; + prepare-formal-manifest) prepare_formal_manifest ;; + prepare-formal-text) prepare_formal_text ;; + prepare-formal-latents) prepare_formal_latents ;; + formal-pipeline) run_formal_pipeline ;; + continue-formal-pipeline) continue_formal_pipeline ;; + train) run_formal ;; + tmux-train) + tmux -L "$TMUX_SOCKET" new-window -t "$TMUX_SESSION" -n core-train "cd '$ROOT' && export MIRA_WAM_OUTPUT_DIR='$FORMAL_OUTPUT' && exec -a syncnet_core_pipe bash scripts/launch_bihub_wam_world.sh train 2>&1 | tee -a '$LOG_ROOT/train.log'" + ;; + *) usage; exit 2 ;; +esac diff --git a/release-20261107/source/workspace_joint/mira/scripts/launch_joint_world_action.sh b/release-20261107/source/workspace_joint/mira/scripts/launch_joint_world_action.sh new file mode 100644 index 0000000000000000000000000000000000000000..e509a6a27740f0050e6e8711920d92f07c458931 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/launch_joint_world_action.sh @@ -0,0 +1,216 @@ +#!/usr/bin/env bash +set -euo pipefail +unset http_proxy https_proxy all_proxy ftp_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY FTP_PROXY +export NO_PROXY='*' no_proxy='*' +export CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:-6,7}" +export PYTHONPATH="$(cd "$(dirname "${BASH_SOURCE[0]}")/../src" && pwd)${PYTHONPATH:+:${PYTHONPATH}}" + +if [[ $# -lt 1 ]]; then + echo "usage: $0 /path/to/RoboTwin2.0 [additional train arguments]" >&2 + exit 2 +fi + +DATASET_ROOT="$(cd "$1" && pwd)" +shift +MIRA_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +PARENT_ROOT="$(cd "${MIRA_ROOT}/.." && pwd)" + +# A restored HF handoff has mira/, models/ and outputs/ as siblings. When invoked directly from +# the un-restored bundle's source/mira tree, extract only the two frozen runtime archives into a +# small asset workspace; no derived training cache is restored or used. +if [[ -d "${PARENT_ROOT}/models/Qwen3-VL-2B-Instruct" ]]; then + WORKSPACE_ROOT="${PARENT_ROOT}" + BUNDLE_ROOT="${HF_BUNDLE_ROOT:-}" +elif [[ -d "${PARENT_ROOT}/../archives" ]]; then + BUNDLE_ROOT="${HF_BUNDLE_ROOT:-$(cd "${PARENT_ROOT}/.." && pwd)}" + WORKSPACE_ROOT="${JOINT_ASSET_WORKSPACE:-${BUNDLE_ROOT}/.joint_assets}" + mkdir -p "${WORKSPACE_ROOT}" + for archive in qwen3-vl-2b-instruct.tar.zst codec-checkpoint-step125000.tar.zst; do + if [[ ! -s "${BUNDLE_ROOT}/archives/${archive}" ]]; then + echo "Missing HF asset archive: ${BUNDLE_ROOT}/archives/${archive}" >&2 + exit 2 + fi + marker="${WORKSPACE_ROOT}/.${archive}.extracted" + if [[ ! -e "${marker}" ]]; then + echo "Extracting frozen runtime asset ${archive}" + tar --zstd -xf "${BUNDLE_ROOT}/archives/${archive}" -C "${WORKSPACE_ROOT}" + touch "${marker}" + fi + done +else + echo "Cannot identify a restored workspace or HF bundle around ${MIRA_ROOT}" >&2 + exit 2 +fi + +if [[ -n "${MIRA_PYTHON:-}" ]]; then + PYTHON_BIN="${MIRA_PYTHON}" +elif [[ -x "${WORKSPACE_ROOT}/conda/envs/mira/bin/python" ]]; then + PYTHON_BIN="${WORKSPACE_ROOT}/conda/envs/mira/bin/python" +else + PYTHON_BIN="$(command -v python)" +fi + +if [[ ! -d "${DATASET_ROOT}/dataset" ]]; then + echo "RoboTwin dataset must contain dataset/*/*.zip: ${DATASET_ROOT}" >&2 + exit 2 +fi + +BASE_MANIFEST_DIR="${ROBOTWIN_MANIFEST_DIR:-${DATASET_ROOT}/mira_manifests}" +JOINT_MANIFEST_DIR="${JOINT_MANIFEST_DIR:-${BASE_MANIFEST_DIR}/joint_eval_language_v3}" +mkdir -p "${BASE_MANIFEST_DIR}" + +if [[ ! -s "${BASE_MANIFEST_DIR}/train.jsonl" || ! -s "${BASE_MANIFEST_DIR}/val.jsonl" ]]; then + "${PYTHON_BIN}" "${MIRA_ROOT}/scripts/build_robotwin_manifest.py" \ + --dataset-root "${DATASET_ROOT}" \ + --output-dir "${BASE_MANIFEST_DIR}" \ + --val-fraction 0.02 \ + --seed 2026 +fi + +if [[ ! -s "${JOINT_MANIFEST_DIR}/train.jsonl" \ + || ! -s "${JOINT_MANIFEST_DIR}/val.jsonl" \ + || ! -s "${JOINT_MANIFEST_DIR}/dataset_stats.json" ]]; then + if [[ -e "${JOINT_MANIFEST_DIR}" ]]; then + echo "Incomplete eval-language manifest: ${JOINT_MANIFEST_DIR}" >&2 + exit 2 + fi + SOURCE_MANIFEST_DIR="${BASE_MANIFEST_DIR}/joint_anchor_v2" + if [[ ! -s "${SOURCE_MANIFEST_DIR}/train.jsonl" \ + || ! -s "${SOURCE_MANIFEST_DIR}/val.jsonl" \ + || ! -s "${SOURCE_MANIFEST_DIR}/dataset_stats.json" ]]; then + mkdir -p "${SOURCE_MANIFEST_DIR}" + "${PYTHON_BIN}" "${MIRA_ROOT}/scripts/build_robotwin_wam_manifest.py" \ + --dataset-root "${DATASET_ROOT}" \ + --train-manifest "${BASE_MANIFEST_DIR}/train.jsonl" \ + --val-manifest "${BASE_MANIFEST_DIR}/val.jsonl" \ + --output-dir "${SOURCE_MANIFEST_DIR}" \ + --embodiment aloha-agilex --min-latents 1 + fi + "${PYTHON_BIN}" "${MIRA_ROOT}/scripts/build_joint_eval_language_manifest.py" \ + --source-manifest-dir "${SOURCE_MANIFEST_DIR}" \ + --dataset-root "${DATASET_ROOT}" \ + --output-dir "${JOINT_MANIFEST_DIR}" +fi + +if [[ "${JOINT_PREPARE_ONLY:-0}" == "1" ]]; then + echo "Prepared joint manifests at ${JOINT_MANIFEST_DIR}; no GPU process started." + exit 0 +fi + +WORLD_CHECKPOINT="${WORLD_CHECKPOINT:-${WORKSPACE_ROOT}/outputs/robotwin_bihub_world_v12_largebatch_remaining/main-checkpoint-25066}" +ACTION_CHECKPOINT="${ACTION_CHECKPOINT:-${WORKSPACE_ROOT}/outputs/robotwin_bihub_wam_v13_action_eval_aligned_continue4epoch/action-checkpoint-23016}" +if [[ ! -d "${WORLD_CHECKPOINT}/distributed" && -n "${BUNDLE_ROOT:-}" ]]; then + WORLD_CHECKPOINT="${BUNDLE_ROOT}/release-20260902/workspace/outputs/robotwin_bihub_world_v12_largebatch_remaining/main-checkpoint-25066" +fi +if [[ ! -d "${ACTION_CHECKPOINT}/distributed" && -n "${BUNDLE_ROOT:-}" ]]; then + ACTION_CHECKPOINT="${BUNDLE_ROOT}/release-20260902/workspace/outputs/robotwin_bihub_wam_v13_action_eval_aligned_continue4epoch/action-checkpoint-23016" +fi +CODEC_CHECKPOINT="${CODEC_CHECKPOINT:-${WORKSPACE_ROOT}/outputs/mira_robotwin_codec/checkpoint-125000/checkpoint.pth}" +QWEN_ROOT="${QWEN_ROOT:-${WORKSPACE_ROOT}/models/Qwen3-VL-2B-Instruct}" +OUTPUT_DIR="${OUTPUT_DIR:-${WORKSPACE_ROOT}/outputs/joint_eval_language_v3_rgb}" + +required=( + "${WORLD_CHECKPOINT}/trainer_state.json" + "${WORLD_CHECKPOINT}/distributed/.metadata" + "${ACTION_CHECKPOINT}/trainer_state.json" + "${ACTION_CHECKPOINT}/distributed/.metadata" + "${CODEC_CHECKPOINT}" + "${QWEN_ROOT}/config.json" +) +for path in "${required[@]}"; do + if [[ ! -s "${path}" ]]; then + echo "Required released asset is missing or still downloading: ${path}" >&2 + exit 2 + fi +done + +if [[ -n "${CUDA_VISIBLE_DEVICES:-}" ]]; then + IFS=',' read -r -a visible_devices <<< "${CUDA_VISIBLE_DEVICES}" + DEFAULT_NPROC="${#visible_devices[@]}" +else + DEFAULT_NPROC="$(nvidia-smi -L 2>/dev/null | wc -l || true)" +fi +NPROC_PER_NODE="${NPROC_PER_NODE:-${DEFAULT_NPROC}}" +if [[ "${NPROC_PER_NODE}" -lt 1 ]]; then + echo "No CUDA device found" >&2 + exit 2 +fi + +PROFILE_ARGS=() +if [[ "${NPROC_PER_NODE}" -eq 8 && "${H200_PROFILE:-0}" == "1" ]]; then + # Aggressive but practical starting point for 8 x H200 141GB. The final user arguments are + # appended after these values, so any individual setting remains directly overridable. + PROFILE_ARGS=( + --per-device-batch "${PER_DEVICE_BATCH:-4}" + --gradient-accumulation "${GRADIENT_ACCUMULATION:-1}" + --num-workers "${NUM_WORKERS:-8}" + --world-rollout-steps "${WORLD_ROLLOUT_STEPS:-10}" + ) +fi + +export PYTHONUNBUFFERED=1 +export TOKENIZERS_PARALLELISM=false +export HF_HUB_OFFLINE=1 +export TRANSFORMERS_OFFLINE=1 +export TORCH_NCCL_ASYNC_ERROR_HANDLING=1 +export OMP_NUM_THREADS="${OMP_NUM_THREADS:-4}" +export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}" + +if [[ -n "${TORCHRUN_NNODES:-}" ]]; then + : "${TORCHRUN_NODE_RANK:?multi-node launch requires TORCHRUN_NODE_RANK}" + : "${TORCHRUN_MASTER_ADDR:?multi-node launch requires TORCHRUN_MASTER_ADDR}" + : "${TORCHRUN_MASTER_PORT:?multi-node launch requires TORCHRUN_MASTER_PORT}" + DISTRIBUTED_ARGS=( + --nnodes="${TORCHRUN_NNODES}" + --nproc_per_node="${NPROC_PER_NODE}" + --node_rank="${TORCHRUN_NODE_RANK}" + --master_addr="${TORCHRUN_MASTER_ADDR}" + --master_port="${TORCHRUN_MASTER_PORT}" + ) +else + DISTRIBUTED_ARGS=(--standalone --nproc_per_node="${NPROC_PER_NODE}") +fi + +COMMAND=( + "${PYTHON_BIN}" -m torch.distributed.run + "${DISTRIBUTED_ARGS[@]}" + "${MIRA_ROOT}/scripts/train_joint_world_action.py" + "${DATASET_ROOT}" + --manifest-dir "${JOINT_MANIFEST_DIR}" + --world-checkpoint "${WORLD_CHECKPOINT}" + --action-checkpoint "${ACTION_CHECKPOINT}" + --codec-checkpoint "${CODEC_CHECKPOINT}" + --qwen-root "${QWEN_ROOT}" + --output-dir "${OUTPUT_DIR}" + --swanlab-mode "${SWANLAB_MODE:-online}" + --swanlab-project "${SWANLAB_PROJECT:-Multi_WAM}" + --swanlab-experiment-name "${SWANLAB_EXPERIMENT_NAME:-Joint-Eval-Language-V3}" + --swanlab-token-file "${SWANLAB_TOKEN_FILE:-${WORKSPACE_ROOT}/z_oranger/token.txt}" + "${PROFILE_ARGS[@]}" + "$@" +) + +echo "Dataset : ${DATASET_ROOT}" +echo "World checkpoint : ${WORLD_CHECKPOINT}" +echo "Action checkpoint: ${ACTION_CHECKPOINT}" +echo "Codec checkpoint : ${CODEC_CHECKPOINT}" +echo "Qwen root : ${QWEN_ROOT}" +echo "Output : ${OUTPUT_DIR}" +echo "GPU workers : ${NPROC_PER_NODE}" +echo "Python : ${PYTHON_BIN}" +if [[ "${#PROFILE_ARGS[@]}" -gt 0 ]]; then + echo "Hardware profile : 8xH200 (micro-batch=${PER_DEVICE_BATCH:-4}, accumulation=${GRADIENT_ACCUMULATION:-1}, workers/rank=${NUM_WORKERS:-8})" +else + echo "Hardware profile : generic trainer defaults" +fi +printf 'Launch command:' +printf ' %q' "${COMMAND[@]}" +printf '\n' +if [[ "${JOINT_DRY_RUN:-0}" == "1" ]]; then + echo "JOINT_DRY_RUN=1: command printed, no process started." + exit 0 +fi +# SwanLab Settings treats SWANLAB_PROJECT as a nested object and rejects the +# project name as a plain string. The CLI argument above carries the name. +unset SWANLAB_PROJECT +exec "${COMMAND[@]}" diff --git a/release-20261107/source/workspace_joint/mira/scripts/launch_world_v10_h1_50.sh b/release-20261107/source/workspace_joint/mira/scripts/launch_world_v10_h1_50.sh new file mode 100644 index 0000000000000000000000000000000000000000..c000c648e1efa5e21726e6d94bc7369367e3c549 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/launch_world_v10_h1_50.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +set -euo pipefail + +unset http_proxy https_proxy all_proxy ftp_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY FTP_PROXY NO_PROXY no_proxy +export NO_PROXY='*' +export no_proxy='*' +export HF_HUB_OFFLINE=1 +export TRANSFORMERS_OFFLINE=1 + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" +source /public/inz/.bashrc >/dev/null 2>&1 || true +conda activate multi-wam-mira +if [[ "${CONDA_PREFIX:-}" != "/public/inz/envs/multi-wam-mira" ]]; then + echo "Unexpected conda environment: ${CONDA_PREFIX:-unset}" >&2 + exit 2 +fi +PYTHON="$CONDA_PREFIX/bin/python" + +preflight() { + local config="$1" + local report="$2" + shift 2 + mkdir -p ../artifacts/world_v10_h1_50/reports + CUDA_VISIBLE_DEVICES="${MIRA_WV10_GPUS:-0,1,2,3,4,5,6,7}" \ + "$PYTHON" -m mira.training.world_v8.preflight \ + --config "$config" --report "$report" --ignore-gpu-headroom "$@" +} + +torchrun_v10() { + local config="$1" + CUDA_VISIBLE_DEVICES="${MIRA_WV10_GPUS:-0,1,2,3,4,5,6,7}" \ + MIRA_LAUNCHER_PROCESS_NAME=tagshotx_wv10l \ + "$PYTHON" scripts/syncnet_torchrun.py --standalone --nproc_per_node=8 \ + -m mira.training.world_v8.train --config "$config" +} + +case "${1:-}" in + preflight) + preflight configs/world_v10_h1_50/train.yaml ../artifacts/world_v10_h1_50/reports/preflight-formal.json --deep-source-load + ;; + smoke) + preflight configs/world_v10_h1_50/smoke.yaml ../artifacts/world_v10_h1_50/reports/preflight-smoke.json + torchrun_v10 configs/world_v10_h1_50/smoke.yaml + ;; + formal) + if [[ "${MIRA_WV10_ALLOW_FORMAL:-}" != "YES" ]]; then + echo 'Set MIRA_WV10_ALLOW_FORMAL=YES after smoke and GPU checks pass.' >&2 + exit 2 + fi + if pgrep -f '^tagshotx_wv10t[0-7]' >/dev/null; then + echo 'A World-v10 training process is already running.' >&2 + exit 3 + fi + preflight configs/world_v10_h1_50/train.yaml ../artifacts/world_v10_h1_50/reports/preflight-formal.json --deep-source-load + torchrun_v10 configs/world_v10_h1_50/train.yaml + ;; + *) + echo "usage: $0 {preflight|smoke|formal}" >&2 + exit 2 + ;; +esac diff --git a/release-20261107/source/workspace_joint/mira/scripts/launch_world_v11_continue30k.sh b/release-20261107/source/workspace_joint/mira/scripts/launch_world_v11_continue30k.sh new file mode 100644 index 0000000000000000000000000000000000000000..947afbb2765f8be495517d19b7c713e4eac01ab3 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/launch_world_v11_continue30k.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +set -euo pipefail + +unset http_proxy https_proxy all_proxy ftp_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY FTP_PROXY NO_PROXY no_proxy +export NO_PROXY='*' +export no_proxy='*' +export HF_HUB_OFFLINE=1 +export TRANSFORMERS_OFFLINE=1 + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" +if [[ -n "${MIRA_PYTHON:-}" ]]; then + PYTHON="$MIRA_PYTHON" +else + source "${MIRA_CONDA_BASHRC:-/public/inz/.bashrc}" >/dev/null 2>&1 || true + conda activate "${MIRA_CONDA_ENV:-multi-wam-mira}" + PYTHON="$CONDA_PREFIX/bin/python" +fi +[[ -x "$PYTHON" ]] || { echo "Missing executable Python: $PYTHON" >&2; exit 2; } +ARTIFACTS=../artifacts/world_v11_continue30k + +preflight() { + local config="$1" + local report="$2" + shift 2 + mkdir -p "$ARTIFACTS/reports" + CUDA_VISIBLE_DEVICES="${MIRA_WV11_GPUS:-0,1,2,3,4,5,6,7}" \ + "$PYTHON" -m mira.training.world_v8.preflight \ + --config "$config" --report "$report" --ignore-gpu-headroom "$@" +} + +torchrun_v11() { + local config="$1" + CUDA_VISIBLE_DEVICES="${MIRA_WV11_GPUS:-0,1,2,3,4,5,6,7}" \ + MIRA_LAUNCHER_PROCESS_NAME=filter_x_wv11l \ + "$PYTHON" scripts/syncnet_torchrun.py --standalone --nproc_per_node=8 \ + -m mira.training.world_v8.train --config "$config" +} + +case "${1:-}" in + preflight) + preflight configs/world_v11_continue30k/train.yaml "$ARTIFACTS/reports/preflight-formal.json" --deep-source-load + ;; + smoke) + preflight configs/world_v11_continue30k/smoke.yaml "$ARTIFACTS/reports/preflight-smoke.json" + torchrun_v11 configs/world_v11_continue30k/smoke.yaml + ;; + formal) + if [[ "${MIRA_WV11_ALLOW_FORMAL:-}" != "YES" ]]; then + echo 'Set MIRA_WV11_ALLOW_FORMAL=YES after smoke and GPU checks pass.' >&2 + exit 2 + fi + if pgrep -f '^filter_x_wv11t[0-7]' >/dev/null; then + echo 'A World-v11 training process is already running.' >&2 + exit 3 + fi + preflight configs/world_v11_continue30k/train.yaml "$ARTIFACTS/reports/preflight-formal.json" --deep-source-load + torchrun_v11 configs/world_v11_continue30k/train.yaml + ;; + *) + echo "usage: $0 {preflight|smoke|formal}" >&2 + exit 2 + ;; +esac diff --git a/release-20261107/source/workspace_joint/mira/scripts/launch_world_v12_eval_aligned.sh b/release-20261107/source/workspace_joint/mira/scripts/launch_world_v12_eval_aligned.sh new file mode 100644 index 0000000000000000000000000000000000000000..f383fde77cbac039dee65b9727635d65c67fa67a --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/launch_world_v12_eval_aligned.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash +set -euo pipefail + +unset http_proxy https_proxy all_proxy ftp_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY FTP_PROXY NO_PROXY no_proxy +export NO_PROXY='*' +export no_proxy='*' +export HF_HUB_OFFLINE=1 +export TRANSFORMERS_OFFLINE=1 + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" +if [[ -n "${MIRA_PYTHON:-}" ]]; then + PYTHON="$MIRA_PYTHON" +else + source "${MIRA_CONDA_BASHRC:-/public/inz/.bashrc}" >/dev/null 2>&1 || true + conda activate "${MIRA_CONDA_ENV:-multi-wam-mira}" + PYTHON="$CONDA_PREFIX/bin/python" +fi +[[ -x "$PYTHON" ]] || { echo "Missing executable Python: $PYTHON" >&2; exit 2; } +ARTIFACTS=../artifacts/world_v12_eval_aligned_epoch +CONFIG_ROOT=configs/world_v12_eval_aligned_epoch +TRAIN_MANIFEST=../artifacts/latent_cache/c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615/manifest_train.jsonl +QWEN_IDENTITY=../artifacts/world_v7/qwen_hidden_cache/qwen_hidden_cache_identity.json +CONTRACT="$ARTIFACTS/cache/sampling_contract.json" + +prepare() { + mkdir -p "$ARTIFACTS/cache" "$ARTIFACTS/reports" "$ARTIFACTS/logs" + "$PYTHON" -m mira.training.world_v8.build_v12_sampling_contract \ + --train-manifest "$TRAIN_MANIFEST" \ + --qwen-cache-identity "$QWEN_IDENTITY" \ + --output "$CONTRACT" +} + +preflight() { + local config="$1" + local report="$2" + shift 2 + prepare + CUDA_VISIBLE_DEVICES="${MIRA_WV12_GPUS:-0,1,2,3,4,5,6,7}" \ + "$PYTHON" -m mira.training.world_v8.preflight \ + --config "$config" --report "$report" "$@" +} + +torchrun_v12() { + local config="$1" + CUDA_VISIBLE_DEVICES="${MIRA_WV12_GPUS:-0,1,2,3,4,5,6,7}" \ + MIRA_LAUNCHER_PROCESS_NAME=filter_x_wv12l \ + "$PYTHON" scripts/syncnet_torchrun.py --standalone --nproc_per_node=8 \ + -m mira.training.world_v8.train --config "$config" +} + +case "${1:-}" in + prepare) + prepare + ;; + preflight) + preflight "$CONFIG_ROOT/train.yaml" "$ARTIFACTS/reports/preflight-formal.json" --deep-source-load + ;; + smoke) + preflight "$CONFIG_ROOT/smoke.yaml" "$ARTIFACTS/reports/preflight-smoke.json" + torchrun_v12 "$CONFIG_ROOT/smoke.yaml" + ;; + formal) + if [[ "${MIRA_WV12_ALLOW_FORMAL:-}" != "YES" ]]; then + echo 'Set MIRA_WV12_ALLOW_FORMAL=YES after smoke and GPU checks pass.' >&2 + exit 2 + fi + if pgrep -f '^filter_x_wv12t[0-7]' >/dev/null; then + echo 'A World-v12 training process is already running.' >&2 + exit 3 + fi + preflight "$CONFIG_ROOT/train.yaml" "$ARTIFACTS/reports/preflight-formal.json" --deep-source-load + torchrun_v12 "$CONFIG_ROOT/train.yaml" + ;; + *) + echo "usage: $0 {prepare|preflight|smoke|formal}" >&2 + exit 2 + ;; +esac diff --git a/release-20261107/source/workspace_joint/mira/scripts/launch_world_v12_largebatch_remaining.sh b/release-20261107/source/workspace_joint/mira/scripts/launch_world_v12_largebatch_remaining.sh new file mode 100644 index 0000000000000000000000000000000000000000..2795cbe1b6d01a1c3876ca2f33560be51d090aab --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/launch_world_v12_largebatch_remaining.sh @@ -0,0 +1,105 @@ +#!/usr/bin/env bash +set -euo pipefail + +unset http_proxy https_proxy all_proxy ftp_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY FTP_PROXY NO_PROXY no_proxy +export NO_PROXY='*' +export no_proxy='*' +export HF_HUB_OFFLINE=1 +export TRANSFORMERS_OFFLINE=1 + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" +if [[ -n "${MIRA_PYTHON:-}" ]]; then + PYTHON="$MIRA_PYTHON" +else + source "${MIRA_CONDA_BASHRC:-/public/inz/.bashrc}" >/dev/null 2>&1 || true + conda activate "${MIRA_CONDA_ENV:-multi-wam-mira}" + PYTHON="$CONDA_PREFIX/bin/python" +fi +[[ -x "$PYTHON" ]] || { echo "Missing executable Python: $PYTHON" >&2; exit 2; } +CONFIG_ROOT="${MIRA_WV12_CONFIG_ROOT:-configs/world_v12_largebatch_remaining}" +ARTIFACTS="${MIRA_WV12_ARTIFACTS:-../artifacts/world_v12_largebatch_remaining}" +PROCESS_PREFIX="${MIRA_WV12_PROCESS_PREFIX:-filter_x_wv12b}" +LAUNCHER_PROCESS_NAME="${MIRA_WV12_LAUNCHER_NAME:-filter_x_wv12bl}" +TRAIN_MODULE="${MIRA_WV12_TRAIN_MODULE:-mira.training.world_v8.train}" +RANK_PROCESS_PATTERN="${MIRA_WV12_RANK_PATTERN:-^${PROCESS_PREFIX}t[0-7]}" +NPROC="${MIRA_WV12_NPROC:-8}" + +torchrun_v12() { + local config="$1" + shift + if [[ "${MIRA_WV12_PLAIN_LAUNCH:-0}" == 1 ]]; then + CUDA_VISIBLE_DEVICES="${MIRA_WV12_GPUS:-0,1,2,3,4,5,6,7}" \ + python -m torch.distributed.run --standalone --nproc_per_node="$NPROC" \ + -m "$TRAIN_MODULE" --config "$config" \ + "experiment.process_prefix=${PROCESS_PREFIX}" "$@" + else + CUDA_VISIBLE_DEVICES="${MIRA_WV12_GPUS:-0,1,2,3,4,5,6,7}" \ + MIRA_LAUNCHER_PROCESS_NAME="$LAUNCHER_PROCESS_NAME" \ + "$PYTHON" scripts/syncnet_torchrun.py --standalone --nproc_per_node="$NPROC" \ + -m "$TRAIN_MODULE" --config "$config" \ + "experiment.process_prefix=${PROCESS_PREFIX}" "$@" + fi +} + +case "${1:-}" in + preflight) + mkdir -p "$ARTIFACTS/reports" "$ARTIFACTS/logs" + CUDA_VISIBLE_DEVICES="${MIRA_WV12_GPUS:-0,1,2,3,4,5,6,7}" \ + "$PYTHON" -m mira.training.world_v8.preflight \ + --config "$CONFIG_ROOT/train.yaml" \ + --report "$ARTIFACTS/reports/preflight-formal.json" \ + --deep-source-load + ;; + smoke) + batch="${2:?usage: $0 smoke PER_DEVICE_BATCH [fsdp2_full_shard|ddp]}" + strategy="${3:-fsdp2_full_shard}" + global=$((NPROC * batch)) + torchrun_v12 "$CONFIG_ROOT/smoke.yaml" \ + "experiment.output_root=../outputs/world_v12_largebatch_smoke_${strategy}_bs${batch}" \ + "distributed.per_device_batch=${batch}" \ + "distributed.effective_global_batch=${global}" \ + "distributed.strategy=${strategy}" + ;; + long-smoke) + batch="${2:-26}" + global=$((NPROC * batch)) + torchrun_v12 "$CONFIG_ROOT/long_smoke.yaml" \ + "experiment.output_root=../outputs/world_v12_largebatch_long_smoke_ddp_bs${batch}" \ + "distributed.per_device_batch=${batch}" \ + "distributed.effective_global_batch=${global}" + ;; + formal) + if [[ "${MIRA_WV12_ALLOW_FORMAL:-}" != "YES" ]]; then + echo 'Set MIRA_WV12_ALLOW_FORMAL=YES after smoke and preflight pass.' >&2 + exit 2 + fi + active_rank_pid=false + while read -r candidate_pid; do + [[ -n "$candidate_pid" ]] || continue + candidate_state="$(ps -o stat= -p "$candidate_pid" 2>/dev/null || true)" + candidate_comm="$(ps -o comm= -p "$candidate_pid" 2>/dev/null || true)" + if [[ -n "$candidate_state" && "$candidate_state" != Z* \ + && ("$candidate_comm" == python* \ + || "$candidate_comm" == "$PROCESS_PREFIX"*) ]]; then + active_rank_pid=true + break + fi + done < <(pgrep -f "$RANK_PROCESS_PATTERN" || true) + if [[ "$active_rank_pid" == true ]]; then + echo 'A large-batch World-v12 continuation is already running.' >&2 + exit 3 + fi + mkdir -p "$ARTIFACTS/reports" "$ARTIFACTS/logs" + CUDA_VISIBLE_DEVICES="${MIRA_WV12_GPUS:-0,1,2,3,4,5,6,7}" \ + "$PYTHON" -m mira.training.world_v8.preflight \ + --config "$CONFIG_ROOT/train.yaml" \ + --report "$ARTIFACTS/reports/preflight-formal.json" \ + --deep-source-load + torchrun_v12 "$CONFIG_ROOT/train.yaml" + ;; + *) + echo "usage: $0 {preflight|smoke PER_DEVICE_BATCH [fsdp2_full_shard|ddp]|long-smoke|formal}" >&2 + exit 2 + ;; +esac diff --git a/release-20261107/source/workspace_joint/mira/scripts/launch_world_v6.sh b/release-20261107/source/workspace_joint/mira/scripts/launch_world_v6.sh new file mode 100644 index 0000000000000000000000000000000000000000..ec7e711837ce11cfdb99c171e56f05aaaac4c580 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/launch_world_v6.sh @@ -0,0 +1,322 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Every v6 subprocess uses a direct connection. Training/cache phases are additionally offline. +unset http_proxy https_proxy all_proxy ftp_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY FTP_PROXY NO_PROXY no_proxy +export NO_PROXY='*' +export no_proxy='*' + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +WORKSPACE="$(cd "$ROOT/.." && pwd)" +PYTHON="${MIRA_PYTHON:-/private/software/conda/envs/mira/bin/python}" +SMOKE_GPUS="6,7" +SMOKE_NPROC=2 +LOG_ROOT="$WORKSPACE/outputs/world_v6_logs" +mkdir -p "$LOG_ROOT" + +set_shell_name() { + printf '%s' "$1" >"/proc/$$/comm" 2>/dev/null || true +} + +offline() { + export HF_HUB_OFFLINE=1 + export TRANSFORMERS_OFFLINE=1 +} + +online_download() { + unset HF_HUB_OFFLINE TRANSFORMERS_OFFLINE +} + +torchrun_v6() { + local gpus="$1" + local nproc="$2" + local rank_prefix="$3" + shift 3 + CUDA_VISIBLE_DEVICES="$gpus" \ + MIRA_LAUNCHER_PROCESS_NAME="${MIRA_V6_PROCESS_PREFIX:-syncnet_v6}_l" \ + MIRA_V6_RANK_PREFIX="$rank_prefix" \ + "$PYTHON" scripts/syncnet_torchrun.py --standalone --nproc_per_node="$nproc" "$@" +} + +require_smoke_headroom() { + "$PYTHON" - "$SMOKE_GPUS" <<'PY' +import subprocess, sys +requested = [int(value) for value in sys.argv[1].split(',')] +rows = subprocess.check_output( + ['nvidia-smi', '--query-gpu=index,memory.free', '--format=csv,noheader,nounits'], + text=True, +) +free = {int(row.split(',')[0]): int(row.split(',')[1]) for row in rows.splitlines()} +minimum_mib = 20 * 1024 +bad = {gpu: free.get(gpu, 0) for gpu in requested if free.get(gpu, 0) < minimum_mib} +if bad: + raise SystemExit(f'World v6 smoke requires >=20GiB free on GPUs 6,7; got {bad}') +print('World v6 smoke GPU headroom:', {gpu: free[gpu] for gpu in requested}) +PY +} + +prepare_qwen() { + online_download + cd "$ROOT" + "$PYTHON" -m mira.training.world_v6.prepare_qwen \ + --repo Qwen/Qwen3-VL-2B-Instruct \ + --revision 89644892e4d85e24eaac8bacfd4f463576704203 \ + --local-dir "$WORKSPACE/models/Qwen3-VL-2B-Instruct" \ + --identity-file "$WORKSPACE/artifacts/world_v6/identities/qwen_identity.json" +} + +prepare_smoke() { + offline + cd "$ROOT" + "$PYTHON" -m mira.training.world_v6.build_window_manifest \ + --train-source-manifest "$WORKSPACE/artifacts/latent_cache/c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615/manifest_train.jsonl" \ + --val-source-manifest "$WORKSPACE/artifacts/latent_cache/c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615/manifest_val.jsonl" \ + --output-root "$WORKSPACE/artifacts/world_v6_smoke/windows" \ + --max-windows-per-split 8 + "$PYTHON" -m mira.training.world_v6.select_source_world \ + --checkpoint "$WORKSPACE/outputs/robotwin_3view_world_1b/checkpoint-80000" \ + --import-selection "$WORKSPACE/artifacts/action_stage/world/world_selection.json" \ + --output "$WORKSPACE/artifacts/world_v6/source/v5_source_selection.json" + if [[ ! -s "$WORKSPACE/artifacts/world_v6/migration/world_v6_initialized.safetensors" ]]; then + "$PYTHON" -m mira.training.world_v6.migrate_checkpoint \ + --config configs/world_v6/smoke_bootstrap.yaml + fi +} + +bootstrap_smoke() { + offline + require_smoke_headroom + cd "$ROOT" + "$PYTHON" -m mira.training.world_v6.preflight \ + --config configs/world_v6/smoke_bootstrap.yaml \ + --phase bootstrap \ + --report "$WORKSPACE/artifacts/world_v6_smoke/reports/preflight-bootstrap.json" + torchrun_v6 "$SMOKE_GPUS" "$SMOKE_NPROC" b \ + -m mira.training.world_v6.train --config configs/world_v6/smoke_bootstrap.yaml +} + +select_smoke_anchor() { + offline + cd "$ROOT" + "$PYTHON" -m mira.training.world_v6.select_anchor_checkpoint \ + --config configs/world_v6/smoke_bootstrap.yaml --allow-smoke-last +} + +cache_smoke() { + offline + require_smoke_headroom + cd "$ROOT" + "$PYTHON" -m mira.training.world_v6.preflight \ + --config configs/world_v6/smoke_cache.yaml \ + --phase cache \ + --report "$WORKSPACE/artifacts/world_v6_smoke/reports/preflight-cache.json" + torchrun_v6 "$SMOKE_GPUS" "$SMOKE_NPROC" c \ + -m mira.training.world_v6.build_anchor_cache --config configs/world_v6/smoke_cache.yaml + CUDA_VISIBLE_DEVICES=6 "$PYTHON" -m mira.training.world_v6.audit_anchor_cache \ + --config configs/world_v6/smoke_cache.yaml \ + --report "$WORKSPACE/artifacts/world_v6_smoke/reports/anchor-cache-audit.json" +} + +main_smoke() { + offline + require_smoke_headroom + cd "$ROOT" + "$PYTHON" -m mira.training.world_v6.preflight \ + --config configs/world_v6/smoke_train.yaml \ + --phase main \ + --report "$WORKSPACE/artifacts/world_v6_smoke/reports/preflight-main.json" + torchrun_v6 "$SMOKE_GPUS" "$SMOKE_NPROC" r \ + -m mira.training.world_v6.train --config configs/world_v6/smoke_train.yaml +} + +eval_smoke() { + offline + require_smoke_headroom + cd "$ROOT" + "$PYTHON" -m mira.training.world_v6.preflight \ + --config configs/world_v6/smoke_eval.yaml \ + --phase eval \ + --report "$WORKSPACE/artifacts/world_v6_smoke/reports/preflight-eval.json" + torchrun_v6 "$SMOKE_GPUS" "$SMOKE_NPROC" e \ + -m mira.training.world_v6.eval_world_v6 --config configs/world_v6/smoke_eval.yaml + for branch in online ema; do + CUDA_VISIBLE_DEVICES=6 "$PYTHON" scripts/eval_bihub_wam_offline.py \ + --case-root "$WORKSPACE/outputs/world_v6_smoke/eval/fixed_cases/$branch" \ + --output-dir "$WORKSPACE/outputs/world_v6_smoke/eval/decoded/$branch" \ + --codec-checkpoint "$WORKSPACE/outputs/mira_robotwin_codec/checkpoint-125000/checkpoint.pth" \ + --decode-missing --latest-only + done +} + +qwen_contract_smoke() { + offline + require_smoke_headroom + cd "$ROOT" + CUDA_VISIBLE_DEVICES=6 "$PYTHON" -m mira.training.world_v6.validate_qwen_contract \ + --config configs/world_v6/smoke_bootstrap.yaml \ + --report "$WORKSPACE/artifacts/world_v6_smoke/reports/qwen-contract.json" +} + +pipeline_smoke() { + set_shell_name syncnet_v6_p + prepare_smoke + qwen_contract_smoke + bootstrap_smoke + select_smoke_anchor + cache_smoke + main_smoke + eval_smoke +} + +prepare_formal() { + offline + cd "$ROOT" + "$PYTHON" -m mira.training.world_v6.build_window_manifest \ + --train-source-manifest "$WORKSPACE/artifacts/latent_cache/c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615/manifest_train.jsonl" \ + --val-source-manifest "$WORKSPACE/artifacts/latent_cache/c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615/manifest_val.jsonl" \ + --output-root "$WORKSPACE/artifacts/world_v6/windows" + "$PYTHON" -m mira.training.world_v6.select_source_world \ + --checkpoint "$WORKSPACE/outputs/robotwin_3view_world_1b/checkpoint-80000" \ + --import-selection "$WORKSPACE/artifacts/action_stage/world/world_selection.json" \ + --output "$WORKSPACE/artifacts/world_v6/source/v5_source_selection.json" + if [[ ! -s "$WORKSPACE/artifacts/world_v6/migration/world_v6_initialized.safetensors" ]]; then + "$PYTHON" -m mira.training.world_v6.migrate_checkpoint --config configs/world_v6/bootstrap.yaml + fi + "$PYTHON" -m mira.training.world_v6.preflight \ + --config configs/world_v6/bootstrap.yaml --phase bootstrap +} + +prepare_overfit64() { + offline + cd "$ROOT" + "$PYTHON" -m mira.training.world_v6.build_window_manifest \ + --train-source-manifest "$WORKSPACE/artifacts/latent_cache/c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615/manifest_train.jsonl" \ + --val-source-manifest "$WORKSPACE/artifacts/latent_cache/c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615/manifest_val.jsonl" \ + --output-root "$WORKSPACE/artifacts/world_v6_overfit64/windows" \ + --max-windows-per-split 64 +} + +require_formal_authorization() { + if [[ "${MIRA_V6_ALLOW_FORMAL:-}" != "YES" ]]; then + echo 'Formal v6 launch is guarded on this shared machine. Set MIRA_V6_ALLOW_FORMAL=YES explicitly.' >&2 + exit 2 + fi +} + +formal_bootstrap() { + require_formal_authorization + offline + cd "$ROOT" + "$PYTHON" -m mira.training.world_v6.preflight --config configs/world_v6/bootstrap.yaml --phase bootstrap + torchrun_v6 "${MIRA_V6_GPUS:-0,1,2,3,4,5,6,7}" 8 b \ + -m mira.training.world_v6.train --config configs/world_v6/bootstrap.yaml +} + +select_formal_anchor() { + require_formal_authorization + offline + cd "$ROOT" + "$PYTHON" -m mira.training.world_v6.select_anchor_checkpoint \ + --config configs/world_v6/bootstrap.yaml +} + +overfit64() { + require_formal_authorization + offline + cd "$ROOT" + prepare_overfit64 + "$PYTHON" -m mira.training.world_v6.preflight --config configs/world_v6/overfit64.yaml --phase bootstrap + torchrun_v6 "${MIRA_V6_GPUS:-0,1,2,3,4,5,6,7}" 8 b \ + -m mira.training.world_v6.train --config configs/world_v6/overfit64.yaml +} + +canary_bootstrap() { + require_formal_authorization + offline + cd "$ROOT" + "$PYTHON" -m mira.training.world_v6.preflight --config configs/world_v6/canary_bootstrap.yaml --phase bootstrap + torchrun_v6 "${MIRA_V6_GPUS:-0,1,2,3,4,5,6,7}" 8 b \ + -m mira.training.world_v6.train --config configs/world_v6/canary_bootstrap.yaml +} + +formal_cache() { + require_formal_authorization + offline + cd "$ROOT" + "$PYTHON" -m mira.training.world_v6.preflight --config configs/world_v6/cache.yaml --phase cache + torchrun_v6 "${MIRA_V6_GPUS:-0,1,2,3,4,5,6,7}" 8 c \ + -m mira.training.world_v6.build_anchor_cache --config configs/world_v6/cache.yaml + CUDA_VISIBLE_DEVICES="${MIRA_V6_AUDIT_GPU:-0}" "$PYTHON" \ + -m mira.training.world_v6.audit_anchor_cache --config configs/world_v6/cache.yaml +} + +formal_main() { + require_formal_authorization + offline + cd "$ROOT" + "$PYTHON" -m mira.training.world_v6.preflight --config configs/world_v6/train.yaml --phase main + torchrun_v6 "${MIRA_V6_GPUS:-0,1,2,3,4,5,6,7}" 8 r \ + -m mira.training.world_v6.train --config configs/world_v6/train.yaml +} + +canary_main() { + require_formal_authorization + offline + cd "$ROOT" + "$PYTHON" -m mira.training.world_v6.preflight --config configs/world_v6/canary_train.yaml --phase main + torchrun_v6 "${MIRA_V6_GPUS:-0,1,2,3,4,5,6,7}" 8 r \ + -m mira.training.world_v6.train --config configs/world_v6/canary_train.yaml +} + +formal_eval() { + require_formal_authorization + offline + cd "$ROOT" + "$PYTHON" -m mira.training.world_v6.preflight --config configs/world_v6/eval.yaml --phase eval + torchrun_v6 "${MIRA_V6_GPUS:-0,1,2,3,4,5,6,7}" 8 e \ + -m mira.training.world_v6.eval_world_v6 --config configs/world_v6/eval.yaml + for branch in online ema; do + CUDA_VISIBLE_DEVICES="${MIRA_V6_AUDIT_GPU:-0}" "$PYTHON" scripts/eval_bihub_wam_offline.py \ + --case-root "$WORKSPACE/outputs/robotwin_bihub_world_v6_eval/fixed_cases/$branch" \ + --output-dir "$WORKSPACE/outputs/robotwin_bihub_world_v6_eval/decoded/$branch" \ + --codec-checkpoint "$WORKSPACE/outputs/mira_robotwin_codec/checkpoint-125000/checkpoint.pth" \ + --decode-missing --latest-only + done +} + +clean_smoke() { + for path in "$WORKSPACE/outputs/world_v6_smoke" "$WORKSPACE/artifacts/world_v6_smoke"; do + if [[ -d "$path" ]]; then + find "$path" -mindepth 1 -delete + rmdir "$path" 2>/dev/null || true + fi + done +} + +usage() { + echo "usage: $0 {prepare-qwen|prepare-smoke|qwen-contract-smoke|bootstrap-smoke|select-smoke-anchor|cache-smoke|main-smoke|eval-smoke|pipeline-smoke|prepare-formal|prepare-overfit64|overfit64|canary-bootstrap|formal-bootstrap|select-formal-anchor|formal-cache|canary-main|formal-main|formal-eval|clean-smoke}" +} + +case "${1:-}" in + prepare-qwen) prepare_qwen ;; + prepare-smoke) prepare_smoke ;; + qwen-contract-smoke) qwen_contract_smoke ;; + bootstrap-smoke) bootstrap_smoke ;; + select-smoke-anchor) select_smoke_anchor ;; + cache-smoke) cache_smoke ;; + main-smoke) main_smoke ;; + eval-smoke) eval_smoke ;; + pipeline-smoke) pipeline_smoke ;; + prepare-formal) prepare_formal ;; + prepare-overfit64) prepare_overfit64 ;; + overfit64) overfit64 ;; + canary-bootstrap) canary_bootstrap ;; + formal-bootstrap) formal_bootstrap ;; + select-formal-anchor) select_formal_anchor ;; + formal-cache) formal_cache ;; + canary-main) canary_main ;; + formal-main) formal_main ;; + formal-eval) formal_eval ;; + clean-smoke) clean_smoke ;; + *) usage; exit 2 ;; +esac diff --git a/release-20261107/source/workspace_joint/mira/scripts/launch_world_v7.sh b/release-20261107/source/workspace_joint/mira/scripts/launch_world_v7.sh new file mode 100644 index 0000000000000000000000000000000000000000..387cde0e4c317570f6af3c6b8e5a9899a34a8112 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/launch_world_v7.sh @@ -0,0 +1,113 @@ +#!/usr/bin/env bash +set -euo pipefail + +unset http_proxy https_proxy all_proxy ftp_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY FTP_PROXY NO_PROXY no_proxy +export NO_PROXY='*' +export no_proxy='*' +export HF_HUB_OFFLINE=1 +export TRANSFORMERS_OFFLINE=1 + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" + +# The shared bashrc initializes conda successfully but may return a non-zero +# status in non-interactive tmux shells because of unrelated nvm/npm settings. +if [[ -n "${MIRA_PYTHON:-}" ]]; then + PYTHON="$MIRA_PYTHON" +else + source "${MIRA_CONDA_BASHRC:-/public/inz/.bashrc}" >/dev/null 2>&1 || true + conda activate "${MIRA_CONDA_ENV:-multi-wam-mira}" + PYTHON="$CONDA_PREFIX/bin/python" +fi +[[ -x "$PYTHON" ]] || { echo "Missing executable Python: $PYTHON" >&2; exit 2; } + +require_formal_authorization() { + if [[ "${MIRA_WV7_ALLOW_FORMAL:-}" != "YES" ]]; then + echo 'Set MIRA_WV7_ALLOW_FORMAL=YES to launch the formal World v7 cache.' >&2 + exit 2 + fi +} + +formal_cache() { + require_formal_authorization + CUDA_VISIBLE_DEVICES="${MIRA_WV7_GPUS:-0,1,2,3,4,5,6,7}" \ + MIRA_LAUNCHER_PROCESS_NAME=tagshotx_wv7_l \ + "$PYTHON" scripts/syncnet_torchrun.py --standalone --nproc_per_node=8 \ + -m mira.training.world_v7.build_qwen_hidden_cache \ + --train-source-manifest ../artifacts/latent_cache/c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615/manifest_train.jsonl \ + --val-source-manifest ../artifacts/latent_cache/c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615/manifest_val.jsonl \ + --dataset-root ../datasets/RoboTwin2.0 \ + --extracted-rgb-root ../artifacts/world_v6/extracted_rgb_episodes \ + --qwen-root ../models/Qwen3-VL-2B-Instruct \ + --qwen-identity ../artifacts/world_v6/identities/qwen_identity.json \ + --output-root ../artifacts/world_v7/qwen_hidden_cache \ + --batch-size "${MIRA_WV7_CACHE_BATCH:-2}" \ + --num-workers "${MIRA_WV7_CACHE_WORKERS:-0}" \ + --prefetch-factor 2 \ + --payload-cache-size 4 \ + --chunk-rows 512 +} + +resume_val_cache() { + require_formal_authorization + CUDA_VISIBLE_DEVICES="${MIRA_WV7_GPUS:-0,1,2,3,4,5,6,7}" \ + MIRA_LAUNCHER_PROCESS_NAME=tagshotx_wv7_l \ + "$PYTHON" scripts/syncnet_torchrun.py --standalone --nproc_per_node=8 \ + -m mira.training.world_v7.build_qwen_hidden_cache \ + --train-source-manifest ../artifacts/latent_cache/c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615/manifest_train.jsonl \ + --val-source-manifest ../artifacts/latent_cache/c07fedc40214687438d50db4aef416ed91a3f91aeaeb3435623a74d61f7ce615/manifest_val.jsonl \ + --dataset-root ../datasets/RoboTwin2.0 \ + --extracted-rgb-root ../artifacts/world_v6/extracted_rgb_episodes \ + --qwen-root ../models/Qwen3-VL-2B-Instruct \ + --qwen-identity ../artifacts/world_v6/identities/qwen_identity.json \ + --output-root ../artifacts/world_v7/qwen_hidden_cache \ + --batch-size "${MIRA_WV7_CACHE_BATCH:-2}" \ + --num-workers "${MIRA_WV7_CACHE_WORKERS:-0}" \ + --prefetch-factor 2 \ + --payload-cache-size 4 \ + --chunk-rows 512 \ + --splits val +} + +torchrun_v7() { + local config="$1" + CUDA_VISIBLE_DEVICES="${MIRA_WV7_GPUS:-0,1,2,3,4,5,6,7}" \ + MIRA_LAUNCHER_PROCESS_NAME=tagshotx_wv7_l \ + "$PYTHON" scripts/syncnet_torchrun.py --standalone --nproc_per_node=8 \ + -m mira.training.world_v7.train --config "$config" +} + +preflight() { + local config="$1" + local report="$2" + mkdir -p ../artifacts/world_v7/reports + CUDA_VISIBLE_DEVICES="${MIRA_WV7_GPUS:-0,1,2,3,4,5,6,7}" \ + "$PYTHON" -m mira.training.world_v7.preflight \ + --config "$config" --report "$report" +} + +smoke_train() { + require_formal_authorization + preflight configs/world_v7/smoke.yaml ../artifacts/world_v7/reports/preflight-smoke.json + torchrun_v7 configs/world_v7/smoke.yaml +} + +formal_train() { + require_formal_authorization + if pgrep -f '[m]ira.training.world_v7.build_qwen_hidden_cache' >/dev/null; then + echo 'World v7 cache is still running; formal training refuses concurrent cache mutation.' >&2 + exit 3 + fi + preflight configs/world_v7/train.yaml ../artifacts/world_v7/reports/preflight-formal.json + torchrun_v7 configs/world_v7/train.yaml +} + +case "${1:-}" in + formal-cache) formal_cache ;; + resume-val-cache) resume_val_cache ;; + preflight-smoke) preflight configs/world_v7/smoke.yaml ../artifacts/world_v7/reports/preflight-smoke.json ;; + smoke-train) smoke_train ;; + preflight-formal) preflight configs/world_v7/train.yaml ../artifacts/world_v7/reports/preflight-formal.json ;; + formal-train) formal_train ;; + *) echo "usage: $0 {formal-cache|resume-val-cache|preflight-smoke|smoke-train|preflight-formal|formal-train}" >&2; exit 2 ;; +esac diff --git a/release-20261107/source/workspace_joint/mira/scripts/launch_world_v8.sh b/release-20261107/source/workspace_joint/mira/scripts/launch_world_v8.sh new file mode 100644 index 0000000000000000000000000000000000000000..1c35711effea760e25a97b6a9427765236a20876 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/launch_world_v8.sh @@ -0,0 +1,92 @@ +#!/usr/bin/env bash +set -euo pipefail + +unset http_proxy https_proxy all_proxy ftp_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY FTP_PROXY NO_PROXY no_proxy +export NO_PROXY='*' +export no_proxy='*' +export HF_HUB_OFFLINE=1 +export TRANSFORMERS_OFFLINE=1 + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" +source /public/inz/.bashrc >/dev/null 2>&1 || true +conda activate multi-wam-mira +if [[ "${CONDA_PREFIX:-}" != "/public/inz/envs/multi-wam-mira" ]]; then + echo "Unexpected conda environment: ${CONDA_PREFIX:-unset}" >&2 + exit 2 +fi +PYTHON="$CONDA_PREFIX/bin/python" + +require_formal_authorization() { + if [[ "${MIRA_WV8_ALLOW_FORMAL:-}" != "YES" ]]; then + echo 'Set MIRA_WV8_ALLOW_FORMAL=YES only after GPU availability is confirmed.' >&2 + exit 2 + fi +} + +preflight() { + local config="$1" + local report="$2" + shift 2 + mkdir -p ../artifacts/world_v8/reports + CUDA_VISIBLE_DEVICES="${MIRA_WV8_GPUS:-0,1,2,3,4,5,6,7}" \ + "$PYTHON" -m mira.training.world_v8.preflight \ + --config "$config" --report "$report" "$@" +} + +torchrun_v8() { + local config="$1" + shift + CUDA_VISIBLE_DEVICES="${MIRA_WV8_GPUS:-0,1,2,3,4,5,6,7}" \ + MIRA_LAUNCHER_PROCESS_NAME=tagshotx_wv8_l \ + "$PYTHON" scripts/syncnet_torchrun.py --standalone --nproc_per_node=8 \ + -m mira.training.world_v8.train --config "$config" "$@" +} + +static_preflight() { + preflight \ + configs/world_v8/train.yaml \ + ../artifacts/world_v8/reports/preflight-static.json \ + --ignore-gpu-headroom +} + +deep_source_audit() { + preflight \ + configs/world_v8/train.yaml \ + ../artifacts/world_v8/reports/preflight-source-online.json \ + --ignore-gpu-headroom \ + --deep-source-load +} + +smoke_train() { + preflight configs/world_v8/smoke.yaml ../artifacts/world_v8/reports/preflight-smoke.json + torchrun_v8 configs/world_v8/smoke.yaml +} + +smoke_resume() { + preflight \ + configs/world_v8/smoke.yaml \ + ../artifacts/world_v8/reports/preflight-smoke-resume.json \ + runtime.max_steps=3 + torchrun_v8 configs/world_v8/smoke.yaml runtime.max_steps=3 +} + +formal_train() { + require_formal_authorization + if pgrep -f '[m]ira.training.world_v8.train' >/dev/null; then + echo 'A World v8 training process is already running.' >&2 + exit 3 + fi + preflight configs/world_v8/train.yaml ../artifacts/world_v8/reports/preflight-formal.json + torchrun_v8 configs/world_v8/train.yaml +} + +case "${1:-}" in + preflight-static) static_preflight ;; + audit-source-online) deep_source_audit ;; + smoke-train) smoke_train ;; + smoke-resume) smoke_resume ;; + preflight-formal) preflight configs/world_v8/train.yaml ../artifacts/world_v8/reports/preflight-formal.json ;; + formal-train) formal_train ;; + *) echo "usage: $0 {preflight-static|audit-source-online|smoke-train|smoke-resume|preflight-formal|formal-train}" >&2; exit 2 ;; +esac diff --git a/release-20261107/source/workspace_joint/mira/scripts/launch_world_v9_episode_start.sh b/release-20261107/source/workspace_joint/mira/scripts/launch_world_v9_episode_start.sh new file mode 100644 index 0000000000000000000000000000000000000000..e9920782cd0434bd2b820767bc8196b7980d1261 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/launch_world_v9_episode_start.sh @@ -0,0 +1,96 @@ +#!/usr/bin/env bash +set -euo pipefail + +unset http_proxy https_proxy all_proxy ftp_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY FTP_PROXY NO_PROXY no_proxy +export NO_PROXY='*' +export no_proxy='*' +export HF_HUB_OFFLINE=1 +export TRANSFORMERS_OFFLINE=1 + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" +source /public/inz/.bashrc >/dev/null 2>&1 || true +conda activate multi-wam-mira +if [[ "${CONDA_PREFIX:-}" != "/public/inz/envs/multi-wam-mira" ]]; then + echo "Unexpected conda environment: ${CONDA_PREFIX:-unset}" >&2 + exit 2 +fi +PYTHON="$CONDA_PREFIX/bin/python" + +require_formal_authorization() { + if [[ "${MIRA_WV9_ALLOW_FORMAL:-}" != "YES" ]]; then + echo 'Set MIRA_WV9_ALLOW_FORMAL=YES only after smoke and GPU checks pass.' >&2 + exit 2 + fi +} + +preflight() { + local config="$1" + local report="$2" + shift 2 + mkdir -p ../artifacts/world_v9_episode_start/reports + CUDA_VISIBLE_DEVICES="${MIRA_WV9_GPUS:-0,1,2,3,4,5,6,7}" \ + "$PYTHON" -m mira.training.world_v8.preflight \ + --config "$config" --report "$report" "$@" +} + +torchrun_v9() { + local config="$1" + shift + CUDA_VISIBLE_DEVICES="${MIRA_WV9_GPUS:-0,1,2,3,4,5,6,7}" \ + MIRA_LAUNCHER_PROCESS_NAME=tagshotx_wv9_l \ + "$PYTHON" scripts/syncnet_torchrun.py --standalone --nproc_per_node=8 \ + -m mira.training.world_v8.train --config "$config" "$@" +} + +static_preflight() { + preflight \ + configs/world_v9_episode_start/train.yaml \ + ../artifacts/world_v9_episode_start/reports/preflight-static.json \ + --ignore-gpu-headroom +} + +deep_source_audit() { + preflight \ + configs/world_v9_episode_start/train.yaml \ + ../artifacts/world_v9_episode_start/reports/preflight-source-online.json \ + --ignore-gpu-headroom \ + --deep-source-load +} + +smoke_train() { + preflight \ + configs/world_v9_episode_start/smoke.yaml \ + ../artifacts/world_v9_episode_start/reports/preflight-smoke.json + torchrun_v9 configs/world_v9_episode_start/smoke.yaml +} + +smoke_resume() { + preflight \ + configs/world_v9_episode_start/smoke.yaml \ + ../artifacts/world_v9_episode_start/reports/preflight-smoke-resume.json \ + runtime.max_steps=8003 + torchrun_v9 configs/world_v9_episode_start/smoke.yaml runtime.max_steps=8003 +} + +formal_train() { + require_formal_authorization + if pgrep -f '^tagshotx_wv9t[0-7]' >/dev/null; then + echo 'A World v9 episode-start training process is already running.' >&2 + exit 3 + fi + preflight \ + configs/world_v9_episode_start/train.yaml \ + ../artifacts/world_v9_episode_start/reports/preflight-formal.json + torchrun_v9 configs/world_v9_episode_start/train.yaml +} + +case "${1:-}" in + preflight-static) static_preflight ;; + audit-source-online) deep_source_audit ;; + smoke-train) smoke_train ;; + smoke-resume) smoke_resume ;; + preflight-formal) preflight configs/world_v9_episode_start/train.yaml ../artifacts/world_v9_episode_start/reports/preflight-formal.json ;; + formal-train) formal_train ;; + *) echo "usage: $0 {preflight-static|audit-source-online|smoke-train|smoke-resume|preflight-formal|formal-train}" >&2; exit 2 ;; +esac diff --git a/release-20261107/source/workspace_joint/mira/scripts/maintenance/diagnose_robotwin_expert.py b/release-20261107/source/workspace_joint/mira/scripts/maintenance/diagnose_robotwin_expert.py new file mode 100644 index 0000000000000000000000000000000000000000..a306c3755eaa0ada5a438a60d31399b19706626f --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/maintenance/diagnose_robotwin_expert.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +"""Run one RoboTwin expert episode without loading a policy checkpoint.""" +from __future__ import annotations + +import argparse +import importlib.util +import os +from pathlib import Path +import sys +import traceback + +from run_robotwin_eval_prewarmed import prewarm + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--robotwin-root", type=Path, required=True) + parser.add_argument("--task", default="adjust_bottle") + parser.add_argument("--task-config", default="demo_clean") + parser.add_argument("--seed", type=int, default=1_000_000) + args = parser.parse_args() + + root = args.robotwin_root.expanduser().resolve() + os.chdir(root) + for path in (root, root / "scripts", root / "description" / "utils"): + sys.path.insert(0, str(path)) + + prewarm() + script = root / "scripts" / "eval_policy_xpolicylab.py" + spec = importlib.util.spec_from_file_location("robotwin_eval_diagnostic", script) + if spec is None or spec.loader is None: + raise RuntimeError(f"cannot load {script}") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + + usr_args = { + "task_name": args.task, + "task_config": args.task_config, + "policy_name": "diagnostic", + "ckpt_setting": "none", + "instruction_type": "seen", + } + task_args, _ = module.load_task_args(usr_args) + task_args["eval_mode"] = True + task_args["render_freq"] = 0 + env = module.class_decorator(args.task) + try: + env.setup_demo(now_ep_num=0, seed=args.seed, is_test=True, **task_args) + env.play_once() + print("[robotwin-expert] passed", flush=True) + return 0 + except BaseException: + traceback.print_exc() + return 1 + finally: + try: + env.close_env() + except BaseException: + pass + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/release-20261107/source/workspace_joint/mira/scripts/maintenance/eval_color_pair.py b/release-20261107/source/workspace_joint/mira/scripts/maintenance/eval_color_pair.py new file mode 100644 index 0000000000000000000000000000000000000000..f7e70bcbd183410368d091983fe36fa5ac94b3bb --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/maintenance/eval_color_pair.py @@ -0,0 +1,105 @@ +"""RGB/BGR paired experiment: fixed language RNG and read-only task diagnostics.""" +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import random + + +def main(): + source = Path(os.environ["WAM_ORIGINAL_EVAL_SCRIPT"]) + destination = Path(os.environ["WAM_COLOR_STAGE_DIAGNOSTICS"]) + color = os.environ["BIHUB_INPUT_COLOR_ORDER"] + spec = importlib.util.spec_from_file_location("color_pair_original_eval", source) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + original_instruction = module.build_instruction + def instruction(args, episode_info, instruction_type, test_num, *, env_seed): + # Independent of condition, worker, requested episode count and retry history. + payload = f"color-pair-v1\0{args['task_name']}\0{args.get('task_config')}\0{env_seed}" + previous = random.getstate() + try: + random.seed(int.from_bytes(hashlib.sha256(payload.encode()).digest()[:8], "big")) + value = original_instruction(args, episode_info, instruction_type, 100, env_seed=env_seed) + if value == args["task_name"]: + raise RuntimeError("Color experiment refuses task-name instruction fallback") + return value + finally: + random.setstate(previous) + module.build_instruction = instruction + original_factory = module.class_decorator + original_prepare = module.prepare_policy_case + original_notify = module.notify_trial_end + current = {"env": None, "episode": None} + + def pose(actor): + value = actor.get_pose() + return {"p": [float(x) for x in value.p], "q": [float(x) for x in value.q]} + + def sample(env): + if type(env).__name__ == "handover_block": + return {"red_block": pose(env.box), "blue_pad": pose(env.target_box), + "right_gripper_open": bool(env.is_right_gripper_open())} + if type(env).__name__ == "blocks_ranking_rgb": + result = {name: pose(getattr(env, f"block{i}")) + for i, name in enumerate(("red", "green", "blue"), 1)} + result["left_to_right"] = sorted(("red", "green", "blue"), key=lambda name: result[name]["p"][0]) + result["both_grippers_open"] = bool(env.is_left_gripper_open() and env.is_right_gripper_open()) + return result + raise ValueError("Color diagnostic only supports the two registered tasks") + + def factory(task_name): + env = original_factory(task_name) + current["env"] = env + original_action = env.take_action + def action(*args, **kwargs): + result = original_action(*args, **kwargs) + row = current["episode"] + if row is not None: + row["actions"] += 1 + row["samples"].append(sample(env)) + return result + env.take_action = action + return env + + def prepare(model_client, task_name, seed, instruction_text, action_type): + current["episode"] = dict(task=task_name, seed=int(seed), input_color_order=color, + instruction=instruction_text, initial=sample(current["env"]), + actions=0, samples=[]) + return original_prepare(model_client, task_name, seed, instruction_text, action_type) + + def notify(model_client, task_name, seed, success): + row = current["episode"] + try: + if row is not None: + row["success"] = bool(success) + row["final"] = sample(current["env"]) + samples = row.pop("samples") + if task_name == "handover_block" and samples: + z0 = row["initial"]["red_block"]["p"][2] + row["red_block_lifted_6cm"] = max(x["red_block"]["p"][2] for x in samples) > z0 + .06 + row["red_block_crossed_center"] = any(x["red_block"]["p"][0] > 0 for x in samples) + row["min_red_to_pad_xy_error"] = min(max(abs(x["red_block"]["p"][i] - x["blue_pad"]["p"][i]) for i in (0,1)) for x in samples) + elif task_name == "blocks_ranking_rgb": + row["ever_rgb_order"] = any(x["left_to_right"] == ["red", "green", "blue"] for x in samples) + destination.parent.mkdir(parents=True, exist_ok=True) + with destination.open("a") as stream: + stream.write(json.dumps(row) + "\n") + finally: + current["episode"] = None + original_notify(model_client, task_name, seed, success) + + module.class_decorator = factory + module.prepare_policy_case = prepare + module.notify_trial_end = notify + from test_render import Sapien_TEST + Sapien_TEST() + parsed = module.parse_args() + if module.parse_bool(parsed.get("eval_batch", False)): + raise ValueError("Color pair wrapper requires a single simulator per server") + module.main(parsed) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/maintenance/eval_prompt_factorial.py b/release-20261107/source/workspace_joint/mira/scripts/maintenance/eval_prompt_factorial.py new file mode 100644 index 0000000000000000000000000000000000000000..c6c24e9573006beaafd4b7791f2b0bf96cfe3097 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/maintenance/eval_prompt_factorial.py @@ -0,0 +1,143 @@ +"""Paired language-factorial evaluation with read-only trajectory diagnostics. + +The official evaluator, actions, seeds, and success check remain unchanged. +""" + +from __future__ import annotations + +import importlib.util +import json +import os +from pathlib import Path + + +PREFIX = "A video recorded from a robot's point of view executing the following instruction: " + + +def main() -> None: + source = Path(os.environ["WAM_ORIGINAL_EVAL_SCRIPT"]).resolve() + condition = os.environ["WAM_PROMPT_CONDITION"] + prompt = Path(os.environ["WAM_TRAIN_PROMPT_FILE"]).read_text().strip() + if not prompt.startswith(PREFIX): + raise ValueError("Training prompt does not have the expected wrapper") + if condition not in {"train_bare", "official_wrapped", "train_exact"}: + raise ValueError(condition) + diagnostics = Path(os.environ["WAM_STAGE_DIAGNOSTICS"]) + diagnostics.parent.mkdir(parents=True, exist_ok=True) + + spec = importlib.util.spec_from_file_location("robotwin_eval_original", source) + if spec is None or spec.loader is None: + raise RuntimeError(f"Cannot load {source}") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + original_instruction = module.build_instruction + + def instruction(*args, **kwargs): + if condition == "train_bare": + return prompt[len(PREFIX):] + if condition == "train_exact": + return prompt + return PREFIX + original_instruction(*args, **kwargs) + + module.build_instruction = instruction + original_factory = module.class_decorator + original_notify = module.notify_trial_end + current = {"env": None, "tracker": None, "seed": None} + + def point(value): + return [float(x) for x in value] + + def sample(env): + if env.__class__.__name__ == "handover_block": + box = point(env.box.get_functional_point(0, "pose").p) + target = point(env.target_box.get_functional_point(1, "pose").p) + return {"box": box, "target": target, "right_gripper_open": bool(env.is_right_gripper_open())} + if env.__class__.__name__ == "pick_dual_bottles": + return { + "left": point(env.bottle1.get_functional_point(0)), + "right": point(env.bottle2.get_functional_point(0)), + "left_target": point(env.left_target_pose[:2]), + "right_target": point(env.right_target_pose[:2]), + } + return {} + + def factory(task_name): + env = original_factory(task_name) + current["env"] = env + original_action = env.take_action + + def action(*args, **kwargs): + tracker = current["tracker"] + if tracker is not None and tracker["initial"] is None: + try: + tracker["initial"] = sample(env) + except Exception: + pass + result = original_action(*args, **kwargs) + if tracker is not None: + tracker["actions"] += 1 + try: + tracker["samples"].append(sample(env)) + except Exception: + pass + return result + + env.take_action = action + return env + + def prepare(model_client, task_name, seed, instruction_text, action_type): + current["seed"] = int(seed) + current["tracker"] = {"initial": None, "samples": [], "actions": 0} + return original_prepare(model_client, task_name, seed, instruction_text, action_type) + + def notify(model_client, task_name, seed, success): + tracker = current["tracker"] + env = current["env"] + try: + if tracker is not None and env is not None: + samples = tracker["samples"] + initial = tracker["initial"] + final = sample(env) + row = { + "task": task_name, "seed": int(seed), "condition": condition, + "success": bool(success), "actions": tracker["actions"], + "initial": initial, "final": final, + } + if task_name == "handover_block" and initial and samples: + start_z = initial["box"][2] + row["max_box_z"] = max(s["box"][2] for s in samples) + row["ever_lifted_6cm"] = row["max_box_z"] > start_z + 0.06 + row["ever_crossed_center"] = any(s["box"][0] > 0 for s in samples) + row["min_target_xy_error"] = min(max(abs(s["box"][i] - s["target"][i]) for i in (0, 1)) for s in samples) + row["final_target_xy_ok"] = max(abs(final["box"][i] - final["target"][i]) for i in (0, 1)) < 0.03 + row["final_target_z_ok"] = abs(final["box"][2] - final["target"][2]) < 0.01 + elif task_name == "pick_dual_bottles" and initial and samples: + for side in ("left", "right"): + row[f"max_{side}_z"] = max(s[side][2] for s in samples) + row[f"ever_{side}_lifted_6cm"] = row[f"max_{side}_z"] > initial[side][2] + 0.06 + row[f"final_{side}_target_xy_ok"] = max(abs(final[side][i] - final[f"{side}_target"][i]) for i in (0, 1)) < 0.1 + row[f"final_{side}_z_ok"] = final[side][2] > 0.89 + with diagnostics.open("a") as handle: + handle.write(json.dumps(row, ensure_ascii=False) + "\n") + except Exception as exc: + print(f"[stage-diagnostics] {type(exc).__name__}: {exc}", flush=True) + finally: + current["tracker"] = None + original_notify(model_client, task_name, seed, success) + + original_prepare = module.prepare_policy_case + module.class_decorator = factory + module.prepare_policy_case = prepare + module.notify_trial_end = notify + + from test_render import Sapien_TEST + + Sapien_TEST() + parsed = module.parse_args() + if module.parse_bool(parsed.get("eval_batch", False)): + raise ValueError("Factorial diagnostic supports one case per process") + module.main(parsed) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/maintenance/eval_prompt_override.py b/release-20261107/source/workspace_joint/mira/scripts/maintenance/eval_prompt_override.py new file mode 100644 index 0000000000000000000000000000000000000000..9c4df77f15c9631c9ad7d12c37162de9d7cb0b98 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/maintenance/eval_prompt_override.py @@ -0,0 +1,39 @@ +"""Run the pinned RoboTwin evaluator with one isolated instruction override. + +The original evaluator and benchmark success checks are left untouched. This +wrapper changes only the instruction passed to the policy for this process. +""" + +from __future__ import annotations + +import importlib.util +import os +from pathlib import Path + + +def main() -> None: + source = Path(os.environ["WAM_ORIGINAL_EVAL_SCRIPT"]).resolve() + prompt_file = Path(os.environ["WAM_PROMPT_FILE"]).resolve() + prompt = prompt_file.read_text(encoding="utf-8").strip() + if not prompt: + raise ValueError(f"Empty prompt: {prompt_file}") + + spec = importlib.util.spec_from_file_location("robotwin_eval_original", source) + if spec is None or spec.loader is None: + raise RuntimeError(f"Cannot load RoboTwin evaluator: {source}") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + module.build_instruction = lambda *args, **kwargs: prompt + + from test_render import Sapien_TEST + + Sapien_TEST() + parsed = module.parse_args() + if module.parse_bool(parsed.get("eval_batch", False)): + module.main_batch(parsed) + else: + module.main(parsed) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/maintenance/install_hf_release.py b/release-20261107/source/workspace_joint/mira/scripts/maintenance/install_hf_release.py new file mode 100644 index 0000000000000000000000000000000000000000..b69ff5c3f2f561a1b793a8b5fd24a57f2fdd6d9f --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/maintenance/install_hf_release.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""Verify staged HF release files, install checkpoints by hardlink, keep originals immutable.""" +import argparse +import hashlib +import json +import os +import shutil +from pathlib import Path + + +def sha(path): + digest = hashlib.sha256() + with path.open('rb') as stream: + while chunk := stream.read(8 << 20): + digest.update(chunk) + return digest.hexdigest() + + +def main(): + p = argparse.ArgumentParser() + p.add_argument('bundle', type=Path) + p.add_argument('workspace', type=Path) + args = p.parse_args() + release = args.bundle / 'release-20260902' + manifest = json.loads((release / 'RELEASE_MANIFEST.json').read_text()) + checksums = {} + for line in (release / 'SHA256SUMS').read_text().splitlines(): + digest, name = line.split(maxsplit=1) + checksums[name.lstrip('*').removeprefix('./')] = digest + installed = [] + for item in manifest['checkpoints']: + source = release / item['path'] + files = sorted(path for path in source.rglob('*') if path.is_file()) + if len(files) != item['files'] or sum(path.stat().st_size for path in files) != item['bytes']: + raise RuntimeError(f'Incomplete checkpoint: {source}') + for path in files: + relative = path.relative_to(release).as_posix() + expected = checksums[relative] + if sha(path) != expected: + raise RuntimeError(f'SHA mismatch: {path}') + target = args.workspace / path.relative_to(release / 'workspace') + target.parent.mkdir(parents=True, exist_ok=True) + if target.exists(): + if sha(target) != expected: + raise RuntimeError(f'Refuse to overwrite local checkpoint: {target}') + else: + try: + os.link(path, target) + except OSError: + shutil.copy2(path, target) + installed.append({'path': str(target.relative_to(args.workspace)), 'sha256': expected}) + report = args.workspace / 'artifacts/reports/20260920/hf_sync.json' + report.parent.mkdir(parents=True, exist_ok=True) + report.write_text(json.dumps({'revision': '1d9b974503993785fc6f59ec62379909173271ea', + 'files': installed, 'verified_bytes': sum(x['bytes'] for x in manifest['checkpoints'])}, indent=2) + '\n') + print(f'Installed and SHA256-verified {len(installed)} checkpoint files: {report}', flush=True) + + +if __name__ == '__main__': + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/maintenance/monitor_joint_eval_gpu.py b/release-20261107/source/workspace_joint/mira/scripts/maintenance/monitor_joint_eval_gpu.py new file mode 100644 index 0000000000000000000000000000000000000000..1a2b124620c2106472ca1d76d1bf0a9aa3e88d0e --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/maintenance/monitor_joint_eval_gpu.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""Keep a durable, per-GPU utilization/memory trace for the formal eval.""" + +from __future__ import annotations + +import csv +import argparse +import json +import subprocess +import time +from datetime import datetime, timezone +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[3] +HOSTS = { + "node12": (None, None), + "node17": ("172.29.15.126", "/private/ssh_keys/root_dedicated-developjob-zhizhou-avgen-2-bjweu_ed25519"), + "node16": ("172.29.112.43", "/private/ssh_keys/root_dedicated-developjob-zhizhou-avgen-1-m8eyg_ed25519"), +} +QUERY = ["nvidia-smi", "--query-gpu=index,memory.used,memory.total,utilization.gpu", "--format=csv,noheader,nounits"] + + +def sample(host: str | None, key: str | None) -> list[tuple[int, int, int, int]]: + command = QUERY if host is None else ["ssh", "-i", key, "-o", "BatchMode=yes", f"root@{host}", *QUERY] + output = subprocess.check_output(command, text=True, timeout=20) + rows = [] + for line in output.splitlines(): + fields = [part.strip() for part in line.split(",")] + if len(fields) == 4 and all(field.isdigit() for field in fields): + rows.append(tuple(map(int, fields))) + if len(rows) != 8: + raise RuntimeError(f"expected 8 GPUs for {host}, got {rows}") + return rows + + +def eval_running(session: str, tmux_label: str) -> bool: + return subprocess.run(["tmux", "-L", tmux_label, "has-session", "-t", session], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0 + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--run-id", default="joint2449_formal20_20260930") + parser.add_argument("--session", default="joint2449_formal20_eval") + parser.add_argument("--tmux-label", default="hc") + args = parser.parse_args() + out = ROOT / "artifacts/evaluation" / args.run_id + out.mkdir(parents=True, exist_ok=True) + csv_path = out / "gpu_trace.csv" + peak_path = out / "gpu_peaks.json" + peaks: dict[str, dict[str, int]] = {} + if peak_path.is_file(): + peaks = json.loads(peak_path.read_text()) + fresh = not csv_path.is_file() + with csv_path.open("a", newline="") as stream: + writer = csv.writer(stream) + if fresh: + writer.writerow(["timestamp_utc", "node", "gpu", "memory_used_mib", "memory_total_mib", "gpu_util_percent"]) + while eval_running(args.session, args.tmux_label): + timestamp = datetime.now(timezone.utc).isoformat() + for name, (host, key) in HOSTS.items(): + try: + for gpu, used, total, util in sample(host, key): + writer.writerow([timestamp, name, gpu, used, total, util]) + entry = peaks.setdefault(f"{name}:gpu{gpu}", {"memory_used_mib": 0, "gpu_util_percent": 0}) + entry["memory_used_mib"] = max(entry["memory_used_mib"], used) + entry["gpu_util_percent"] = max(entry["gpu_util_percent"], util) + except (OSError, RuntimeError, subprocess.SubprocessError) as exc: + print(f"{timestamp} {name} sample failed: {exc}", flush=True) + stream.flush() + temp = peak_path.with_suffix(".tmp") + temp.write_text(json.dumps(peaks, indent=2, sort_keys=True) + "\n") + temp.replace(peak_path) + time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/maintenance/preflight_joint.py b/release-20261107/source/workspace_joint/mira/scripts/maintenance/preflight_joint.py new file mode 100644 index 0000000000000000000000000000000000000000..e62d4eb92d34508ce60e66ac8b7ef635f0d9b034 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/maintenance/preflight_joint.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +"""Read-only CPU preflight against real assets and real RoboTwin episodes.""" +import argparse +import importlib.metadata +import json +from pathlib import Path + +from mira.data.joint_online import JointOnlineRoboTwinDataset +from mira.data.robotwin_wam_schema import sha256_file +from mira.joint.paths import workspace_path +from mira.training.world_v8.checkpoint import checkpoint_fingerprint + + +def main(): + p = argparse.ArgumentParser() + p.add_argument('--dataset-root', type=Path, required=True) + p.add_argument('--manifest-dir', type=Path, required=True) + p.add_argument('--report', type=Path, required=True) + args = p.parse_args() + workspace = Path(__file__).resolve().parents[3] + sync = json.loads((workspace / 'artifacts/reports/20260920/hf_sync.json').read_text()) + roles = { + 'world': 'outputs/robotwin_bihub_world_v12_largebatch_remaining/main-checkpoint-25066', + 'action_final': 'outputs/robotwin_bihub_wam_v13_action_eval_aligned_continue4epoch/action-checkpoint-23016', + 'action_best': 'outputs/robotwin_bihub_wam_v13_action_eval_aligned_continue4epoch/action-checkpoint-11508', + } + reports = {} + for role, relative in roles.items(): + root = workspace / relative + meta = json.loads((root / 'trainer_state.json').read_text()) + reports[role] = {'step': meta['completed_steps'], 'fingerprint': checkpoint_fingerprint(root)} + world_meta = json.loads((workspace / roles['world'] / 'trainer_state.json').read_text()) + stats = workspace_path(world_meta['resolved_config']['artifacts']['dataset_stats']) + assert sha256_file(stats) == world_meta['artifact_identity']['state_stats'] + codec = workspace_path(world_meta['resolved_config']['artifacts']['codec_checkpoint']) + codec_hash = sha256_file(codec) + assert codec_hash == world_meta['resolved_config']['artifacts']['codec_sha256'] + datasets = {split: JointOnlineRoboTwinDataset(dataset_root=args.dataset_root, + manifest=args.manifest_dir / f'{split}.jsonl') for split in ('train', 'val')} + assert not ({row['episode_sha256'] for row in datasets['train'].source_rows} & + {row['episode_sha256'] for row in datasets['val'].source_rows}) + decoded = [] + for split, dataset in datasets.items(): + for anchor in (0, min(8, dataset.base_counts[0]-1), dataset.base_counts[0]-1): + sample = dataset[dataset.anchor_index(0, anchor)] + decoded.append({'split': split, 'anchor': anchor, 'video_shape': list(sample['video'].shape), + 'history': int(sample['history_valid'].sum()), + 'valid_action': int(sample['action_valid'].sum()), + 'valid_future': int(sample['future_valid'].sum())}) + report = {'status': 'cpu_preflight_passed_NOT_GPU_VALIDATED', 'revision': sync['revision'], + 'checkpoints': reports, 'codec_sha256': codec_hash, 'decoded_real_samples': decoded, + 'manifest_dir': str(args.manifest_dir), + 'episodes': {key: len(ds.source_rows) for key, ds in datasets.items()}, + 'current_anchor_count': {key: len(ds) for key, ds in datasets.items()}, + 'versions': {name: importlib.metadata.version(name) for name in ('torch', 'transformers', 'h5py')}, + 'gpu_used': False} + args.report.parent.mkdir(parents=True, exist_ok=True) + args.report.write_text(json.dumps(report, indent=2) + '\n') + print(json.dumps(report, indent=2)) + + +if __name__ == '__main__': + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/maintenance/preflight_robotwin_closed_loop.py b/release-20261107/source/workspace_joint/mira/scripts/maintenance/preflight_robotwin_closed_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..335068045625ba940cc9f14e9ab9ffb1fb719980 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/maintenance/preflight_robotwin_closed_loop.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python3 +"""Fail-fast preflight for the official RoboTwin closed-loop simulator.""" +from __future__ import annotations + +import argparse +import importlib.metadata +import json +import os +from pathlib import Path +import platform +import subprocess +import sys +import traceback + + +def package_version(name: str) -> str | None: + try: + return importlib.metadata.version(name) + except importlib.metadata.PackageNotFoundError: + return None + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--robotwin-root", type=Path, required=True) + parser.add_argument("--report", type=Path, required=True) + args = parser.parse_args() + root = args.robotwin_root.expanduser().resolve() + report_path = args.report.expanduser().resolve() + report_path.parent.mkdir(parents=True, exist_ok=True) + checks: dict[str, object] = { + "robotwin_root": str(root), + "python": sys.executable, + "python_version": platform.python_version(), + "packages": { + name: package_version(name) + for name in ( + "sapien", + "mplib", + "gymnasium", + "torch", + "numpy", + "open3d", + "nvidia-curobo", + "warp-lang", + ) + }, + "graphics_runtime_source": os.environ.get( + "ROBOTWIN_GRAPHICS_RUNTIME_SOURCE" + ), + "vk_icd_filenames": os.environ.get("VK_ICD_FILENAMES"), + "egl_vendor_library_filenames": os.environ.get( + "__EGL_VENDOR_LIBRARY_FILENAMES" + ), + } + required = [ + root / "scripts/eval_policy_xpolicylab.py", + root / "XPolicyLab/setup_policy_server.py", + root / "XPolicyLab/model_template.py", + root / "assets/embodiments/aloha-agilex/config.yml", + root / "env_cfg/task_config/demo_clean.yml", + root / "env_cfg/task_config/demo_randomized.yml", + root / "assets/embodiments/aloha-agilex/curobo_left.yml", + root / "assets/embodiments/aloha-agilex/curobo_right.yml", + ] + missing = [str(path) for path in required if not path.is_file()] + checks["required_files"] = { + "status": "passed" if not missing else "failed", + "missing": missing, + } + generated = [root / "assets/embodiments/aloha-agilex" / name + for name in ("curobo_left.yml", "curobo_right.yml")] + unresolved = [str(path) for path in generated if path.is_file() and "${ASSETS_PATH}" in path.read_text()] + missing_planner_assets = [] + for path in generated: + if not path.is_file(): + continue + import yaml + kinematics = yaml.safe_load(path.read_text())["robot_cfg"]["kinematics"] + for key in ("urdf_path", "collision_spheres"): + asset = Path(kinematics[key]) + if not asset.is_file(): + missing_planner_assets.append(str(asset)) + checks["planner_asset_paths"] = { + "status": "passed" if not unresolved and not missing_planner_assets else "failed", + "unresolved_templates": unresolved, + "missing_assets": missing_planner_assets, + } + runtime_import_errors: dict[str, str] = {} + previous_cwd = Path.cwd() + try: + os.chdir(root) + task_modules = ( + "envs.adjust_bottle", + "envs.click_bell", + "envs.grab_roller", + "envs.handover_block", + "envs.lift_pot", + "envs.open_laptop", + "envs.pick_dual_bottles", + "envs.place_a2b_left", + ) + for module_name in ("open3d", "curobo", "envs", *task_modules): + try: + __import__(module_name) + except BaseException: + runtime_import_errors[module_name] = traceback.format_exc() + finally: + os.chdir(previous_cwd) + checks["runtime_imports"] = { + "status": "passed" if not runtime_import_errors else "failed", + "errors": runtime_import_errors, + } + try: + gpu_lines = subprocess.check_output( + [ + "nvidia-smi", + "--query-gpu=index,name,driver_version", + "--format=csv,noheader", + ], + text=True, + ).splitlines() + checks["gpus"] = gpu_lines + except Exception as exc: # pragma: no cover - machine-specific diagnostic + checks["gpus"] = {"error": repr(exc)} + + try: + import sapien.core as sapien + from sapien.render import set_global_config + + set_global_config(max_num_materials=50000, max_num_textures=50000) + engine = sapien.Engine() + renderer = sapien.SapienRenderer() + engine.set_renderer(renderer) + sapien.render.set_camera_shader_dir("rt") + sapien.render.set_ray_tracing_samples_per_pixel(32) + sapien.render.set_ray_tracing_path_depth(8) + denoiser = os.environ.get("ROBOTWIN_RAY_DENOISER", "oidn") + if denoiser not in {"oidn", "optix"}: + raise ValueError(f"unsupported ray tracing denoiser: {denoiser}") + sapien.render.set_ray_tracing_denoiser(denoiser) + scene = engine.create_scene(sapien.SceneConfig()) + checks["official_rt_renderer"] = { + "status": "passed", + "scene_type": type(scene).__name__, + "denoiser": denoiser, + } + except BaseException as exc: # SAPIEN may raise non-standard extension errors + checks["official_rt_renderer"] = { + "status": "failed", + "error_type": type(exc).__name__, + "error": str(exc), + "traceback": traceback.format_exc(), + "remedy": ( + "Run the simulator in a host/container exposing NVIDIA graphics and " + "Vulkan capabilities; CUDA-only GPU mounts are insufficient." + ), + } + + passed = ( + not missing + and not unresolved + and not missing_planner_assets + and not runtime_import_errors + and checks.get("official_rt_renderer", {}).get("status") == "passed" + ) + checks["status"] = "passed" if passed else "failed" + checks["training_started"] = False + report_path.write_text(json.dumps(checks, indent=2) + "\n", encoding="utf-8") + print(json.dumps(checks, indent=2)) + return 0 if passed else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/release-20261107/source/workspace_joint/mira/scripts/maintenance/prepare_joint_eval_resume.py b/release-20261107/source/workspace_joint/mira/scripts/maintenance/prepare_joint_eval_resume.py new file mode 100644 index 0000000000000000000000000000000000000000..0e0f732400c072e9ba4d8082010f984fcbd8fe6f --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/maintenance/prepare_joint_eval_resume.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""Snapshot completed RoboTwin episodes after a PID-scoped eval stop. + +Only episodes with a completed success-rate line and a decodable video count. +The next run resumes the original 20-trial loop at the next seed, reusing the +original result directory and counters. Any interrupted episode is rerun. +""" + +from __future__ import annotations + +import argparse +import json +import re +import subprocess +from datetime import datetime, timezone +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[3] +EVAL_ROOT = ROOT / "transfer/robotwin-official-20260921" +ANSI = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]") +PROGRESS = re.compile(r"Success rate:\s*(\d+)/(\d+)[^\n]*current seed:\s*(\d+)") + + +def valid_video(path: Path) -> bool: + if not path.is_file() or path.stat().st_size < 1000: + return False + result = subprocess.run( + ["ffprobe", "-v", "error", "-show_entries", "format=duration", + "-of", "default=noprint_wrappers=1:nokey=1", str(path)], + text=True, capture_output=True, timeout=15, + ) + try: + return result.returncode == 0 and float(result.stdout.strip()) > 0 + except ValueError: + return False + + +def atomic_json(path: Path, payload: dict) -> None: + temp = path.with_suffix(path.suffix + ".tmp") + temp.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") + temp.replace(path) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--run-id", required=True) + args = parser.parse_args() + if not re.fullmatch(r"[A-Za-z0-9_.-]+", args.run_id): + parser.error("invalid run-id") + out = ROOT / "artifacts/evaluation" / args.run_id + manifest = json.loads((out / "manifest.json").read_text()) + target = int(manifest["test_num_per_task_domain"]) + report = {"run_id": args.run_id, "snapshot_at": datetime.now(timezone.utc).isoformat(), + "target_per_job": target, "jobs": []} + for status_file in sorted((out / "jobs").glob("*/status.json")): + status = json.loads(status_file.read_text()) + if status.get("status") == "passed" and Path(status.get("result_file", "")).is_file(): + report["jobs"].append({"job_id": status["job_id"], "completed": target, + "success": status["success"], "status": "already_passed"}) + continue + client_log = status_file.with_name("client.log") + entries = [] + if client_log.is_file(): + content = ANSI.sub("", client_log.read_text(errors="replace")) + entries = [(int(success), int(completed), int(seed)) + for success, completed, seed in PROGRESS.findall(content)] + result_parent = (EVAL_ROOT / "eval_result" / status["task"] / "BiHubJoint" / + status["domain"] / args.run_id) + result_dirs = sorted((p for p in result_parent.glob("*") if p.is_dir()), + key=lambda p: p.stat().st_mtime, reverse=True) + accepted = (0, 0, 99999, None) + for success, completed, seed in reversed(entries): + if not 0 < completed <= target or not 0 <= success <= completed: + continue + for result_dir in result_dirs: + if all(valid_video(result_dir / f"episode{i}.mp4") for i in range(completed)): + accepted = (success, completed, seed, result_dir.resolve()) + break + if accepted[1]: + break + success, completed, seed, result_dir = accepted + resume_file = status_file.with_name("resume.json") + if completed: + snapshot = { + "job_id": status["job_id"], "completed": completed, + "success": success, "next_seed": seed + 1, + "save_dir": str(result_dir), "original_test_num": target, + "source_log": str(client_log), "snapshot_at": report["snapshot_at"], + } + atomic_json(resume_file, snapshot) + if completed == target: + result_file = result_dir / "_result.txt" + result_file.write_text( + f"Timestamp: {report['snapshot_at']}\n\n" + f"Instruction Type: {'seen' if status['domain'] == 'demo_clean' else 'unseen'}\n\n" + f"{success / target}", encoding="utf-8", + ) + status.update(status="passed", success=success, rate=success / target, + videos=completed, result_file=str(result_file), + finished_at=report["snapshot_at"]) + atomic_json(status_file, status) + else: + resume_file.unlink(missing_ok=True) + if completed < target: + status.update(status="paused", retained_episodes=completed, + retained_success=success, paused_at=report["snapshot_at"]) + atomic_json(status_file, status) + report["jobs"].append({"job_id": status["job_id"], "completed": completed, + "success": success, "next_seed": seed + 1 if completed else 100000, + "status": "ready_to_resume" if completed < target else "passed"}) + report["retained_episodes"] = sum(job["completed"] for job in report["jobs"]) + report["retained_successes"] = sum(job["success"] for job in report["jobs"]) + report["jobs_with_progress"] = sum(job["completed"] > 0 for job in report["jobs"]) + atomic_json(out / "resume_report.json", report) + states = [json.loads(path.read_text()) for path in sorted((out / "jobs").glob("*/status.json"))] + passed = [state for state in states if state["status"] == "passed"] + paused = [state for state in states if state["status"] == "paused"] + atomic_json(out / "progress.json", { + "updated_at": report["snapshot_at"], "total_jobs": len(states), + "planned_rollouts": len(states) * target, + "passed_jobs": len(passed), "paused_jobs": len(paused), + "failed_jobs": 0, "running_jobs": 0, + "completed_rollouts": len(passed) * target, + "completed_successes": sum(state["success"] for state in passed), + "inflight_rollouts": 0, "inflight_successes": 0, + "retained_rollouts": report["retained_episodes"], + "retained_successes": report["retained_successes"], + "provisional_success_rate": ( + report["retained_successes"] / report["retained_episodes"] + if report["retained_episodes"] else None + ), + "jobs": states, + }) + print(json.dumps({key: value for key, value in report.items() if key != "jobs"}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/maintenance/run_formal_offline_eval.py b/release-20261107/source/workspace_joint/mira/scripts/maintenance/run_formal_offline_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..bad8b8e9347355fd8b9ea15b60fc4dbbd6871eaa --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/maintenance/run_formal_offline_eval.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""Eight-GPU, all-task offline evaluation for the two released Action candidates.""" +from __future__ import annotations + +from datetime import datetime, timezone +import argparse +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import time + + +def gpu_memory() -> dict[int, dict[str, float]]: + output = subprocess.check_output( + ['nvidia-smi', '--query-gpu=index,memory.free,memory.used', + '--format=csv,noheader,nounits'], text=True, + ) + return { + int(row.split(',')[0]): { + 'free_gib': int(row.split(',')[1]) / 1024, + 'used_gib': int(row.split(',')[2]) / 1024, + } + for row in output.splitlines() + } + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument('--output', type=Path) + args = parser.parse_args() + root = Path(__file__).resolve().parents[3] + stamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ') + output = args.output or root / f'artifacts/evaluation/formal_offline_{stamp}' + output.mkdir(parents=True, exist_ok=False) + environment = dict(os.environ) + for key in ('http_proxy', 'https_proxy', 'all_proxy', 'ftp_proxy', + 'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'FTP_PROXY'): + environment.pop(key, None) + environment.update( + NO_PROXY='*', no_proxy='*', HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1', + PYTHONPATH=str(root / 'mira/src'), PYTHONUNBUFFERED='1', OMP_NUM_THREADS='2', + TOKENIZERS_PARALLELISM='false', PYTORCH_CUDA_ALLOC_CONF='expandable_segments:True', + ) + # Four deterministic shards per checkpoint: 500 cases/checkpoint, 125 cases/GPU. + specs = [ + (gpu, step, shard, f'action{step}_shard{shard}') + for step, base in ((23016, 0), (11508, 4)) + for shard, gpu in enumerate(range(base, base + 4)) + ] + children = [] + + def stop_children(*_args) -> None: + for _, process, stream in children: + if process.poll() is None: + process.terminate() + stream.flush() + + signal.signal(signal.SIGINT, stop_children) + signal.signal(signal.SIGTERM, stop_children) + initial = gpu_memory() + (output / 'initial_memory.json').write_text(json.dumps(initial, indent=2) + '\n') + try: + for gpu, step, shard, label in specs: + free = gpu_memory()[gpu]['free_gib'] + cap = min(128.0, free - 4.0) + if cap < 24: + raise RuntimeError(f'GPU {gpu} has only {free:.1f} GiB free') + stream = (output / f'{label}.log').open('w') + command = [ + sys.executable, str(root / 'mira/scripts/validate_joint_inference.py'), + '--mode', 'baseline', '--action-step', str(step), '--cases', '0', + '--all-task-domains', '--num-shards', '4', '--shard-index', str(shard), + '--memory-cap-gib', str(cap), '--output', str(output / label), + ] + process = subprocess.Popen( + command, cwd=root, stdout=stream, stderr=subprocess.STDOUT, + env={**environment, 'CUDA_VISIBLE_DEVICES': str(gpu)}, + ) + children.append((gpu, process, stream)) + print(f'{label}: GPU {gpu}, PID {process.pid}, cases=125, cap={cap:.1f} GiB', flush=True) + + safety_stops = [] + with (output / 'gpu_memory.jsonl').open('a') as memory_log: + while any(process.poll() is None for _, process, _ in children): + current = gpu_memory() + memory_log.write(json.dumps({'time': time.time(), 'gpus': current}) + '\n') + memory_log.flush() + for gpu, process, _ in children: + if process.poll() is None and current[gpu]['free_gib'] < 4: + safety_stops.append({'gpu': gpu, 'pid': process.pid, + 'free_gib': current[gpu]['free_gib']}) + process.terminate() + time.sleep(3) + workers = [ + {'gpu': gpu, 'pid': process.pid, 'exit_code': process.returncode} + for gpu, process, _ in children + ] + result = { + 'status': 'passed' if all(row['exit_code'] == 0 for row in workers) else 'failed', + 'training_started': False, 'gpus': list(range(8)), + 'cases_per_checkpoint': 500, 'safety_stops': safety_stops, 'workers': workers, + } + (output / 'supervisor.json').write_text(json.dumps(result, indent=2) + '\n') + print(json.dumps(result), flush=True) + return 0 if result['status'] == 'passed' else 1 + finally: + stop_children() + for _, process, stream in children: + process.wait() + stream.close() + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/release-20261107/source/workspace_joint/mira/scripts/maintenance/run_gpu_validation.py b/release-20261107/source/workspace_joint/mira/scripts/maintenance/run_gpu_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..a0b32eb349d4f861bebf8b1213db2c75e4413412 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/maintenance/run_gpu_validation.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Bounded eight-GPU inference supervisor; terminate only children started by this run.""" +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import time + + +def gpu_memory(): + output = subprocess.check_output(['nvidia-smi', '--query-gpu=index,memory.free,memory.used', + '--format=csv,noheader,nounits'], text=True) + return {int(row.split(',')[0]): {'free_gib': int(row.split(',')[1]) / 1024, + 'used_gib': int(row.split(',')[2]) / 1024} + for row in output.splitlines()} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--output', type=Path) + args = parser.parse_args() + root = Path(__file__).resolve().parents[3] + stamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ') + output = args.output or root / f'artifacts/reports/gpu_validation_{stamp}' + output.mkdir(parents=True, exist_ok=False) + environment = dict(os.environ) + for key in ('http_proxy', 'https_proxy', 'all_proxy', 'ftp_proxy', 'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'FTP_PROXY'): + environment.pop(key, None) + environment.update(NO_PROXY='*', no_proxy='*', HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1', + PYTHONPATH=str(root / 'mira/src'), PYTHONUNBUFFERED='1', OMP_NUM_THREADS='2', + TOKENIZERS_PARALLELISM='false', PYTORCH_CUDA_ALLOC_CONF='expandable_segments:True') + children = [] + def stop_children(*_): + for _, process, _ in children: + if process.poll() is None: + process.terminate() + signal.signal(signal.SIGTERM, stop_children) + signal.signal(signal.SIGINT, stop_children) + # Cover the full 20-case task/domain/history grid. Joint and codec workloads are sharded + # across GPUs; the two deployed Action checkpoints each see the same complete grid. + specs = [ + (0, 'final23016', 'baseline', 23016, 20, 0), + (1, 'best11508', 'baseline', 11508, 20, 0), + (2, 'joint23016_a', 'joint', 23016, 10, 0), + (3, 'joint23016_b', 'joint', 23016, 10, 10), + (4, 'joint11508_a', 'joint', 11508, 10, 0), + (5, 'joint11508_b', 'joint', 11508, 10, 10), + (6, 'codec_a', 'codec', 23016, 10, 0), + (7, 'codec_b', 'codec', 23016, 10, 10), + ] + try: + initial = gpu_memory() + (output / 'initial_memory.json').write_text(json.dumps(initial, indent=2) + '\n') + for gpu, label, mode, step, cases, offset in specs: + free = gpu_memory()[gpu]['free_gib'] + cap = min(128.0, free - 4.0) + if cap < 24: + raise RuntimeError(f'GPU {gpu} free={free:.1f} GiB; insufficient for bounded validation') + log = (output / f'{label}.log').open('w') + command = [sys.executable, str(root / 'mira/scripts/validate_joint_inference.py'), + '--mode', mode, '--action-step', str(step), '--cases', str(cases), + '--case-offset', str(offset), + '--memory-cap-gib', str(cap), '--output', str(output / label)] + process = subprocess.Popen(command, env={**environment, 'CUDA_VISIBLE_DEVICES': str(gpu)}, + stdout=log, stderr=subprocess.STDOUT, cwd=root) + children.append((gpu, process, log)) + print(f'{label}: GPU {gpu}, PID {process.pid}, cap {cap:.1f} GiB, log {log.name}', flush=True) + safety_stops = [] + with (output / 'gpu_memory.jsonl').open('a') as stream: + while any(process.poll() is None for _, process, _ in children): + memory = gpu_memory() + stream.write(json.dumps({'time': time.time(), 'gpus': {str(gpu): memory[gpu] for gpu, _, _ in children}}) + '\n') + stream.flush() + for gpu, process, _ in children: + if process.poll() is None and memory[gpu]['free_gib'] < 8: + print(f'Safety stop of own worker PID {process.pid}: GPU {gpu} <8 GiB free', flush=True) + safety_stops.append({'gpu': gpu, 'pid': process.pid, 'free_gib': memory[gpu]['free_gib']}) + process.terminate() + time.sleep(3) + results = {'training_started': False, 'gpus': list(range(8)), 'safety_stops': safety_stops, + 'workers': [{'gpu': gpu, 'pid': proc.pid, 'exit_code': proc.returncode} for gpu, proc, _ in children]} + results['passed'] = all(row['exit_code'] == 0 for row in results['workers']) + (output / 'supervisor.json').write_text(json.dumps(results, indent=2) + '\n') + print(json.dumps(results), flush=True) + return 0 if results['passed'] else 1 + finally: + stop_children() + for _, process, log in children: + process.wait() + log.close() + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/release-20261107/source/workspace_joint/mira/scripts/maintenance/run_joint_eval_local.py b/release-20261107/source/workspace_joint/mira/scripts/maintenance/run_joint_eval_local.py new file mode 100644 index 0000000000000000000000000000000000000000..64aab403b81f52801ca57360391c387a0c174136 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/maintenance/run_joint_eval_local.py @@ -0,0 +1,472 @@ +#!/usr/bin/env python3 +"""One-GPU RoboTwin closed-loop evaluation with paired joint deployment. + +The scheduler must reserve the GPU before this process starts. Policy and +simulator share that reserved device; no training checkpoint is modified. +""" +from __future__ import annotations + +import argparse +import ctypes +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import re +import signal +import socket +import subprocess +import time + + +ROOT = Path(__file__).resolve().parents[3] +EVAL_ROOT = ROOT / "transfer/robotwin-official-20260921" +DOMAINS = ("demo_clean", "demo_randomized") +PROGRESS_FILENAME = "progress.json" +PROGRESS_FORMAT = "robotwin-eval-progress-v1" +RESUME_PROTOCOL = "progress_file_v1" + + +def set_process_name() -> None: + name = os.environ.get("ROBOTWIN_PROCESS_NAME") + if not name: + return + try: + import setproctitle + setproctitle.setproctitle(name) + except ImportError: + pass + ctypes.CDLL(None).prctl(15, name.encode()[:15], 0, 0, 0) + + +def now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def write_json(path: Path, value: dict) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(path.suffix + ".tmp") + temp.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n") + temp.replace(path) + + +def digest(path: Path) -> str: + value = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(1 << 20), b""): + value.update(block) + return value.hexdigest() + + +def terminate(proc: subprocess.Popen | None) -> None: + if proc is None or proc.poll() is not None: + return + os.killpg(proc.pid, signal.SIGTERM) + try: + proc.wait(timeout=15) + except subprocess.TimeoutExpired: + os.killpg(proc.pid, signal.SIGKILL) + proc.wait(timeout=10) + + +def wait_server(proc: subprocess.Popen, port: int, seconds: int) -> None: + from websockets.sync.client import connect + + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + if proc.poll() is not None: + raise RuntimeError(f"policy server exited with code {proc.returncode}") + try: + with connect(f"ws://127.0.0.1:{port}", open_timeout=2, close_timeout=2): + return + except (OSError, TimeoutError): + time.sleep(2) + raise TimeoutError(f"policy server not ready on port {port}") + + +def result_parent(task: str, domain: str, run_id: str) -> Path: + return EVAL_ROOT / "eval_result" / task / "BiHubJoint" / domain / run_id + + +def read_progress(path: Path) -> dict | None: + try: + data = json.loads(path.read_text()) + except (OSError, json.JSONDecodeError): + return None + return data if isinstance(data, dict) and data.get("format") == PROGRESS_FORMAT else None + + +def locate_progress(result_dir: Path) -> tuple[Path, dict] | None: + """Newest progress record among the official result directories of one case.""" + found = [] + for path in (result_dir.glob(f"*/{PROGRESS_FILENAME}") if result_dir.is_dir() else []): + data = read_progress(path) + if data is not None: + found.append((int(data["completed"]), path.stat().st_mtime, path, data)) + if not found: + return None + _, _, path, data = max(found, key=lambda item: item[:2]) + return path, data + + +def verify_episode_videos(save_dir: Path, progress: dict) -> int: + """Every scored episode except an abandoned one must have its official video.""" + indices = list(range(int(progress.get("bootstrap", {}).get("completed", 0)))) + indices += [int(e["index"]) for e in progress["episodes"] if e["outcome"] != "abandoned"] + for index in indices: + video = save_dir / f"episode{index}.mp4" + if not video.is_file() or video.stat().st_size <= 1024: + raise RuntimeError(f"missing rollout video for scored episode: {video}") + return len(indices) + + +def abandoned_episodes(progress: dict) -> list[dict]: + return [{"seed": e["seed"], "index": e["index"], "attempts": e["attempts"], "reason": e["reason"]} + for e in progress["episodes"] if e["outcome"] == "abandoned"] + + +def skipped_by_stage(progress: dict) -> dict[str, int]: + counts: dict[str, int] = {} + for item in progress["skipped"]: + counts[item["stage"]] = counts.get(item["stage"], 0) + 1 + return counts + + +def partial_case_state(case_dir: Path, result_dir: Path) -> dict | None: + """Resume state of an interrupted case; the progress record is authoritative.""" + located = locate_progress(result_dir) + if located is not None: + path, progress = located + save_dir = path.parent + recorded = Path(progress["save_dir"]) + if not recorded.is_absolute(): + # The official evaluator runs in EVAL_ROOT and records its directory relative to it. + recorded = EVAL_ROOT / recorded + if recorded.resolve() != save_dir.resolve(): + raise RuntimeError(f"progress record {path} names a different result directory") + return {"completed": int(progress["completed"]), "success": int(progress["success"]), + "next_seed": int(progress["next_seed"]), "save_dir": str(save_dir), + "source": "progress_file", "progress_file": str(path), + "videos": verify_episode_videos(save_dir, progress), + "abandoned": len(abandoned_episodes(progress)), "skipped": skipped_by_stage(progress)} + # Cases started before progress records existed: recover counters from console output. + recorded = [] + for log in case_dir.glob("client*.log"): + clean_log = re.sub(r"\x1b\[[0-9;]*m", "", log.read_text(errors="replace")) + updates = re.findall( + r"Success rate:\s*(\d+)\s*/\s*(\d+).*?current seed:\s*(\d+)", clean_log + ) + if updates: + success, completed, last_seed = map(int, updates[-1]) + recorded.append((completed, log.stat().st_mtime, success, last_seed, log)) + if not recorded: + return None + completed, _, success, last_seed, source_log = max(recorded) + if not 0 <= success <= completed: + raise RuntimeError(f"invalid partial eval counters: {success}/{completed}") + candidates = [p for p in result_dir.iterdir() if p.is_dir()] if result_dir.is_dir() else [] + matching = [p for p in candidates if all( + (p / f"episode{i}.mp4").is_file() and (p / f"episode{i}.mp4").stat().st_size > 1024 + for i in range(completed) + )] + if not matching: + raise RuntimeError(f"no result directory contains {completed} recorded episodes") + # An interrupted attempt before its first completed episode can create + # another directory. Prefer the directory with the most preserved videos. + save_dir = max(matching, key=lambda p: (len(list(p.glob("episode*.mp4"))), p.stat().st_mtime)) + return {"completed": completed, "success": success, "next_seed": last_seed + 1, + "save_dir": str(save_dir), "source": "console_log", "source_log": str(source_log)} + + +def run_case(args: argparse.Namespace, task: str, domain: str, out: Path) -> dict: + case_id = f"{domain}_{task}" + case_dir = out / "cases" / case_id + case_dir.mkdir(parents=True, exist_ok=True) + status_path = case_dir / "status.json" + previous = None + if args.resume and status_path.is_file(): + old = json.loads(status_path.read_text()) + if old.get("status") == "passed" and Path(old.get("result_file", "")).is_file(): + return old + previous = partial_case_state(case_dir, result_parent(task, domain, args.run_id)) + if previous and previous["completed"] >= args.test_num: + raise RuntimeError("all rollouts exist but the official result is missing; inspect before resuming") + status = {"task": task, "domain": domain, "test_num": args.test_num, + "status": "starting", "started_at": now(), "physical_gpu": os.environ["CUDA_VISIBLE_DEVICES"]} + if previous: + status["resume_from"] = previous + write_json(status_path, status) + server = client = None + try: + server_env = os.environ.copy() + server_env["ROBOTWIN_POLICY_HOST"] = "127.0.0.1" + server_env["ROBOTWIN_DIAGNOSTICS_DIR"] = str(case_dir / "diagnostics") + server_env["BIHUB_WAM_SAVE_PREDICTED_WORLD"] = "0" + server_env["BIHUB_INPUT_COLOR_ORDER"] = args.input_color_order + server_env["BIHUB_CODEC_INCREMENTAL"] = "1" if args.codec_incremental else "0" + server_env["BIHUB_STAGE_TIMING"] = "1" if args.stage_timing else "0" + server_env["BIHUB_STATE_SOURCE"] = args.state_source + server_env.pop("BIHUB_ACTION_CLIP_SIGMA", None) + if args.action_clip_sigma is not None: + server_env["BIHUB_ACTION_CLIP_SIGMA"] = repr(args.action_clip_sigma) + with (case_dir / "server.log").open("wb") as log: + server = subprocess.Popen( + ["bash", str(ROOT / "scripts/serve_policy.sh"), "BiHubJoint", str(args.deploy), str(args.port)], + cwd=ROOT, env=server_env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True, + ) + wait_server(server, args.port, args.server_timeout) + status["server_ready_at"] = now() + status["status"] = "running" + write_json(status_path, status) + env = os.environ.copy() + env["ROBOTWIN_STRICT_EVAL"] = "1" if args.strict_eval else "0" + env["ROBOTWIN_CONTROL_AUDIT"] = str(case_dir / "controller.jsonl") + env["PYTHONPATH"] = f"{EVAL_ROOT}:{EVAL_ROOT / 'XPolicyLab'}:{env.get('PYTHONPATH', '')}" + eval_script = EVAL_ROOT / "scripts/eval_policy_xpolicylab.py" + if args.color_pair_experiment: + env["WAM_ORIGINAL_EVAL_SCRIPT"] = str(eval_script) + env["WAM_COLOR_STAGE_DIAGNOSTICS"] = str(case_dir / "color_stages.jsonl") + env["BIHUB_INPUT_COLOR_ORDER"] = args.input_color_order + eval_script = ROOT / "mira/scripts/maintenance/eval_color_pair.py" + instruction = "seen" if domain == "demo_clean" else "unseen" + additional = f"ckpt_setting={args.run_id},action_type=joint,evaluation_id={case_id}" + command = [os.environ["ROBOTWIN_EVAL_PYTHON"], + str(ROOT / "mira/scripts/maintenance/run_robotwin_eval_prewarmed.py"), + "--eval-script", str(eval_script), + "--task_name", task, "--policy_name", "BiHubJoint", "--env_cfg_type", "arx_x5", + "--host", "127.0.0.1", "--port", str(args.port), "--protocol", "ws", + "--device_id", os.environ["CUDA_VISIBLE_DEVICES"], "--task_config", domain, + "--instruction_type", instruction, "--seed", "0", "--seed_start", str(args.seed_start), + "--test_num", str(args.test_num), "--expert_check", "true", + "--max_episode_attempts", str(args.max_episode_attempts), + "--max_consecutive_expert_errors", str(args.max_consecutive_expert_errors), + "--additional_info", additional] + if previous: + command[command.index("--seed_start") + 1] = str(previous["next_seed"]) + if previous["completed"]: + command.extend(["--resume_completed", str(previous["completed"]), + "--resume_success", str(previous["success"])]) + # Always reuse the result directory so attempt counters survive restarts. + command.extend(["--resume_save_dir", previous["save_dir"]]) + if (case_dir / "client.log").is_file(): + (case_dir / "client.log").rename( + case_dir / f"client.before-resume-{previous['completed']}-{int(time.time())}.log" + ) + started = time.time() + with (case_dir / "client.log").open("wb") as log: + client = subprocess.Popen(command, cwd=EVAL_ROOT, env=env, stdout=log, + stderr=subprocess.STDOUT, start_new_session=True) + while True: + try: + code = client.wait(timeout=30) + break + except subprocess.TimeoutExpired as exc: + if time.time() - started > args.case_timeout: + raise TimeoutError(f"simulator exceeded {args.case_timeout}s") from exc + if time.time() - (case_dir / "client.log").stat().st_mtime > args.stall_timeout: + raise TimeoutError(f"simulator log stalled for {args.stall_timeout}s") from exc + if code: + raise RuntimeError(f"simulator exited {code}; inspect {case_dir / 'client.log'}") + results = sorted( + (p for p in result_parent(task, domain, args.run_id).glob("*/_result.txt") + if p.stat().st_mtime >= started - 2), key=lambda p: p.stat().st_mtime, + ) + if not results: + raise RuntimeError("simulator exited without a new official _result.txt") + result = results[-1] + rate = float(result.read_text().splitlines()[-1]) + if not 0 <= rate <= 1: + raise ValueError(f"invalid success rate {rate}") + progress = read_progress(result.parent / PROGRESS_FILENAME) + if progress is None: + raise RuntimeError(f"official result {result} has no progress record") + abandoned = abandoned_episodes(progress) + if int(progress["completed"]) != args.test_num or round(rate * args.test_num) != int(progress["success"]): + raise RuntimeError(f"official result {result} disagrees with its progress record") + videos = verify_episode_videos(result.parent, progress) + if videos + len(abandoned) != args.test_num: + raise RuntimeError(f"expected {args.test_num} scored episodes, found {videos} videos " + f"and {len(abandoned)} abandoned") + status.update(status="passed", result_file=str(result), success=int(progress["success"]), + success_rate=rate, videos=videos, abandoned=abandoned, + skipped=skipped_by_stage(progress), progress_file=str(result.parent / PROGRESS_FILENAME), + resume_protocol=RESUME_PROTOCOL, finished_at=now()) + except BaseException as exc: + status.update(status="failed", error=repr(exc), finished_at=now()) + if isinstance(exc, (KeyboardInterrupt, SystemExit)): + raise + finally: + terminate(client) + terminate(server) + write_json(status_path, status) + return status + + +def main() -> int: + set_process_name() + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--deploy", type=Path, required=True) + parser.add_argument("--run-id", required=True) + parser.add_argument("--case", action="append", default=[], metavar="TASK:DOMAIN") + parser.add_argument("--all-tasks", action="store_true") + parser.add_argument("--shard-count", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + parser.add_argument("--test-num", type=int, default=1) + parser.add_argument("--seed-start", type=int, default=100000) + parser.add_argument("--port", type=int, default=21805) + parser.add_argument("--server-timeout", type=int, default=600) + parser.add_argument("--case-timeout", type=int, default=3600) + parser.add_argument("--stall-timeout", type=int, default=900) + parser.add_argument("--max-case-retries", type=int, default=20) + parser.add_argument("--max-episode-attempts", type=int, default=3, + help="A seed that cannot be completed after this many attempts is scored as a failure") + parser.add_argument("--max-consecutive-expert-errors", type=int, default=50, + help="Consecutive expert-demonstration exceptions that abort a case as broken") + parser.add_argument("--resume", action="store_true") + parser.add_argument("--input-color-order", choices=("auto", "rgb", "bgr"), default="auto") + parser.add_argument("--strict-eval", action="store_true", + help="Abort on infrastructure/language errors; deterministic per-seed instructions") + parser.add_argument("--color-pair-experiment", action="store_true") + parser.add_argument("--codec-incremental", action="store_true", + help="Reuse codec latents of frames already encoded in the previous plan") + parser.add_argument("--action-clip-sigma", type=float, + help="Override the checkpoint's normalized action clip (ablation only)") + parser.add_argument("--state-source", choices=("command", "observed"), default="command", + help="Adapter state history: issued waypoints (historical) or observed joints; " + "observed requires scripts/apply_eval_patches.sh") + parser.add_argument("--stage-timing", action="store_true", + help="Record synchronized per-stage policy latency in diagnostics") + args = parser.parse_args() + if not re.fullmatch(r"[A-Za-z0-9_.-]+", args.run_id): + parser.error("run-id must use only letters, digits, underscores, periods or dashes") + if not 1 <= args.test_num <= 100 or not 1 <= args.shard_count <= 100: + parser.error("test-num and shard-count must be in [1, 100]") + if not 0 <= args.shard_index < args.shard_count: + parser.error("shard-index must be in [0, shard-count)") + if not 1024 <= args.port <= 65535: + parser.error("port must be in [1024, 65535]") + if args.stall_timeout < 60 or args.max_case_retries < 0: + parser.error("stall-timeout must be >=60 and max-case-retries must be >=0") + if args.max_episode_attempts < 1 or args.max_consecutive_expert_errors < 1: + parser.error("max-episode-attempts and max-consecutive-expert-errors must be >=1") + if args.action_clip_sigma is not None and not 0 < args.action_clip_sigma < float("inf"): + parser.error("action-clip-sigma must be a positive finite number") + adapter = EVAL_ROOT / "XPolicyLab/policy/BiHubWAMV11/model.py" + if args.state_source != "command" and "BIHUB_STATE_SOURCE" not in adapter.read_text(): + parser.error("--state-source observed needs the patched adapter; run scripts/apply_eval_patches.sh") + if args.all_tasks == bool(args.case): + parser.error("choose --all-tasks or at least one --case") + tasks = sorted(p.stem for p in (EVAL_ROOT / "envs").glob("*.py") + if p.stem not in {"__init__", "_GLOBAL_CONFIGS", "_base_task"}) + if len(tasks) != 50: + parser.error(f"expected 50 official tasks, found {len(tasks)}") + if args.all_tasks: + cases = [(task, domain) for domain in DOMAINS for task in tasks] + else: + cases = [] + for item in args.case: + task, sep, domain = item.partition(":") + if not sep or task not in tasks or domain not in DOMAINS: + parser.error(f"invalid case {item!r}") + cases.append((task, domain)) + if len(cases) != len(set(cases)): + parser.error("duplicate cases") + cases = cases[args.shard_index::args.shard_count] + def interrupt(*_): + raise KeyboardInterrupt("evaluation interrupted") + signal.signal(signal.SIGTERM, interrupt) + signal.signal(signal.SIGINT, interrupt) + args.deploy = args.deploy.expanduser().resolve() + deployment = json.loads((args.deploy / "deployment.json").read_text()) + if deployment["architecture"] != "bihub-joint-world-action-anchor-v2": + parser.error("deployment is not a paired joint checkpoint") + from mira.joint.image_contract import resolve_deployment_color + args.input_color_order = resolve_deployment_color(deployment, args.input_color_order) + if args.strict_eval and args.color_pair_experiment: + parser.error("strict full evaluation and color-pair diagnostic protocols are separate") + print(f"Resolved checkpoint input color: {args.input_color_order}; strict_eval={args.strict_eval}", flush=True) + for filename, expected in deployment["sha256"].items(): + if digest(args.deploy / filename) != expected: + parser.error(f"deployment checksum mismatch: {filename}") + with socket.socket() as sock: + try: + sock.bind(("127.0.0.1", args.port)) + except OSError as exc: + parser.error(f"port {args.port} unavailable: {exc}") + out = ROOT / "artifacts/evaluation" / args.run_id / f"shard-{args.shard_index:02d}" + manifest_path = out / "manifest.json" + identity = {"run_id": args.run_id, "checkpoint_step": deployment["completed_steps"], + "checkpoint_fingerprint": deployment["joint_checkpoint_fingerprint"], + "deploy": str(args.deploy), "test_num": args.test_num, + "seed_start": args.seed_start, "cases": [list(case) for case in cases], + "shard_index": args.shard_index, "shard_count": args.shard_count, + "instruction": {"demo_clean": "seen", "demo_randomized": "unseen"}, + "expert_check": True, "policy": "BiHubJoint", "action_type": "joint", + "input_color_order": args.input_color_order, + "instruction_protocol": ("color_pair_seeded_candidates100_v1" if args.color_pair_experiment + else "strict_seeded_candidates100_v1" if args.strict_eval else "official"), + "strict_eval": args.strict_eval, + "codec_incremental": args.codec_incremental, + "action_clip_sigma": args.action_clip_sigma, + "state_source": args.state_source, + "process_name": os.environ.get("ROBOTWIN_PROCESS_NAME", ""), + "ray_denoiser": os.environ.get("ROBOTWIN_RAY_DENOISER", "oidn")} + if manifest_path.is_file(): + previous = json.loads(manifest_path.read_text()) + # Pre-color-audit manifests used the default RGB adapter. + previous.setdefault("input_color_order", "rgb") + previous.setdefault("instruction_protocol", "official") + previous.setdefault("strict_eval", False) + previous.setdefault("codec_incremental", False) + previous.setdefault("action_clip_sigma", None) + previous.setdefault("state_source", "command") + if not args.resume or any(previous.get(key) != value for key, value in identity.items()): + parser.error(f"existing run has different identity or --resume is missing: {manifest_path}") + else: + out.mkdir(parents=True, exist_ok=True) + write_json(manifest_path, {**identity, "created_at": now(), "host": socket.gethostname(), + "physical_gpu": os.environ["CUDA_VISIBLE_DEVICES"], + "simulator_source_sha256": digest(EVAL_ROOT / "scripts/eval_policy_xpolicylab.py"), + "robot_reset_sha256": digest(EVAL_ROOT / "envs/robot/robot.py"), + "renderer_source_sha256": digest(EVAL_ROOT / "envs/_base_task.py"), + "adapter_source_sha256": digest(EVAL_ROOT / "XPolicyLab/policy/BiHubWAMV11/model.py")}) + manifest = json.loads(manifest_path.read_text()) + manifest.setdefault("sessions", []).append({ + "started_at": now(), "host": socket.gethostname(), + "physical_gpu": os.environ["CUDA_VISIBLE_DEVICES"], + "simulator_source_sha256": digest(EVAL_ROOT / "scripts/eval_policy_xpolicylab.py"), + "runner_source_sha256": digest(Path(__file__)), + "websocket_keepalive_disabled": os.environ.get("ROBOTWIN_WS_DISABLE_KEEPALIVE") == "1", + "stall_timeout_s": args.stall_timeout, "max_case_retries": args.max_case_retries, + "resume_protocol": RESUME_PROTOCOL, "max_episode_attempts": args.max_episode_attempts, + "max_consecutive_expert_errors": args.max_consecutive_expert_errors, + "stage_timing": args.stage_timing, + }) + write_json(manifest_path, manifest) + preflight = out / "preflight.json" + env = os.environ.copy() + env["ROBOTWIN_PREFLIGHT_REPORT"] = str(preflight) + with (out / "preflight.log").open("wb") as log: + check = subprocess.run(["bash", str(ROOT / "scripts/preflight_robotwin_closed_loop.sh")], + cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT) + if check.returncode: + raise RuntimeError(f"RoboTwin preflight failed: {preflight}; see {out / 'preflight.log'}") + statuses = [] + for task, domain in cases: + for attempt in range(args.max_case_retries + 1): + status = run_case(args, task, domain, out) + if status["status"] == "passed": + break + print(f"{domain}/{task}: attempt {attempt + 1} failed: {status.get('error')}", flush=True) + args.resume = True + statuses.append(status) + write_json(out / "summary.json", {"run_id": args.run_id, "updated_at": now(), + "passed": sum(s["status"] == "passed" for s in statuses), + "failed": sum(s["status"] == "failed" for s in statuses), "cases": statuses}) + print(f"{domain}/{task}: {status['status']} {status.get('success', '-')}/{args.test_num}", flush=True) + return 1 if any(s["status"] != "passed" for s in statuses) else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/release-20261107/source/workspace_joint/mira/scripts/maintenance/run_joint_robotwin_formal.py b/release-20261107/source/workspace_joint/mira/scripts/maintenance/run_joint_robotwin_formal.py new file mode 100644 index 0000000000000000000000000000000000000000..6c435be6c74bc1bce589051180ccf2f5de1c6bae --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/maintenance/run_joint_robotwin_formal.py @@ -0,0 +1,488 @@ +#!/usr/bin/env python3 +"""Run RoboTwin 2.0 Full/ID evaluation from an exported joint checkpoint. + +Each concurrent simulator gets a dedicated stateful policy process. GPU slots +bound real concurrent workloads, including when another job shares a node. +""" + +from __future__ import annotations + +import argparse +from contextlib import ExitStack +import json +import os +import queue +import re +import shlex +import signal +import subprocess +import threading +import time +from concurrent.futures import ThreadPoolExecutor, as_completed +from datetime import datetime, timezone +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[3] +EVAL_ROOT = ROOT / "transfer/robotwin-official-20260921" +DEPLOY = ROOT / "outputs/joint_anchor_v2_24gpu_main/deploy-2449" +SIM_HOST = "172.29.112.43" +POLICY_HOSTS = ("172.29.252.24", "172.29.15.126", SIM_HOST) +KEYS = { + SIM_HOST: "/private/ssh_keys/root_dedicated-developjob-zhizhou-avgen-1-m8eyg_ed25519", + POLICY_HOSTS[1]: "/private/ssh_keys/root_dedicated-developjob-zhizhou-avgen-2-bjweu_ed25519", +} +SIM_PYTHON = "/private/software/conda/envs/robotwin-eval/bin/python" +ANSI = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]") +STOP = threading.Event() +MONITOR_STOP = threading.Event() +ACTIVE: dict[str, tuple[subprocess.Popen, str, Path]] = {} +LOCK = threading.Lock() +POLICY_GPU_SLOTS: dict[tuple[str, int], threading.Semaphore] = {} +SIM_GPU_SLOTS: dict[tuple[str, int], threading.Semaphore] = {} + + +def policy_slots(plan: str) -> tuple[list[tuple[str, int]], dict[str, int]]: + """Interleave hosts/GPUs so early jobs use the whole available cluster.""" + capacity: dict[str, int] = {} + for item in plan.split(","): + host, separator, value = item.partition(":") + if not separator or host not in POLICY_HOSTS or host in capacity: + raise ValueError(f"invalid policy-plan entry: {item!r}") + count = int(value) + if not 1 <= count <= 8: + raise ValueError("policy replicas per GPU must be in [1, 8]") + capacity[host] = count + if not capacity: + raise ValueError("policy-plan must not be empty") + slots = [(host, gpu) for layer in range(max(capacity.values())) + for gpu in range(8) for host, count in capacity.items() if layer < count] + return slots, capacity + + +def now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def atomic_json(path: Path, data: dict) -> None: + temp = path.with_suffix(path.suffix + ".tmp") + temp.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n") + temp.replace(path) + + +def remote_argv(host: str, command: str) -> list[str]: + if host == POLICY_HOSTS[0]: + return ["bash", "-lc", command] + return [ + "ssh", "-T", "-i", KEYS[host], "-o", "BatchMode=yes", + "-o", "ServerAliveInterval=30", "-o", "ServerAliveCountMax=4", + f"root@{host}", "bash -lc " + shlex.quote(command), + ] + + +def run_remote(host: str, command: str, timeout: float = 20) -> subprocess.CompletedProcess: + return subprocess.run(remote_argv(host, command), text=True, capture_output=True, timeout=timeout) + + +def gpu_memory(host: str) -> list[int]: + command = "nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits" + result = run_remote(host, command) + if result.returncode: + raise RuntimeError(f"GPU query failed on {host}: {result.stderr}") + values = [int(line.strip()) for line in result.stdout.splitlines() + if re.fullmatch(r"\s*\d+\s*", line)] + if len(values) != 8: + raise RuntimeError(f"unexpected GPU query on {host}: {result.stdout!r}") + return values + + +def gpu_used(host: str, gpu: int) -> int: + return gpu_memory(host)[gpu] + + +def wait_port(host: str, port: int, proc: subprocess.Popen, timeout: float = 600) -> None: + from websockets.sync.client import connect + + deadline = time.monotonic() + timeout + while time.monotonic() < deadline and not STOP.is_set(): + if proc.poll() is not None: + raise RuntimeError(f"policy server exited early: {proc.returncode}") + try: + with connect(f"ws://{host}:{port}", open_timeout=2, close_timeout=2): + return + except (OSError, TimeoutError): + time.sleep(2) + raise RuntimeError(f"policy server not reachable: {host}:{port}") + + +def start_process(host: str, command: str, log: Path, pidfile: Path) -> subprocess.Popen: + wrapped = f"echo $$ > {shlex.quote(str(pidfile))}; {command}" + stream = log.open("ab", buffering=0) + try: + proc = subprocess.Popen(remote_argv(host, wrapped), stdout=stream, stderr=subprocess.STDOUT, start_new_session=True) + finally: + stream.close() + with LOCK: + ACTIVE[str(pidfile)] = (proc, host, pidfile) + return proc + + +def stop_process(proc: subprocess.Popen, host: str, pidfile: Path) -> None: + if pidfile.is_file(): + # PID file belongs to this specific evaluation worker, not a process-name match. + run_remote(host, f"kill -TERM $(cat {shlex.quote(str(pidfile))}) 2>/dev/null || true", timeout=10) + try: + proc.wait(timeout=15) + except subprocess.TimeoutExpired: + proc.terminate() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + proc.kill() + with LOCK: + ACTIVE.pop(str(pidfile), None) + + +def result_dir(task: str, domain: str, run_id: str) -> Path: + return EVAL_ROOT / "eval_result" / task / "BiHubJoint" / domain / run_id + + +def evaluate_one(index: int, task: str, domain: str, args: argparse.Namespace, out: Path) -> dict: + sim_host = args.sim_hosts[index % len(args.sim_hosts)] + sim_gpu = (index // len(args.sim_hosts)) % 8 + port = args.port_base + index + job_id = f"{index:03d}_{domain}_{task}" + job_dir = out / "jobs" / job_id + job_dir.mkdir(parents=True, exist_ok=True) + status_file = job_dir / "status.json" + if args.resume and status_file.is_file(): + prior = json.loads(status_file.read_text()) + if prior.get("status") == "passed" and Path(prior["result_file"]).is_file(): + return prior + if args.policy_plan: + # Keep the scarce simulator slot busy and borrow any free policy + # replica, avoiding a long tail pinned to one arbitrary policy GPU. + with SIM_GPU_SLOTS[(sim_host, sim_gpu)]: + host, policy_gpu = args.policy_queue.get() + try: + return _run_one_active(index, task, domain, args, out, host, policy_gpu, + sim_host, sim_gpu, port, job_id, job_dir, status_file) + finally: + args.policy_queue.put((host, policy_gpu)) + if args.policy_host: + host = args.policy_host + policy_gpu = index % 8 + else: + # Legacy topology: six replicas per GPU on the two inference nodes, + # then one replica on four simulator GPUs. + host = POLICY_HOSTS[index % 2] if index < 96 else SIM_HOST + policy_gpu = (index // 2) % 8 if index < 96 else index - 96 + with ExitStack() as slots: + if args.policy_host: + slots.enter_context(POLICY_GPU_SLOTS[(host, policy_gpu)]) + if len(args.sim_hosts) > 1: + slots.enter_context(SIM_GPU_SLOTS[(sim_host, sim_gpu)]) + return _run_one_active(index, task, domain, args, out, host, policy_gpu, + sim_host, sim_gpu, port, job_id, job_dir, status_file) + + +def _run_one_active(index: int, task: str, domain: str, args: argparse.Namespace, + out: Path, host: str, policy_gpu: int, sim_host: str, + sim_gpu: int, port: int, job_id: str, job_dir: Path, + status_file: Path) -> dict: + resume = {} + resume_file = job_dir / "resume.json" + if args.resume and resume_file.is_file(): + resume = json.loads(resume_file.read_text()) + if resume.get("original_test_num") != args.test_num: + raise RuntimeError(f"resume target mismatch: {resume_file}") + status = { + "job_id": job_id, "task": task, "domain": domain, "policy_host": host, + "policy_gpu": policy_gpu, "sim_host": sim_host, "sim_gpu": sim_gpu, + "port": port, "test_num": args.test_num, "status": "starting", "started_at": now(), + "resumed_episodes": int(resume.get("completed", 0)), + } + atomic_json(status_file, status) + server = client = None + server_pid = job_dir / "server.pid" + client_pid = job_dir / "client.pid" + try: + if STOP.is_set(): + raise RuntimeError("supervisor stopping") + # A model replica uses ~18 GiB and a simulator ~7 GiB in the measured + # smoke. Keep >=10 GiB of H200 headroom even during a scale-up. + if gpu_used(host, policy_gpu) > 111000: + raise RuntimeError(f"policy GPU {host}:{policy_gpu} lacks safe headroom") + if gpu_used(sim_host, sim_gpu) > 123000: + raise RuntimeError(f"sim GPU {sim_host}:{sim_gpu} lacks safe headroom") + policy_cmd = ( + f"cd {shlex.quote(str(ROOT))} && unset http_proxy https_proxy all_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY " + f"&& export CUDA_VISIBLE_DEVICES={policy_gpu} ROBOTWIN_POLICY_HOST=0.0.0.0 " + f"&& exec -a filter_x_server bash scripts/serve_policy.sh BiHubJoint {shlex.quote(str(args.deploy_path))} {port}" + ) + server = start_process(host, policy_cmd, job_dir / "server.log", server_pid) + wait_port(host, port, server) + status["status"] = "running" + status["server_ready_at"] = now() + atomic_json(status_file, status) + instruction = "seen" if domain == "demo_clean" else "unseen" + additional = f"ckpt_setting={args.run_id},action_type=joint,evaluation_id={job_id}" + start_seed = int(resume.get("next_seed", 100000)) + resume_flags = "" + if resume: + resume_flags = ( + f" --resume_completed {int(resume['completed'])}" + f" --resume_success {int(resume['success'])}" + f" --resume_save_dir {shlex.quote(str(resume['save_dir']))}" + ) + client_cmd = ( + f"cd {shlex.quote(str(ROOT))} && source scripts/setup_robotwin_graphics_env.sh " + f"&& unset http_proxy https_proxy all_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY " + f"&& export CUDA_VISIBLE_DEVICES={sim_gpu} PYTHONUNBUFFERED=1 " + f"ROBOTWIN_CONTROL_AUDIT={shlex.quote(str(job_dir / 'controller.jsonl'))} " + f"PYTHONPATH={shlex.quote(str(EVAL_ROOT) + ':' + str(EVAL_ROOT / 'XPolicyLab'))} " + f"&& cd {shlex.quote(str(EVAL_ROOT))} " + f"&& exec -a filter_x_sim {SIM_PYTHON} {shlex.quote(str(ROOT / 'mira/scripts/maintenance/run_robotwin_eval_prewarmed.py'))} " + f"--eval-script scripts/eval_policy_xpolicylab.py --task_name {task} " + f"--policy_name BiHubJoint --env_cfg_type arx_x5 --host {host} --port {port} " + f"--protocol ws --device_id {sim_gpu} --task_config {domain} " + f"--instruction_type {instruction} --seed 0 --seed_start {start_seed} " + f"--test_num {args.test_num} --additional_info {shlex.quote(additional)}{resume_flags}" + ) + client = start_process(sim_host, client_cmd, job_dir / "client.log", client_pid) + client_rc = client.wait() + with LOCK: + ACTIVE.pop(str(client_pid), None) + if client_rc: + raise RuntimeError(f"simulator exited {client_rc}; see {job_dir / 'client.log'}") + results = sorted(result_dir(task, domain, args.run_id).glob("*/_result.txt"), key=lambda p: p.stat().st_mtime) + if not results: + raise RuntimeError("simulator exited successfully without _result.txt") + result = results[-1] + rate = float(result.read_text().strip().splitlines()[-1]) + successes = round(rate * args.test_num) + videos = len(list(result.parent.glob("episode*.mp4"))) + status.update(status="passed", success=successes, rate=rate, videos=videos, + result_file=str(result), finished_at=now()) + except Exception as exc: + status.update(status="failed", error=str(exc), finished_at=now()) + finally: + if client is not None and client.poll() is None: + stop_process(client, sim_host, client_pid) + if server is not None: + stop_process(server, host, server_pid) + atomic_json(status_file, status) + return status + + +def summarize(out: Path, jobs: list[dict]) -> None: + summary = {"run_id": out.name, "updated_at": now(), "total_jobs": len(jobs), + "passed_jobs": sum(job["status"] == "passed" for job in jobs), + "failed_jobs": sum(job["status"] == "failed" for job in jobs), + "rollouts_completed": sum(job.get("test_num", 0) for job in jobs if job["status"] == "passed"), + "successes": sum(job.get("success", 0) for job in jobs), + "jobs": jobs} + completed = summary["rollouts_completed"] + summary["success_rate"] = summary["successes"] / completed if completed else None + domains = {} + for domain in ("demo_clean", "demo_randomized"): + passed = [job for job in jobs if job.get("status") == "passed" and job.get("domain") == domain] + rollouts = sum(int(job["test_num"]) for job in passed) + successes = sum(int(job["success"]) for job in passed) + domains[domain] = { + "completed_tasks": len(passed), "completed_rollouts": rollouts, + "successes": successes, + "mean_task_success_rate": (sum(float(job["rate"]) for job in passed) / len(passed) + if passed else None), + "micro_success_rate": successes / rollouts if rollouts else None, + } + summary["domains"] = domains + if all(domains[domain]["completed_tasks"] == 50 for domain in domains): + summary["average_easy_hard"] = ( + domains["demo_clean"]["mean_task_success_rate"] + + domains["demo_randomized"]["mean_task_success_rate"] + ) / 2 + atomic_json(out / "summary.json", summary) + + +def monitor_progress(out: Path, total_jobs: int, test_num: int) -> None: + pattern = re.compile(r"Success rate:\s*(\d+)/(\d+)") + while not MONITOR_STOP.is_set(): + states = [] + for status_file in sorted((out / "jobs").glob("*/status.json")): + try: + state = json.loads(status_file.read_text()) + if state["status"] == "running": + log = status_file.with_name("client.log") + if log.is_file(): + with log.open("rb") as stream: + stream.seek(max(0, log.stat().st_size - 200000)) + tail = ANSI.sub("", stream.read().decode(errors="replace")) + matches = pattern.findall(tail) + if matches: + state["live_success"], state["live_episodes"] = map(int, matches[-1]) + states.append(state) + except (OSError, ValueError, KeyError, json.JSONDecodeError): + continue + completed = [state for state in states if state["status"] == "passed"] + running = [state for state in states if state["status"] == "running"] + progress = { + "updated_at": now(), "total_jobs": total_jobs, + "planned_rollouts": total_jobs * test_num, + "passed_jobs": len(completed), + "failed_jobs": sum(state["status"] == "failed" for state in states), + "running_jobs": len(running), + "completed_rollouts": len(completed) * test_num, + "completed_successes": sum(state.get("success", 0) for state in completed), + "inflight_rollouts": sum(state.get("live_episodes", 0) for state in running), + "inflight_successes": sum(state.get("live_success", 0) for state in running), + "jobs": states, + } + count = progress["completed_rollouts"] + progress["inflight_rollouts"] + successes = progress["completed_successes"] + progress["inflight_successes"] + progress["provisional_success_rate"] = successes / count if count else None + try: + progress["gpu_memory_mib"] = {host: gpu_memory(host) for host in POLICY_HOSTS} + except (RuntimeError, subprocess.TimeoutExpired) as exc: + progress["gpu_memory_error"] = str(exc) + atomic_json(out / "progress.json", progress) + MONITOR_STOP.wait(60) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--run-id", default="joint2449_formal20_20260930") + parser.add_argument("--deploy-path", type=Path, default=DEPLOY) + parser.add_argument("--test-num", type=int, default=20) + parser.add_argument("--max-workers", type=int, default=24) + parser.add_argument("--port-base", type=int, default=19700) + parser.add_argument("--launch-interval", type=float, default=5.0) + parser.add_argument("--policy-host", choices=POLICY_HOSTS, + help="Use one host for all stateful policy replicas") + parser.add_argument("--policy-plan", + help="Comma-separated HOST:replicas-per-GPU pairs, e.g. node12:4,node17:6") + parser.add_argument("--sim-hosts", default=SIM_HOST, + help="Comma-separated graphics-capable simulator hosts") + parser.add_argument("--sim-slots-per-gpu", type=int, default=3, + help="Maximum concurrent simulator clients per GPU for planned topology") + parser.add_argument("--resume", action="store_true") + parser.add_argument("--pilot", action="store_true", help="Run one clean and one randomized task") + args = parser.parse_args() + if not re.fullmatch(r"[A-Za-z0-9_.-]+", args.run_id): + parser.error("run-id must contain only ASCII letters, digits, _ . -") + if not 1 <= args.max_workers <= 100 or not 1 <= args.test_num <= 100: + parser.error("max-workers and test-num must be in [1, 100]") + args.sim_hosts = tuple(dict.fromkeys(args.sim_hosts.split(","))) + if not args.sim_hosts or any(host not in POLICY_HOSTS for host in args.sim_hosts): + parser.error(f"sim-hosts must be drawn from {POLICY_HOSTS}") + if args.policy_host and args.max_workers > 48: + parser.error("one policy host supports at most 48 concurrent replicas (six per GPU)") + if args.policy_host and args.policy_plan: + parser.error("--policy-host and --policy-plan are mutually exclusive") + if not 1 <= args.sim_slots_per_gpu <= 12: + parser.error("sim-slots-per-gpu must be in [1, 12]") + args.policy_slots = [] + args.policy_capacity = {} + args.policy_queue = queue.Queue() + if args.policy_plan: + try: + args.policy_slots, args.policy_capacity = policy_slots(args.policy_plan) + except ValueError as exc: + parser.error(str(exc)) + if args.max_workers > len(args.policy_slots): + parser.error("max-workers exceeds available policy replicas in policy-plan") + for slot in args.policy_slots: + args.policy_queue.put(slot) + elif args.policy_host: + for gpu in range(8): + POLICY_GPU_SLOTS[(args.policy_host, gpu)] = threading.Semaphore(6) + for host in args.sim_hosts: + for gpu in range(8): + SIM_GPU_SLOTS[(host, gpu)] = threading.Semaphore(args.sim_slots_per_gpu) + args.deploy_path = args.deploy_path.resolve() + if not args.deploy_path.is_dir(): + parser.error(f"missing deployment: {args.deploy_path}") + out = ROOT / "artifacts/evaluation" / args.run_id + out.mkdir(parents=True, exist_ok=True) + tasks = sorted(p.stem for p in (EVAL_ROOT / "envs").glob("*.py") + if p.stem not in {"__init__", "_GLOBAL_CONFIGS", "_base_task"}) + if len(tasks) != 50: + parser.error(f"expected 50 official tasks, found {len(tasks)}") + jobs = [(task, domain) for domain in ("demo_clean", "demo_randomized") for task in tasks] + if args.pilot: + jobs = [("adjust_bottle", "demo_clean"), ("click_bell", "demo_randomized")] + # Fail before launching any policy replica when a requested simulator node + # cannot initialize the actual SAPIEN ray-tracing renderer. + for host in args.sim_hosts: + report = out / f"preflight_sim_{host.replace('.', '_')}.json" + command = ( + f"cd {shlex.quote(str(ROOT))} && unset http_proxy https_proxy all_proxy " + f"HTTP_PROXY HTTPS_PROXY ALL_PROXY && " + f"ROBOTWIN_PREFLIGHT_REPORT={shlex.quote(str(report))} " + "bash scripts/preflight_robotwin_closed_loop.sh" + ) + result = run_remote(host, command, timeout=180) + if result.returncode: + parser.error(f"simulator preflight failed on {host}; see {report}: {result.stderr[-1000:]}") + deployment = json.loads((args.deploy_path / "deployment.json").read_text()) + robotwin_commit = subprocess.check_output( + ["git", "-C", str(EVAL_ROOT), "rev-parse", "HEAD"], text=True).strip() + scope = "RoboTwin2.0 Full/ID 100-trial" if args.test_num == 100 else f"RoboTwin2.0 Full/ID diagnostic {args.test_num}-trial" + manifest_path = out / "manifest.json" + previous = json.loads(manifest_path.read_text()) if manifest_path.is_file() else None + if previous is not None: + if not args.resume: + parser.error(f"existing run requires --resume: {out}") + for field, expected in ( + ("checkpoint_fingerprint", deployment["joint_checkpoint_fingerprint"]), + ("test_num_per_task_domain", args.test_num), ("tasks", tasks), + ("domains", ["demo_clean", "demo_randomized"]), + ): + if previous.get(field) != expected: + parser.error(f"resume manifest mismatch in {field}: {manifest_path}") + manifest = {"run_id": args.run_id, "checkpoint": str(args.deploy_path), "scope": scope, + "checkpoint_step": deployment["completed_steps"], + "checkpoint_fingerprint": deployment["joint_checkpoint_fingerprint"], + "robotwin_commit": robotwin_commit, + "tasks": tasks, "domains": ["demo_clean", "demo_randomized"], + "test_num_per_task_domain": args.test_num, "expert_check": True, + "seed": 0, "seed_start": 100000, "simulator_host": args.sim_hosts[0], + "simulator_hosts": args.sim_hosts, "policy_host": args.policy_host, + "policy_plan": args.policy_plan, "sim_slots_per_gpu": args.sim_slots_per_gpu, + "policy_hosts": POLICY_HOSTS, "max_workers": args.max_workers, + "launch_interval_seconds": args.launch_interval, + "created_at": previous["created_at"] if previous else now()} + manifest["topology_history"] = (previous or {}).get("topology_history", []) + [{ + "at": now(), "policy_host": args.policy_host, "simulator_hosts": args.sim_hosts, + "policy_plan": args.policy_plan, "sim_slots_per_gpu": args.sim_slots_per_gpu, + "max_workers": args.max_workers, + }] + atomic_json(manifest_path, manifest) + monitor = threading.Thread(target=monitor_progress, args=(out, len(jobs), args.test_num), daemon=True) + monitor.start() + def handle_stop(*_): + STOP.set() + signal.signal(signal.SIGTERM, handle_stop) + signal.signal(signal.SIGINT, handle_stop) + completed: list[dict] = [] + with ThreadPoolExecutor(max_workers=args.max_workers) as pool: + futures = [] + for index, (task, domain) in enumerate(jobs): + if STOP.is_set(): + break + futures.append(pool.submit(evaluate_one, index, task, domain, args, out)) + time.sleep(args.launch_interval) + for future in as_completed(futures): + result = future.result() + completed.append(result) + summarize(out, completed) + print(f"[{now()}] {result['job_id']}: {result['status']} " + f"{result.get('success', '-')}/{result.get('test_num', '-')} " + f"({len(completed)}/{len(jobs)} jobs)", flush=True) + MONITOR_STOP.set() + monitor.join(timeout=5) + return 1 if any(j["status"] != "passed" for j in completed) or STOP.is_set() else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/release-20261107/source/workspace_joint/mira/scripts/maintenance/run_prompt_ablation_resumable.py b/release-20261107/source/workspace_joint/mira/scripts/maintenance/run_prompt_ablation_resumable.py new file mode 100644 index 0000000000000000000000000000000000000000..9e854322dc6802e04bc62be3cd2029e9fd4ef6b2 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/maintenance/run_prompt_ablation_resumable.py @@ -0,0 +1,205 @@ +"""Resume the 25k prompt ablation after a wedged simulator without repeating episodes.""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import re +import signal +import subprocess +import time + + +CASES = [ + ("handover_block", "train_exact"), + ("handover_block", "complete_goal"), + ("pick_dual_bottles", "train_exact"), + ("pick_dual_bottles", "complete_goal"), +] +ANSI = re.compile(r"\x1b\[[0-9;]*m") +RESULT = re.compile(r"Success rate:\s*(\d+)/(\d+).*?current seed:\s*(\d+)") +ACTIVE: subprocess.Popen | None = None + + +def stop_active() -> None: + global ACTIVE + if ACTIVE is None or ACTIVE.poll() is not None: + return + os.killpg(ACTIVE.pid, signal.SIGTERM) + try: + ACTIVE.wait(timeout=15) + except subprocess.TimeoutExpired: + os.killpg(ACTIVE.pid, signal.SIGKILL) + ACTIVE.wait() + ACTIVE = None + + +def on_signal(_signum: int, _frame: object) -> None: + stop_active() + raise SystemExit(128 + _signum) + + +def save_state(path: Path, state: dict) -> None: + temp = path.with_suffix(".json.tmp") + temp.write_text(json.dumps(state, indent=2) + "\n") + temp.replace(path) + + +def result_dir(eval_root: Path, task: str, condition: str) -> Path: + run_id = f"joint25000_prompt_ablation_20261020_{condition}" + return eval_root / "eval_result" / task / "BiHubJoint" / "demo_clean" / run_id + + +def latest_result_dir(eval_root: Path, task: str, condition: str) -> str: + dirs = [p for p in result_dir(eval_root, task, condition).glob("*") if p.is_dir()] + if not dirs: + raise RuntimeError(f"No result directory for {task}/{condition}") + return str(max(dirs, key=lambda p: p.name).resolve()) + + +def last_progress(log: Path) -> tuple[int, int, int] | None: + if not log.exists(): + return None + clean = ANSI.sub("", log.read_text(errors="replace")) + matches = RESULT.findall(clean) + if not matches: + return None + success, completed, seed = map(int, matches[-1]) + return success, completed, seed + + +def append_progress(path: Path, message: str) -> None: + with path.open("a") as file: + file.write(f"{time.strftime('%Y-%m-%dT%H:%M:%S%z')} {message}\n") + print(message, flush=True) + + +def main() -> None: + global ACTIVE + parser = argparse.ArgumentParser() + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--eval-root", type=Path, required=True) + parser.add_argument("--python", type=Path, required=True) + parser.add_argument("--wrapper", type=Path, required=True) + parser.add_argument("--port", type=int, required=True) + parser.add_argument("--gpu", required=True) + args = parser.parse_args() + for signum in (signal.SIGTERM, signal.SIGINT): + signal.signal(signum, on_signal) + + state_file = args.out / "resume_state.json" + if state_file.exists(): + state = json.loads(state_file.read_text()) + else: + prior = last_progress(args.out / "logs/handover_block_train_exact.log") + if prior is None: + raise RuntimeError("Cannot recover the ten completed episodes") + success, completed, seed = prior + state = { + f"{task}_{condition}": { + "completed": 0, + "success": 0, + "next_seed": 100000, + "save_dir": None, + } + for task, condition in CASES + } + first = state["handover_block_train_exact"] + first.update( + completed=completed, + success=success, + next_seed=seed + 1, + save_dir=latest_result_dir(args.eval_root, "handover_block", "train_exact"), + ) + save_state(state_file, state) + + progress_file = args.out / "progress.log" + for task, condition in CASES: + case_id = f"{task}_{condition}" + current = state[case_id] + run_id = f"joint25000_prompt_ablation_20261020_{condition}" + failures = 0 + while current["completed"] < 20: + before = current["completed"] + attempt = int(time.time() * 1000) + log = args.out / "logs/attempts" / f"{case_id}_from{before}_{attempt}.log" + command = [ + str(args.python), + str(args.out.parents[2] / "mira/scripts/maintenance/run_robotwin_eval_prewarmed.py"), + "--eval-script", str(args.wrapper), + "--task_name", task, + "--policy_name", "BiHubJoint", + "--env_cfg_type", "arx_x5", + "--host", "127.0.0.1", + "--port", str(args.port), + "--protocol", "ws", + "--device_id", str(args.gpu), + "--task_config", "demo_clean", + "--instruction_type", "seen", + "--seed", "0", + "--seed_start", str(current["next_seed"]), + "--test_num", "20", + "--additional_info", f"ckpt_setting={run_id},action_type=joint,evaluation_id={case_id}", + ] + if before: + command.extend([ + "--resume_completed", str(before), + "--resume_success", str(current["success"]), + "--resume_save_dir", current["save_dir"], + ]) + env = os.environ.copy() + env["CUDA_VISIBLE_DEVICES"] = str(args.gpu) + env["WAM_PROMPT_FILE"] = str(args.out / "prompts" / f"{case_id}.txt") + env["ROBOTWIN_CONTROL_AUDIT"] = str(args.out / "diagnostics" / f"{case_id}_controller.jsonl") + append_progress(progress_file, f"RESUME case={task}/{condition} completed={before}/20 success={current['success']} seed={current['next_seed']}") + with log.open("w") as output: + ACTIVE = subprocess.Popen(command, cwd=args.eval_root, env=env, stdout=output, stderr=subprocess.STDOUT, start_new_session=True) + last_update = time.monotonic() + last_size = -1 + while ACTIVE.poll() is None: + time.sleep(5) + size = log.stat().st_size + if size != last_size: + last_size = size + last_update = time.monotonic() + result = last_progress(log) + if result is not None and result[1] > current["completed"]: + success, completed, seed = result + if not before and current["save_dir"] is None: + current["save_dir"] = latest_result_dir(args.eval_root, task, condition) + current.update(completed=completed, success=success, next_seed=seed + 1) + save_state(state_file, state) + failures = 0 + append_progress(progress_file, f"EPISODE_DONE case={task}/{condition} success={success}/{completed} seed={seed}") + if time.monotonic() - last_update > 300: + append_progress(progress_file, f"WATCHDOG case={task}/{condition} no_output=300s restarting_simulator") + stop_active() + break + if ACTIVE is not None: + exit_code = ACTIVE.wait() + ACTIVE = None + else: + exit_code = 124 + result = last_progress(log) + if result is not None and result[1] > current["completed"]: + success, completed, seed = result + if not before and current["save_dir"] is None: + current["save_dir"] = latest_result_dir(args.eval_root, task, condition) + current.update(completed=completed, success=success, next_seed=seed + 1) + save_state(state_file, state) + failures = 0 + append_progress(progress_file, f"EPISODE_DONE case={task}/{condition} success={success}/{completed} seed={seed}") + if current["completed"] == 20: + append_progress(progress_file, f"DONE case={task}/{condition} success={current['success']}/20") + break + if current["completed"] == before: + failures += 1 + append_progress(progress_file, f"RETRY case={task}/{condition} failures={failures} exit={exit_code}") + if failures >= 5: + raise RuntimeError(f"{case_id} failed five times without completing an episode") + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/maintenance/run_prompt_validation_case.py b/release-20261107/source/workspace_joint/mira/scripts/maintenance/run_prompt_validation_case.py new file mode 100644 index 0000000000000000000000000000000000000000..2393a9688cff31fd297c4e2a5e2686a52f141010 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/maintenance/run_prompt_validation_case.py @@ -0,0 +1,134 @@ +"""Run one paired prompt condition and resume after simulator stalls.""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import re +import signal +import subprocess +import time + + +ANSI = re.compile(r"\x1b\[[0-9;]*m") +RESULT = re.compile(r"Success rate:\s*(\d+)/(\d+).*?current seed:\s*(\d+)") +ACTIVE: subprocess.Popen | None = None + + +def stop(_signum=None, _frame=None): + global ACTIVE + if ACTIVE is not None and ACTIVE.poll() is None: + os.killpg(ACTIVE.pid, signal.SIGTERM) + try: + ACTIVE.wait(timeout=15) + except subprocess.TimeoutExpired: + os.killpg(ACTIVE.pid, signal.SIGKILL) + ACTIVE.wait() + ACTIVE = None + if _signum is not None: + raise SystemExit(128 + _signum) + + +def progress(log): + if not log.exists(): + return None + hits = RESULT.findall(ANSI.sub("", log.read_text(errors="replace"))) + return tuple(map(int, hits[-1])) if hits else None + + +def save(path, state): + temp = path.with_suffix(".tmp") + temp.write_text(json.dumps(state, indent=2) + "\n") + temp.replace(path) + + +def main(): + global ACTIVE + p = argparse.ArgumentParser() + for name in ("out", "eval-root", "python", "wrapper", "prompt-file", "task", "condition", "gpu"): + p.add_argument("--" + name, required=True) + for name in ("port", "test-num"): + p.add_argument("--" + name, type=int, required=True) + args = p.parse_args() + for signum in (signal.SIGTERM, signal.SIGINT): + signal.signal(signum, stop) + out = Path(args.out) + root = Path(args.eval_root) + (out / "logs/attempts").mkdir(parents=True, exist_ok=True) + (out / "diagnostics").mkdir(parents=True, exist_ok=True) + case = f"{args.task}_{args.condition}" + state_path = out / "resume_state.json" + state = json.loads(state_path.read_text()) if state_path.exists() else { + "task": args.task, "condition": args.condition, "target": args.test_num, + "completed": 0, "success": 0, "next_seed": 100000, "save_dir": None, + } + if (state["task"], state["condition"], state["target"]) != (args.task, args.condition, args.test_num): + raise ValueError("Existing state belongs to a different evaluation") + save(state_path, state) + run_id = f"joint25000_factorial_20261021_{args.condition}" + result_root = root / "eval_result" / args.task / "BiHubJoint" / "demo_clean" / run_id + failures = 0 + while state["completed"] < args.test_num: + before = state["completed"] + log = out / "logs/attempts" / f"{case}_from{before}_{int(time.time()*1000)}.log" + command = [ + args.python, + str(out.parents[3] / "mira/scripts/maintenance/run_robotwin_eval_prewarmed.py"), + "--eval-script", args.wrapper, "--task_name", args.task, + "--policy_name", "BiHubJoint", "--env_cfg_type", "arx_x5", + "--host", "127.0.0.1", "--port", str(args.port), "--protocol", "ws", + "--device_id", args.gpu, "--task_config", "demo_clean", + "--instruction_type", "seen", "--seed", "0", + "--seed_start", str(state["next_seed"]), "--test_num", str(args.test_num), + "--additional_info", f"ckpt_setting={run_id},action_type=joint,evaluation_id={case}", + ] + if before: + command += ["--resume_completed", str(before), "--resume_success", str(state["success"]), "--resume_save_dir", state["save_dir"]] + env = os.environ.copy() + env.update( + CUDA_VISIBLE_DEVICES=args.gpu, + WAM_PROMPT_CONDITION=args.condition, + WAM_TRAIN_PROMPT_FILE=args.prompt_file, + WAM_STAGE_DIAGNOSTICS=str(out / "diagnostics/stages.jsonl"), + ROBOTWIN_CONTROL_AUDIT=str(out / "diagnostics/controller.jsonl"), + ) + print(f"START {case} {before}/{args.test_num} seed={state['next_seed']}", flush=True) + with log.open("w") as output: + ACTIVE = subprocess.Popen(command, cwd=root, env=env, stdout=output, stderr=subprocess.STDOUT, start_new_session=True) + last_size, last_change = -1, time.monotonic() + while ACTIVE.poll() is None: + time.sleep(5) + size = log.stat().st_size + if size != last_size: + last_size, last_change = size, time.monotonic() + hit = progress(log) + if hit and hit[1] > state["completed"]: + success, completed, seed = hit + if state["save_dir"] is None: + dirs = [x for x in result_root.glob("*") if x.is_dir()] + if not dirs: + raise RuntimeError(f"Missing result directory under {result_root}") + state["save_dir"] = str(max(dirs, key=lambda x: x.name).resolve()) + state.update(completed=completed, success=success, next_seed=seed + 1) + save(state_path, state) + failures = 0 + print(f"DONE_EPISODE {case} success={success}/{completed} seed={seed}", flush=True) + if time.monotonic() - last_change > 300: + print(f"WATCHDOG {case} no output for 300s", flush=True) + stop() + break + if ACTIVE is not None: + ACTIVE.wait() + ACTIVE = None + if state["completed"] == before: + failures += 1 + if failures >= 5: + raise RuntimeError(f"Five consecutive attempts made no progress: {case}") + time.sleep(5) + print(f"COMPLETE {case} success={state['success']}/{args.test_num}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/maintenance/run_robotwin_eval_prewarmed.py b/release-20261107/source/workspace_joint/mira/scripts/maintenance/run_robotwin_eval_prewarmed.py new file mode 100644 index 0000000000000000000000000000000000000000..969e127814c1b7074a4b3a9c9950d2a35acb8c71 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/maintenance/run_robotwin_eval_prewarmed.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +"""Start the XPolicyLab evaluator with CUDA/cuRobo initialized before SAPIEN.""" +from __future__ import annotations + +import argparse +import ctypes +import os +import runpy +import sys +import types +from pathlib import Path + + +def prewarm() -> None: + import torch + + if not torch.cuda.is_available(): + raise RuntimeError("CUDA is unavailable in the RoboTwin evaluator") + torch.cuda.init() + _ = torch.zeros(1, device="cuda") + from curobo.wrap.reacher.motion_gen import MotionGen # noqa: F401 + + # cuRobo v0.7.8 uses the legacy wp.torch namespace. Warp 1.12 keeps the + # functions at module scope, so expose a compatibility namespace before + # any planner is constructed. + import warp as wp + + if not hasattr(wp, "torch"): + wp.torch = types.SimpleNamespace( + from_torch=getattr(wp, "from_torch", None), + to_torch=getattr(wp, "to_torch", None), + dtype_from_torch=getattr(wp, "dtype_from_torch", None), + dtype_to_torch=getattr(wp, "dtype_to_torch", None), + device_from_torch=getattr(wp, "device_from_torch", None), + device_to_torch=getattr(wp, "device_to_torch", None), + stream_from_torch=getattr(wp, "stream_from_torch", None), + stream_to_torch=getattr(wp, "stream_to_torch", None), + ) + print("[robotwin-eval] prewarmed CUDA/cuRobo before SAPIEN", flush=True) + + +def main() -> None: + name = os.environ.get("ROBOTWIN_PROCESS_NAME") + if name: + ctypes.CDLL(None).prctl(15, name.encode()[:15], 0, 0, 0) + parser = argparse.ArgumentParser(add_help=False) + parser.add_argument("--eval-script", type=Path, required=True) + known, remaining = parser.parse_known_args() + eval_script = known.eval_script.expanduser().resolve() + if not eval_script.is_file(): + raise FileNotFoundError(eval_script) + prewarm() + sys.argv = [str(eval_script), *remaining] + runpy.run_path(str(eval_script), run_name="__main__") + + +if __name__ == "__main__": + main() + diff --git a/release-20261107/source/workspace_joint/mira/scripts/maintenance/stop_joint_robotwin_eval.py b/release-20261107/source/workspace_joint/mira/scripts/maintenance/stop_joint_robotwin_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..be2e69d290b71cabf4b30b47256f9a3295e8ed2e --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/maintenance/stop_joint_robotwin_eval.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Stop only the PID-file-owned clients/servers of one joint eval run.""" + +from __future__ import annotations + +import argparse +import json +import re +import shlex +import subprocess +import time +from datetime import datetime, timezone +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[3] +LOCAL_HOST = "172.29.252.24" +KEYS = { + "172.29.15.126": "/private/ssh_keys/root_dedicated-developjob-zhizhou-avgen-2-bjweu_ed25519", + "172.29.112.43": "/private/ssh_keys/root_dedicated-developjob-zhizhou-avgen-1-m8eyg_ed25519", +} +REMOTE_CODE = r""" +import json, os, signal, sys +items, sig, run_id = json.loads(sys.argv[1]), int(sys.argv[2]), sys.argv[3] +results = [] +for item in items: + pid, kind = item['pid'], item['kind'] + try: + args = open(f'/proc/{pid}/cmdline', 'rb').read().replace(b'\0', b' ').decode(errors='replace') + valid = ('filter_x_sim' in args and run_id in args) if kind == 'client' else 'filter_x_server' in args + if not valid: + results.append([pid, kind, 'skipped: PID no longer matches']) + continue + os.kill(pid, sig) + results.append([pid, kind, 'signalled']) + except (FileNotFoundError, ProcessLookupError): + results.append([pid, kind, 'already exited']) +print(json.dumps(results)) +""" + + +def signal_host(host: str, items: list[dict], sig: int, run_id: str) -> list: + if not items: + return [] + args = ["python3", "-c", REMOTE_CODE, json.dumps(items), str(sig), run_id] + if host != LOCAL_HOST: + remote = " ".join(shlex.quote(arg) for arg in args) + args = ["ssh", "-T", "-i", KEYS[host], "-o", "BatchMode=yes", f"root@{host}", remote] + result = subprocess.run(args, text=True, capture_output=True, timeout=30) + if result.returncode: + raise RuntimeError(f"signal failed on {host}: {result.stderr}") + return json.loads(result.stdout.splitlines()[-1]) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--run-id", required=True) + parser.add_argument("--session", required=True) + args = parser.parse_args() + if not re.fullmatch(r"[A-Za-z0-9_.-]+", args.run_id + args.session): + parser.error("run-id/session may contain only letters, digits, _ . -") + out = ROOT / "artifacts/evaluation" / args.run_id + if not (out / "manifest.json").is_file(): + parser.error(f"not an eval run: {out}") + by_host: dict[str, list[dict]] = {} + for status_file in (out / "jobs").glob("*/status.json"): + state = json.loads(status_file.read_text()) + # Completed/failed jobs retain old PID files. Never signal a recycled PID + # belonging to an unrelated process when stopping an active run. + if state.get("status") not in {"starting", "running"}: + continue + for kind, host in (("client", state["sim_host"]), ("server", state["policy_host"])): + pidfile = status_file.with_name(f"{kind}.pid") + if pidfile.is_file(): + pid = int(pidfile.read_text().strip()) + if pid > 1: + by_host.setdefault(host, []).append({"pid": pid, "kind": kind}) + subprocess.run(["tmux", "-L", "hc", "kill-session", "-t", args.session], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + results: dict[str, dict[str, list]] = {} + for sig, label in ((15, "term"), (9, "kill_remaining")): + results[label] = {} + for host, items in by_host.items(): + results[label][host] = signal_host(host, items, sig, args.run_id) + if sig == 15: + time.sleep(8) + report = {"run_id": args.run_id, "session": args.session, + "stopped_at": datetime.now(timezone.utc).isoformat(), "signals": results} + (out / "stop_report.json").write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps({"run_id": args.run_id, "owned_processes": sum(map(len, by_host.values())), + "stop_report": str(out / "stop_report.json")}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/maintenance/summarize_formal_offline_eval.py b/release-20261107/source/workspace_joint/mira/scripts/maintenance/summarize_formal_offline_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..477d90fab6d336d249629e98ef3bfcb56229d519 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/maintenance/summarize_formal_offline_eval.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Merge formal offline shards and reject missing/duplicated/mixed cases.""" +from __future__ import annotations + +import argparse +from collections import defaultdict +import json +from pathlib import Path + +import numpy as np + + +def load_cases(root: Path, step: int) -> list[dict]: + rows = [] + fingerprints = set() + for shard in range(4): + directory = root / f'action{step}_shard{shard}' + summary = json.loads((directory / 'summary.json').read_text()) + if summary['status'] != 'passed' or summary['action_step'] != step: + raise RuntimeError(f'failed or mixed shard: {directory}') + fingerprints.add(summary['runtime_provenance']['action_checkpoint_fingerprint']) + for line in (directory / 'metrics.jsonl').read_text().splitlines(): + row = json.loads(line) + if row.get('event') == 'case': + rows.append(row) + if len(fingerprints) != 1: + raise RuntimeError(f'mixed checkpoint fingerprints for step {step}: {fingerprints}') + keys = [ + (row['episode_sha256'], row['current_anchor'], row['stratum']) + for row in rows + ] + if len(rows) != 500 or len(set(keys)) != 500: + raise RuntimeError(f'step {step}: expected 500 unique cases, got {len(rows)}/{len(set(keys))}') + return rows + + +def aggregate(rows: list[dict]) -> dict: + result = { + 'cases': len(rows), + 'tasks': len({row['task'] for row in rows}), + 'domains': sorted({row['domain'] for row in rows}), + } + for key in ('normalized_action_mse', 'execute8_normalized_mse', 'latency_s'): + values = np.asarray([row[key] for row in rows], dtype=np.float64) + result[key] = { + 'mean': float(values.mean()), 'p50': float(np.quantile(values, .5)), + 'p95': float(np.quantile(values, .95)), + 'p99': float(np.quantile(values, .99)), 'maximum': float(values.max()), + } + grouped = defaultdict(list) + for row in rows: + grouped[row['stratum']].append(row['execute8_normalized_mse']) + result['execute8_mse_by_stratum'] = { + key: float(np.mean(value)) for key, value in sorted(grouped.items()) + } + grouped_domain = defaultdict(list) + grouped_task = defaultdict(list) + for row in rows: + grouped_domain[row['domain']].append(row['execute8_normalized_mse']) + grouped_task[row['task']].append(row['execute8_normalized_mse']) + result['execute8_mse_by_domain'] = { + key: float(np.mean(value)) for key, value in sorted(grouped_domain.items()) + } + result['execute8_mse_by_task'] = { + key: float(np.mean(value)) for key, value in sorted(grouped_task.items()) + } + worst = sorted(rows, key=lambda row: row['execute8_normalized_mse'], reverse=True)[:10] + result['worst_execute8_cases'] = [ + { + key: row[key] + for key in ( + 'task', 'domain', 'stratum', 'episode_sha256', 'current_anchor', + 'valid_action_steps', 'execute8_normalized_mse', 'normalized_action_mse', + ) + } + for row in worst + ] + result['execute8_cases_above_1'] = sum( + row['execute8_normalized_mse'] > 1.0 for row in rows + ) + return result + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument('root', type=Path) + args = parser.parse_args() + candidates = {step: load_cases(args.root, step) for step in (11508, 23016)} + key = lambda row: (row['episode_sha256'], row['current_anchor'], row['stratum']) + left = {key(row) for row in candidates[11508]} + right = {key(row) for row in candidates[23016]} + if left != right: + raise RuntimeError('candidate checkpoints were not evaluated on identical cases') + report = { + 'status': 'passed', + 'scope': 'offline_diagnostic_not_closed_loop_success_rate', + 'paired_case_grid': True, + 'action_noise_contract': 'checkpoint-fingerprint-bound deterministic deployment seed', + 'candidates': {str(step): aggregate(rows) for step, rows in candidates.items()}, + } + target = args.root / 'aggregate.json' + target.write_text(json.dumps(report, indent=2) + '\n') + print(json.dumps(report, indent=2)) + + +if __name__ == '__main__': + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/maintenance/summarize_prompt_validation.py b/release-20261107/source/workspace_joint/mira/scripts/maintenance/summarize_prompt_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..02adc6305e3b1ef1f85a5953375fcee09bbc79e1 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/maintenance/summarize_prompt_validation.py @@ -0,0 +1,106 @@ +"""Summarize seed-paired 25k prompt factorial and read-only stage diagnostics.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import json +from math import comb +from pathlib import Path + + +TASKS = ("handover_block", "pick_dual_bottles") +CONDITIONS = ("official_bare", "official_wrapped", "train_bare", "train_exact") + + +def rows(paths, *, task=None, instruction=None, key="env_seed"): + found = {} + for path in paths: + if not path.exists(): + continue + for line in path.open(): + try: + row = json.loads(line) + except json.JSONDecodeError: + continue + if task is not None and row.get("task") != task: + continue + if instruction is not None and row.get("instruction") != instruction: + continue + if key in row: + found[int(row[key])] = row + return found + + +def exact_p(a, b, seeds): + gains = sum(not a[s]["success"] and b[s]["success"] for s in seeds) + losses = sum(a[s]["success"] and not b[s]["success"] for s in seeds) + discordant = gains + losses + if discordant == 0: + return {"gains": 0, "losses": 0, "mcnemar_p_two_sided": 1.0} + tail = sum(comb(discordant, i) for i in range(min(gains, losses) + 1)) / (2**discordant) + return {"gains": gains, "losses": losses, "mcnemar_p_two_sided": min(1.0, 2 * tail)} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[3]) + args = parser.parse_args() + root = args.root + base = root / "artifacts/evaluation/joint25000_full100_optix_20261018" + pilot = root / "artifacts/evaluation/joint25000_prompt_ablation_20261020" + factorial = root / "artifacts/evaluation/joint25000_factorial_20261021" + report = {"checkpoint_step": 25000, "tasks": {}} + for task in TASKS: + official_paths = list(base.glob(f"shard-*/cases/demo_clean_{task}/diagnostics/episodes.jsonl")) + official = rows(official_paths, task=task) + train_prompt = (pilot / "prompts" / f"{task}_train_exact.txt").read_text().strip() + pilot_paths = list((pilot / "diagnostics").glob("server*/episodes.jsonl")) + exact_pilot = rows(pilot_paths, task=task, instruction=train_prompt) + data = {"official_bare": official, "train_exact": exact_pilot} + stages = {} + for condition in ("official_wrapped", "train_bare", "train_exact"): + path = factorial / f"{task}_{condition}" / "diagnostics/stages.jsonl" + entries = rows([path], task=task, key="seed") + if condition == "train_exact": + data[condition + "_100"] = entries + else: + data[condition] = entries + stages[condition] = entries + + first20 = set(list(official)[:20]) + paired = sorted(first20.intersection(*(set(data[c]) for c in CONDITIONS))) + task_report = { + "counts_available": {key: {"n": len(value), "success": sum(bool(x.get("success")) for x in value.values())} for key, value in data.items()}, + "factorial_matched_n": len(paired), + "factorial": {condition: sum(bool(data[condition][seed]["success"]) for seed in paired) for condition in CONDITIONS}, + "paired_comparisons": {}, + "stage_counts": {}, + } + if paired: + for a, b in (("official_bare", "official_wrapped"), ("official_bare", "train_bare"), ("official_bare", "train_exact"), ("train_bare", "train_exact"), ("official_wrapped", "train_exact")): + task_report["paired_comparisons"][f"{a}_vs_{b}"] = exact_p(data[a], data[b], paired) + for condition, entries in stages.items(): + if not entries: + continue + keys = ("ever_lifted_6cm", "ever_crossed_center", "final_target_xy_ok", "final_target_z_ok", "right_gripper_open") if task == "handover_block" else ( + "ever_left_lifted_6cm", "ever_right_lifted_6cm", "final_left_target_xy_ok", "final_right_target_xy_ok", "final_left_z_ok", "final_right_z_ok") + counts = Counter() + for row in entries.values(): + if row.get("actions", 0) == 0: + continue + for key in keys: + value = row.get(key, row.get("final", {}).get(key)) + counts[key] += bool(value) + task_report["stage_counts"][condition] = {"n": sum(row.get("actions", 0) > 0 for row in entries.values()), **counts} + if "train_exact_100" in data: + matched100 = sorted(set(official) & set(data["train_exact_100"])) + task_report["exact_prompt_100_paired_n"] = len(matched100) + if matched100: + task_report["exact_prompt_100_vs_official"] = exact_p(official, data["train_exact_100"], matched100) + report["tasks"][task] = task_report + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/merge_robotwin_latent_cache_shards.py b/release-20261107/source/workspace_joint/mira/scripts/merge_robotwin_latent_cache_shards.py new file mode 100644 index 0000000000000000000000000000000000000000..507402c6854ba13697d8ee8b470c1c71afe84784 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/merge_robotwin_latent_cache_shards.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +"""Strictly merge successful RoboTwin latent-cache shards in source-manifest order.""" + +from __future__ import annotations + +import argparse +import ctypes +import json +from pathlib import Path + +from mira.data.robotwin_wam_schema import read_jsonl, write_jsonl_atomic + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifests", nargs="+", required=True) + parser.add_argument("--output-root", required=True) + parser.add_argument("--codec-sha256", required=True) + parser.add_argument("--num-shards", type=int, required=True) + args = parser.parse_args() + ctypes.CDLL(None).prctl(15, b"syncnet_core_g", 0, 0, 0) + + if args.num_shards < 1: + raise ValueError("num-shards must be positive") + output = Path(args.output_root).expanduser().resolve() / args.codec_sha256 + shard_root = output / "_shards" + shard_stats = [] + for rank in range(args.num_shards): + path = shard_root / f"stats.rank-{rank:05d}-of-{args.num_shards:05d}.json" + if not path.is_file(): + raise FileNotFoundError(f"Incomplete cache build; missing shard stats: {path}") + value = json.loads(path.read_text(encoding="utf-8")) + if value.get("codec_sha256") != args.codec_sha256: + raise ValueError(f"Codec hash mismatch in {path}") + shard_stats.append(value) + + total_rows = 0 + total_latents = 0 + for manifest_arg in args.manifests: + manifest = Path(manifest_arg).expanduser().resolve() + source = read_jsonl(manifest) + enriched_by_digest: dict[str, dict] = {} + for rank in range(args.num_shards): + path = ( + shard_root + / f"manifest_{manifest.stem}.rank-{rank:05d}-of-{args.num_shards:05d}.jsonl" + ) + if not path.is_file(): + raise FileNotFoundError(f"Incomplete cache build; missing manifest shard: {path}") + for row in read_jsonl(path): + digest = str(row["episode_sha256"]) + if digest in enriched_by_digest: + raise RuntimeError(f"Episode appears in multiple cache shards: {digest}") + enriched_by_digest[digest] = row + expected = [str(row["episode_sha256"]) for row in source] + missing = [digest for digest in expected if digest not in enriched_by_digest] + unexpected = sorted(set(enriched_by_digest) - set(expected)) + if missing or unexpected: + raise RuntimeError( + f"Cache shards do not exactly cover {manifest}: " + f"missing={missing[:5]}, unexpected={unexpected[:5]}" + ) + merged = [enriched_by_digest[digest] for digest in expected] + destination = output / f"manifest_{manifest.stem}.jsonl" + write_jsonl_atomic(destination, merged) + total_rows += len(merged) + total_latents += sum(int(row["n_latents"]) for row in merged) + print(f"wrote {destination} ({len(merged)} episodes, strict {args.num_shards}-shard merge)") + + first = shard_stats[0] + aggregate = { + "format_version": 1, + "codec_checkpoint": first["codec_checkpoint"], + "codec_sha256": args.codec_sha256, + "codec_latent_mean_std": first["codec_latent_mean_std"], + "text_cache_index": first["text_cache_index"], + "text_cache_debug_only": first["text_cache_debug_only"], + "complete_cache": True, + "episodes": total_rows, + "latent_cells": total_latents, + "max_overlap_error": max(float(value["max_overlap_error"]) for value in shard_stats), + "merged_shards": args.num_shards, + } + temporary = output / ".stats.json.tmp" + temporary.write_text(json.dumps(aggregate, indent=2) + "\n", encoding="utf-8") + temporary.replace(output / "stats.json") + print(json.dumps(aggregate, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/monitor_bihub_wam_pipeline.py b/release-20261107/source/workspace_joint/mira/scripts/monitor_bihub_wam_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..7dfc81ad7f0cb8b75358fd506206b283656f65c7 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/monitor_bihub_wam_pipeline.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python3 +"""Write lightweight progress records for the long-running three-view world-model pipeline.""" + +from __future__ import annotations + +import argparse +import ctypes +import json +import os +import time +from datetime import UTC, datetime +from pathlib import Path + + +def _set_process_name() -> None: + ctypes.CDLL(None).prctl(15, b"syncnet_core_w", 0, 0, 0) + try: + import setproctitle + + setproctitle.setproctitle("syncnet_core_watch") + except ImportError: + pass + + +def _processes() -> list[dict[str, object]]: + rows: list[dict[str, object]] = [] + for entry in os.scandir("/proc"): + if not entry.name.isdigit(): + continue + try: + status: dict[str, str] = {} + with open(f"/proc/{entry.name}/status", encoding="utf-8") as handle: + for line in handle: + if ":" in line: + key, value = line.split(":", 1) + status[key] = value.strip() + name = status.get("Name", "") + if not name.startswith("syncnet_core_"): + continue + rows.append( + { + "pid": int(entry.name), + "ppid": int(status.get("PPid", "0")), + "name": name, + "state": status.get("State", ""), + } + ) + except (FileNotFoundError, PermissionError, ProcessLookupError): + continue + return rows + + +def _current_zip(pid: int, dataset_root: Path) -> str | None: + try: + descriptors = os.scandir(f"/proc/{pid}/fd") + except FileNotFoundError: + return None + with descriptors: + for descriptor in descriptors: + try: + target = Path(os.readlink(descriptor.path)) + except OSError: + continue + if target.suffix == ".zip": + try: + return str(target.relative_to(dataset_root)) + except ValueError: + return str(target) + return None + + +def _manifest_archives(path: Path) -> list[str]: + archives: set[str] = set() + with path.open(encoding="utf-8") as handle: + for line in handle: + row = json.loads(line) + if row.get("robot") == "aloha-agilex": + archives.add(str(row["archive"])) + return sorted(archives) + + +def _last_jsonl(path: Path) -> dict[str, object] | None: + if not path.is_file() or path.stat().st_size == 0: + return None + last = "" + with path.open(encoding="utf-8") as handle: + for line in handle: + if line.strip(): + last = line + return json.loads(last) if last else None + + +def _snapshot(workspace: Path, train_archives: list[str], previous_index: int) -> tuple[dict, int]: + processes = _processes() + names = [str(row["name"]) for row in processes] + result: dict[str, object] = { + "time_utc": datetime.now(UTC).isoformat(), + "processes": processes, + } + manifest = next((row for row in processes if row["name"] == "syncnet_core_m"), None) + if manifest is not None: + current = _current_zip(int(manifest["pid"]), workspace / "datasets" / "RoboTwin2.0") + index = train_archives.index(current) + 1 if current in train_archives else None + phase = "val" if index is not None and previous_index >= len(train_archives) and index < previous_index else "train" + result.update(stage="formal_manifest", split=phase, archive=current, archive_index=index, archive_total=len(train_archives)) + return result, max(previous_index, index or 0) + + if "syncnet_core_x" in names: + result["stage"] = "instruction_cache" + elif any(name.startswith("syncnet_core_c") for name in names): + result["stage"] = "latent_cache" + result["cached_episode_files"] = sum(1 for _ in (workspace / "artifacts" / "latent_cache").rglob("*.safetensors")) + result["target_episode_files"] = 27500 + elif "syncnet_core_g" in names: + result["stage"] = "merge_latent_cache" + elif "syncnet_core_a" in names: + result["stage"] = "cache_preflight_audit" + elif any(name.startswith("syncnet_core_r") for name in names): + result["stage"] = "world_model_training" + result["last_metrics"] = _last_jsonl(workspace / "outputs" / "robotwin_3view_world_1b" / "metrics.jsonl") + elif "syncnet_core_p" in names or "syncnet_core_l" in names: + result["stage"] = "transition" + else: + result["stage"] = "pipeline_not_running" + return result, previous_index + + +def main() -> None: + _set_process_name() + parser = argparse.ArgumentParser() + parser.add_argument("--workspace", type=Path, default=Path(__file__).resolve().parents[2]) + parser.add_argument("--interval", type=float, default=30.0) + parser.add_argument("--output") + args = parser.parse_args() + workspace = args.workspace.expanduser().resolve() + output = Path(args.output).expanduser().resolve() if args.output else workspace / "outputs" / "world_model_logs" / "formal-progress.jsonl" + output.parent.mkdir(parents=True, exist_ok=True) + train_archives = _manifest_archives( + workspace / "datasets" / "RoboTwin2.0" / "mira_manifests" / "codec_40f_30to20" / "train.jsonl" + ) + previous_index = 0 + missing_snapshots = 0 + while True: + record, previous_index = _snapshot(workspace, train_archives, previous_index) + with output.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(record, ensure_ascii=False) + "\n") + print(json.dumps(record, ensure_ascii=False), flush=True) + missing_snapshots = missing_snapshots + 1 if record["stage"] == "pipeline_not_running" else 0 + # Pipeline stages replace one another and can briefly leave no named child. + # Require a sustained absence before stopping the monitor. + if missing_snapshots >= 3: + break + time.sleep(max(5.0, args.interval)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/precompute_instruction_embeddings.py b/release-20261107/source/workspace_joint/mira/scripts/precompute_instruction_embeddings.py new file mode 100644 index 0000000000000000000000000000000000000000..4c17bb203702d878867a4cccb2b7f865ad7e1cf2 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/precompute_instruction_embeddings.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Precompute frozen Wan UMT5-XXL instruction tokens for Stage W.""" + +from __future__ import annotations + +import argparse +import ctypes +import json +import os +import uuid +from pathlib import Path + +import torch +from safetensors.torch import save_file +from transformers import AutoTokenizer + +from mira.data.robotwin_wam_schema import read_jsonl, sha256_file, sha256_text +from mira.text import load_wan_umt5 + +MODEL_REPOSITORY = "Wan-AI/Wan2.2-TI2V-5B" +MODEL_REVISION = "921dbaf3f1674a56f47e83fb80a34bac8a8f203e" + + +def _set_process_name() -> None: + ctypes.CDLL(None).prctl(15, b"syncnet_core_x", 0, 0, 0) + + +def _atomic_save(tensors: dict[str, torch.Tensor], metadata: dict[str, str], path: Path) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.tmp.{uuid.uuid4().hex}") + save_file(tensors, temporary, metadata=metadata) + os.replace(temporary, path) + + +def _debug_embedding(instruction_sha: str, length: int) -> torch.Tensor: + """Stable fake text tokens used only to exercise a smoke-test code path.""" + seed = int(instruction_sha[:16], 16) + generator = torch.Generator().manual_seed(seed) + return torch.randn(length, 4096, generator=generator, dtype=torch.float32).to(torch.bfloat16) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifests", nargs="+", required=True) + parser.add_argument("--output-root", required=True) + parser.add_argument("--model-root", required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--max-length", type=int, default=128) + parser.add_argument("--overwrite", action="store_true") + parser.add_argument("--debug-deterministic", action="store_true") + args = parser.parse_args() + _set_process_name() + + instructions: dict[str, str] = {} + for manifest in args.manifests: + for row in read_jsonl(manifest): + instruction = str(row["instruction"]) + digest = sha256_text(instruction) + if row.get("instruction_sha256") != digest: + raise ValueError(f"Instruction hash mismatch in {manifest}: {row.get('episode_sha256')}") + instructions[digest] = instruction + + model_root = Path(args.model_root).expanduser().resolve() + checkpoint = model_root / "models_t5_umt5-xxl-enc-bf16.pth" + tokenizer_root = model_root / "google" / "umt5-xxl" + model_hash = "debug-deterministic-no-model" + tokenizer_hashes: dict[str, str] = {} + tokenizer = None + encoder = None + if not args.debug_deterministic: + model_hash = sha256_file(checkpoint) + tokenizer_hashes = { + path.name: sha256_file(path) for path in sorted(tokenizer_root.iterdir()) if path.is_file() + } + tokenizer = AutoTokenizer.from_pretrained(tokenizer_root, local_files_only=True) + encoder = load_wan_umt5(checkpoint, device=args.device) + + namespace = sha256_text(f"{MODEL_REPOSITORY}@{MODEL_REVISION}:{model_hash}:len={args.max_length}") + output = Path(args.output_root).expanduser().resolve() / namespace + output.mkdir(parents=True, exist_ok=True) + index: dict[str, dict[str, object]] = {} + + for digest, instruction in sorted(instructions.items()): + path = output / f"{digest}.safetensors" + if path.exists() and not args.overwrite: + index[digest] = {"path": str(path), "instruction": instruction} + continue + if args.debug_deterministic: + # A nontrivial variable length also exercises text padding/masking in collation. + length = min(args.max_length, max(4, len(instruction.split()) + 2)) + hidden = _debug_embedding(digest, length) + mask = torch.ones(length, dtype=torch.bool) + else: + assert tokenizer is not None and encoder is not None + tokens = tokenizer( + [instruction], + return_tensors="pt", + padding="max_length", + truncation=True, + max_length=args.max_length, + add_special_tokens=True, + ) + ids = tokens.input_ids.to(args.device) + full_mask = tokens.attention_mask.to(device=args.device, dtype=torch.bool) + with torch.inference_mode(), torch.autocast(device_type="cuda", dtype=torch.bfloat16): + encoded = encoder(ids, full_mask)[0] + length = int(full_mask[0].sum()) + hidden = encoded[:length].to(device="cpu", dtype=torch.bfloat16).contiguous() + mask = torch.ones(length, dtype=torch.bool) + _atomic_save( + {"text_hidden_bf16": hidden, "text_mask_bool": mask}, + { + "instruction": instruction, + "instruction_sha256": digest, + "model_repository": MODEL_REPOSITORY, + "model_revision": MODEL_REVISION, + "model_sha256": model_hash, + "max_length": str(args.max_length), + "debug_only": str(args.debug_deterministic).lower(), + }, + path, + ) + index[digest] = {"path": str(path), "instruction": instruction, "tokens": length} + + payload = { + "format_version": 1, + "namespace": namespace, + "model_repository": MODEL_REPOSITORY, + "model_revision": MODEL_REVISION, + "model_sha256": model_hash, + "tokenizer_sha256": tokenizer_hashes, + "max_length": args.max_length, + "hidden_dim": 4096, + "debug_only": args.debug_deterministic, + "entries": index, + } + temporary = output / ".index.json.tmp" + temporary.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + temporary.replace(output / "index.json") + print(json.dumps({key: value for key, value in payload.items() if key != "entries"}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/precompute_robotwin_latents.py b/release-20261107/source/workspace_joint/mira/scripts/precompute_robotwin_latents.py new file mode 100644 index 0000000000000000000000000000000000000000..bbcb486ded781145fbcb41597392b1c640509fd2 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/precompute_robotwin_latents.py @@ -0,0 +1,449 @@ +#!/usr/bin/env python3 +"""Precompute three independent LingBot codec streams for audited RoboTwin episodes.""" + +from __future__ import annotations + +import argparse +import ctypes +import io +import json +import os +import time +import uuid +import zipfile +from datetime import UTC, datetime +from pathlib import Path + +import h5py +import numpy as np +import torch +from safetensors.torch import save_file +from torchvision.io import ImageReadMode, decode_jpeg + +from mira.codec.codec_model import VideoCodec +from mira.data.batch import VideoActionBatch +from mira.data.robotwin_wam_schema import ( + CAMERA_PATHS, + RAW_VECTOR_PATH, + derive_target_state_and_action, + half_up_source_indices, + read_jsonl, + sha256_file, + write_jsonl_atomic, +) +from mira.world_model.actions_config import ActionConfig, ActionTensors + + +def _set_process_name(shard_index: int) -> None: + try: + import setproctitle + + setproctitle.setproctitle(f"syncnet_core_cache_{shard_index}") + except ImportError: + pass + ctypes.CDLL(None).prctl(15, f"syncnet_core_c{shard_index}".encode()[:15], 0, 0, 0) + + +def _atomic_save(tensors: dict[str, torch.Tensor], metadata: dict[str, str], path: Path) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.tmp.{uuid.uuid4().hex}") + try: + save_file(tensors, temporary, metadata=metadata) + os.replace(temporary, path) + finally: + temporary.unlink(missing_ok=True) + + +def _append_jsonl_atomic(path: Path, record: dict[str, object]) -> None: + """Append one compact progress record without interleaving concurrent ranks.""" + path.parent.mkdir(parents=True, exist_ok=True) + payload = (json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n").encode() + descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o644) + try: + os.write(descriptor, payload) + finally: + os.close(descriptor) + + +def _report_progress( + *, + args: argparse.Namespace, + phase: str, + manifest: str | None, + completed: int, + total: int, + reused: int, + encoded: int, + started_at: float, +) -> None: + elapsed = max(time.monotonic() - started_at, 1.0e-6) + rate = encoded / elapsed + remaining = max(total - completed, 0) + eta_seconds = remaining / rate if rate > 0 else None + record: dict[str, object] = { + "time_utc": datetime.now(UTC).isoformat(), + "stage": "latent_cache", + "phase": phase, + "rank": args.shard_index, + "num_shards": args.num_shards, + "device": args.device, + "manifest": manifest, + "completed": completed, + "total": total, + "reused_at_start": reused, + "encoded_this_run": encoded, + "episodes_per_min": round(rate * 60.0, 3), + "eta_seconds": round(eta_seconds, 1) if eta_seconds is not None else None, + } + line = json.dumps(record, ensure_ascii=False) + print(line, flush=True) + if args.progress_jsonl: + _append_jsonl_atomic(Path(args.progress_jsonl).expanduser().resolve(), record) + + +def _decode(dataset: h5py.Dataset, indices: list[int]) -> torch.Tensor: + encoded = [torch.frombuffer(bytearray(bytes(dataset[index])), dtype=torch.uint8) for index in indices] + images = decode_jpeg(encoded, mode=ImageReadMode.RGB) + if not isinstance(images, list): + raise TypeError("torchvision.decode_jpeg batched API returned a non-list") + return torch.stack(images) + + +def _empty_batch(video: torch.Tensor) -> VideoActionBatch: + config = ActionConfig(valid_keys=[], source_fps=20, target_fps=20) + actions = ActionTensors(config, batch_size=video.shape[0]) + actions.key_presses = torch.zeros(video.shape[0], video.shape[1], 0, dtype=torch.int32) + actions.mouse_movements = torch.zeros(video.shape[0], video.shape[1], 2) + return VideoActionBatch(video=video, actions=actions) + + +def _block_starts(n_frames20: int, block: int = 40) -> list[int]: + if n_frames20 < block: + raise ValueError(f"Codec cache requires at least {block} target frames, got {n_frames20}") + starts = list(range(0, n_frames20 - block + 1, block)) + final = n_frames20 - block + if final % 2: + final -= 1 + if final not in starts: + starts.append(final) + return sorted(starts) + + +@torch.inference_mode() +def _encode_episode_sequential_views( + codec: VideoCodec, + episode: h5py.File, + source_indices: torch.Tensor, + *, + device: str, +) -> tuple[torch.Tensor, float]: + n_frames20 = int(source_indices.numel()) + n_latents = n_frames20 // 2 + all_views: list[torch.Tensor] = [] + max_overlap_error = 0.0 + for camera_path in CAMERA_PATHS: + dataset = episode[camera_path] + if not isinstance(dataset, h5py.Dataset): + raise ValueError(f"{camera_path} is not a dataset") + chunks: dict[int, torch.Tensor] = {} + for start in _block_starts(n_frames20): + selected = source_indices[start : start + 40].tolist() + video = _decode(dataset, selected)[None].to(device, non_blocking=True) + batch = _empty_batch(video) + codec.preprocess_batch(batch) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + _, output = codec.encode(batch.video, trim_video=False) + latent = output.z[0].to(device="cpu", dtype=torch.bfloat16) + if latent.shape != (20, 32, 9, 12): + raise ValueError(f"Unexpected codec latent shape {tuple(latent.shape)}") + latent_start = start // 2 + for offset in range(latent.shape[0]): + index = latent_start + offset + if index in chunks: + error = float((chunks[index].float() - latent[offset].float()).abs().max()) + max_overlap_error = max(max_overlap_error, error) + if error > 5.0e-3: + raise ValueError(f"Codec overlap mismatch at latent {index}: max error {error}") + else: + chunks[index] = latent[offset].clone() + missing = sorted(set(range(n_latents)) - set(chunks)) + if missing: + raise RuntimeError(f"Missing cached latent cells: {missing[:8]}") + all_views.append(torch.stack([chunks[index] for index in range(n_latents)])) + return torch.stack(all_views), max_overlap_error + + +@torch.inference_mode() +def _encode_episode_batched_views( + codec: VideoCodec, + episode: h5py.File, + source_indices: torch.Tensor, + *, + device: str, +) -> tuple[torch.Tensor, float]: + """Encode the three independent camera streams in one backbone forward per time block.""" + n_frames20 = int(source_indices.numel()) + n_latents = n_frames20 // 2 + chunks: list[dict[int, torch.Tensor]] = [{} for _ in CAMERA_PATHS] + max_overlap_error = 0.0 + for start in _block_starts(n_frames20): + selected = source_indices[start : start + 40].tolist() + videos: list[torch.Tensor] = [] + for camera_path in CAMERA_PATHS: + dataset = episode[camera_path] + if not isinstance(dataset, h5py.Dataset): + raise ValueError(f"{camera_path} is not a dataset") + videos.append(_decode(dataset, selected)) + video = torch.stack(videos).to(device, non_blocking=True) + batch = _empty_batch(video) + codec.preprocess_batch(batch) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + _, output = codec.encode(batch.video, trim_video=False) + latent = output.z.to(device="cpu", dtype=torch.bfloat16) + expected = (len(CAMERA_PATHS), 20, 32, 9, 12) + if latent.shape != expected: + raise ValueError(f"Unexpected batched codec latent shape {tuple(latent.shape)}") + latent_start = start // 2 + for view_index, view_latent in enumerate(latent): + view_chunks = chunks[view_index] + for offset in range(view_latent.shape[0]): + index = latent_start + offset + if index in view_chunks: + error = float((view_chunks[index].float() - view_latent[offset].float()).abs().max()) + max_overlap_error = max(max_overlap_error, error) + if error > 5.0e-3: + raise ValueError( + f"Codec overlap mismatch for view {view_index} at latent {index}: " + f"max error {error}" + ) + else: + view_chunks[index] = view_latent[offset].clone() + all_views: list[torch.Tensor] = [] + for view_index, view_chunks in enumerate(chunks): + missing = sorted(set(range(n_latents)) - set(view_chunks)) + if missing: + raise RuntimeError(f"Missing cached latent cells for view {view_index}: {missing[:8]}") + all_views.append(torch.stack([view_chunks[index] for index in range(n_latents)])) + return torch.stack(all_views), max_overlap_error + + +def _encode_episode( + codec: VideoCodec, + episode: h5py.File, + source_indices: torch.Tensor, + *, + device: str, + batch_views: bool, +) -> tuple[torch.Tensor, float]: + implementation = _encode_episode_batched_views if batch_views else _encode_episode_sequential_views + return implementation(codec, episode, source_indices, device=device) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--dataset-root", required=True) + parser.add_argument("--manifests", nargs="+", required=True) + parser.add_argument("--codec-checkpoint", required=True) + parser.add_argument("--text-cache-index", required=True) + parser.add_argument("--output-root", required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--max-episodes-per-manifest", type=int) + parser.add_argument("--overwrite", action="store_true") + parser.add_argument("--codec-sha256") + parser.add_argument("--shard-index", type=int, default=0) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--log-every", type=int, default=1) + parser.add_argument("--progress-jsonl") + parser.add_argument("--cpu-threads", type=int, default=8) + parser.add_argument("--batch-views", action="store_true") + args = parser.parse_args() + if args.num_shards < 1 or not 0 <= args.shard_index < args.num_shards: + raise ValueError(f"Invalid cache shard {args.shard_index}/{args.num_shards}") + if args.cpu_threads < 1: + raise ValueError("cpu-threads must be positive") + torch.set_num_threads(args.cpu_threads) + torch.set_num_interop_threads(1) + _set_process_name(args.shard_index) + + root = Path(args.dataset_root).expanduser().resolve() + checkpoint = Path(args.codec_checkpoint).expanduser().resolve() + codec_hash = args.codec_sha256 or sha256_file(checkpoint) + output = Path(args.output_root).expanduser().resolve() / codec_hash + output.mkdir(parents=True, exist_ok=True) + + text_index_path = Path(args.text_cache_index).expanduser().resolve() + text_index = json.loads(text_index_path.read_text(encoding="utf-8")) + text_entries = text_index["entries"] + + work: list[tuple[Path, list[dict]]] = [] + for manifest_arg in args.manifests: + manifest = Path(manifest_arg).expanduser().resolve() + rows = read_jsonl(manifest) + if args.max_episodes_per_manifest is not None: + rows = rows[: args.max_episodes_per_manifest] + work.append((manifest, rows[args.shard_index :: args.num_shards])) + + def cache_path_for(row: dict) -> Path: + digest = str(row["episode_sha256"]) + return output / "episodes" / digest[:2] / digest[2:4] / f"{digest}.safetensors" + + total = sum(len(rows) for _, rows in work) + reused = sum(cache_path_for(row).is_file() for _, rows in work for row in rows) + encoded = 0 + started_at = time.monotonic() + _report_progress( + args=args, + phase="loading_codec", + manifest=None, + completed=reused, + total=total, + reused=reused, + encoded=encoded, + started_at=started_at, + ) + + codec = VideoCodec.load_from_checkpoint(checkpoint, device="cpu") + codec.eval().requires_grad_(False) + # Only the encoder is used for cache generation; keeping the 28-layer decoder on CPU avoids + # stealing memory from the codec training job that may be sharing the GPUs. + codec.encoder.to(args.device) + + aggregate = {"episodes": 0, "latent_cells": 0, "max_overlap_error": 0.0} + _report_progress( + args=args, + phase="encoding", + manifest=None, + completed=reused, + total=total, + reused=reused, + encoded=encoded, + started_at=started_at, + ) + for manifest, rows in work: + cached_rows: list[dict] = [] + handles: dict[str, zipfile.ZipFile] = {} + try: + for row in rows: + archive = str(row["archive"]) + digest = str(row["episode_sha256"]) + cache_path = cache_path_for(row) + if not cache_path.exists() or args.overwrite: + handle = handles.get(archive) + if handle is None: + handle = zipfile.ZipFile(root / archive) + handles[archive] = handle + payload = handle.read(str(row["member"])) + with h5py.File(io.BytesIO(payload), "r") as episode: + source = half_up_source_indices(int(row["n_source_frames"])) + if source.numel() % 2: + source = source[:-1] + raw_state = torch.from_numpy(np.asarray(episode[RAW_VECTOR_PATH], dtype=np.float32)) + state20, action20 = derive_target_state_and_action(raw_state, source) + latents, overlap_error = _encode_episode( + codec, + episode, + source, + device=args.device, + batch_views=args.batch_views, + ) + _atomic_save( + { + "world_latent_raw_bf16": latents.contiguous(), + "joint_target_state20_f32": state20.contiguous(), + "action20_f32": action20.contiguous(), + "source_index_i32": source.contiguous(), + }, + { + "format_version": "1", + "episode_sha256": digest, + "codec_sha256": codec_hash, + "codec_checkpoint": str(checkpoint), + "codec_weights": "EMA", + "view_order": "left,global,right", + "state_semantics": "simulator_drive_target_not_measured_qpos", + "source_fps": "30", + "video_fps": "20", + "latent_fps": "10", + "view_encode_batch_size": str(len(CAMERA_PATHS) if args.batch_views else 1), + }, + cache_path, + ) + aggregate["max_overlap_error"] = max(aggregate["max_overlap_error"], overlap_error) + encoded += 1 + text = text_entries.get(str(row["instruction_sha256"])) + if text is None: + raise KeyError(f"Missing text cache for {row['instruction_sha256']}") + enriched = dict(row) + enriched.update( + cache_path=str(cache_path), + text_cache_path=str(text["path"]), + codec_sha256=codec_hash, + text_cache_debug_only=bool(text_index.get("debug_only", False)), + cache_format_version=1, + ) + cached_rows.append(enriched) + aggregate["episodes"] += 1 + aggregate["latent_cells"] += int(row["n_latents"]) + if encoded > 0 and (encoded % max(args.log_every, 1) == 0 or reused + encoded == total): + _report_progress( + args=args, + phase="encoding", + manifest=manifest.name, + completed=reused + encoded, + total=total, + reused=reused, + encoded=encoded, + started_at=started_at, + ) + finally: + for handle in handles.values(): + handle.close() + if args.num_shards == 1: + destination = output / f"manifest_{manifest.stem}.jsonl" + else: + destination = ( + output + / "_shards" + / f"manifest_{manifest.stem}.rank-{args.shard_index:05d}-of-{args.num_shards:05d}.jsonl" + ) + write_jsonl_atomic(destination, cached_rows) + print(f"wrote {destination} ({len(cached_rows)} episodes)", flush=True) + + aggregate.update( + format_version=1, + codec_checkpoint=str(checkpoint), + codec_sha256=codec_hash, + codec_latent_mean_std=codec.info_from_checkpoint.get("latent_mean_std") if codec.info_from_checkpoint else None, + text_cache_index=str(text_index_path), + text_cache_debug_only=bool(text_index.get("debug_only", False)), + complete_cache=args.max_episodes_per_manifest is None, + shard_index=args.shard_index, + num_shards=args.num_shards, + reused_at_start=reused, + encoded_this_run=encoded, + cpu_threads=args.cpu_threads, + batch_views=args.batch_views, + ) + if args.num_shards == 1: + stats_path = output / "stats.json" + else: + stats_path = output / "_shards" / f"stats.rank-{args.shard_index:05d}-of-{args.num_shards:05d}.json" + stats_path.parent.mkdir(parents=True, exist_ok=True) + temporary = stats_path.with_name(f".{stats_path.name}.tmp") + temporary.write_text(json.dumps(aggregate, indent=2) + "\n", encoding="utf-8") + temporary.replace(stats_path) + print(json.dumps(aggregate, indent=2), flush=True) + _report_progress( + args=args, + phase="complete", + manifest=None, + completed=total, + total=total, + reused=reused, + encoded=encoded, + started_at=started_at, + ) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/recycle_world_v12_after_delay.sh b/release-20261107/source/workspace_joint/mira/scripts/recycle_world_v12_after_delay.sh new file mode 100644 index 0000000000000000000000000000000000000000..5bc2b550997e2c5b95837b544f1495f3a3639453 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/recycle_world_v12_after_delay.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +set -euo pipefail + +DELAY_SECONDS="${1:-7200}" +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" + +date '+recycle_wait_started=%F %T %Z' +sleep "$DELAY_SECONDS" +date '+recycle_woke=%F %T %Z' + +mapfile -t gpu_pids < <( + nvidia-smi --query-compute-apps=pid --format=csv,noheader,nounits \ + | awk 'NF {print $1}' | sort -nu +) +if ((${#gpu_pids[@]})); then + printf 'sending_sigterm_to_gpu_pids=%s\n' "${gpu_pids[*]}" + kill -TERM "${gpu_pids[@]}" +else + echo 'no_gpu_compute_processes_found' +fi + +# A SIGTERM-aware job may need time to write its own recovery checkpoint. +deadline=$((SECONDS + 600)) +while :; do + mapfile -t remaining_pids < <( + nvidia-smi --query-compute-apps=pid --format=csv,noheader,nounits \ + | awk 'NF {print $1}' | sort -nu + ) + if ((${#remaining_pids[@]} == 0)); then + break + fi + if ((SECONDS >= deadline)); then + printf 'gpu_processes_remained_after_sigterm=%s\n' "${remaining_pids[*]}" >&2 + exit 3 + fi + sleep 5 +done + +date '+gpu_released=%F %T %Z' +export MIRA_WV12_ALLOW_FORMAL=YES +export MIRA_WV12_PROCESS_PREFIX=inference_x_ +export MIRA_WV12_LAUNCHER_NAME=inference_x_launch +exec bash scripts/launch_world_v12_largebatch_remaining.sh formal \ + >> ../artifacts/world_v12_largebatch_remaining/logs/formal.log 2>&1 diff --git a/release-20261107/source/workspace_joint/mira/scripts/rollout_world_v9_sampling_steps.py b/release-20261107/source/workspace_joint/mira/scripts/rollout_world_v9_sampling_steps.py new file mode 100644 index 0000000000000000000000000000000000000000..a5719e8dc9cdb88b352ca1ea6fec5d0e7a76e66b --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/rollout_world_v9_sampling_steps.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +"""Re-run the frozen World-v9 fixed H1 cases with alternate flow step counts.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch +import torch.distributed as dist +from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( + CheckpointImpl, + checkpoint_wrapper, +) +from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard + +from mira.data.world_v6 import set_world_v6_process_name +from mira.training.distributed import set_up_distributed +from mira.training.world_v8.checkpoint import load_online_source +from mira.training.world_v8.config import load_config +from mira.training.world_v8.train import ( + _dataset, + _decode_fixed_h1_cases, + _fixed_cases, + _save_fixed_h1_case, +) +from mira.world_v6.model import WorldV6System + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", required=True) + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--checkpoint-step", required=True, type=int) + parser.add_argument("--output-root", required=True) + parser.add_argument("--sampling-steps", required=True, type=int, nargs="+") + args = parser.parse_args() + + if any(steps < 1 for steps in args.sampling_steps): + raise ValueError("All sampling step counts must be positive") + + settings = set_up_distributed() + rank, world_size = settings.rank, settings.world_size + if world_size != 8: + raise RuntimeError("The fixed six-case comparison requires eight ranks") + set_world_v6_process_name(f"tagshotx_wv9r{rank}") + device = torch.device("cuda", settings.device) + torch.manual_seed(2026 + rank) + torch.cuda.manual_seed(2026 + rank) + torch.backends.cuda.matmul.allow_tf32 = True + + config = load_config(args.config, []) + system = WorldV6System(config.model) + source = load_online_source( + system, args.checkpoint, expected_step=args.checkpoint_step + ) + system = system.to(device) + policy = MixedPrecisionPolicy( + param_dtype=torch.bfloat16, + reduce_dtype=torch.float32, + output_dtype=torch.bfloat16, + ) + if config.model.activation_checkpointing: + system.world_model.external_activation_checkpointing = True + for index, block in enumerate(system.world_model.blocks): + system.world_model.blocks[index] = checkpoint_wrapper( + block, + checkpoint_impl=CheckpointImpl.NO_REENTRANT, + preserve_rng_state=True, + ) + for block in system.world_model.blocks: + fully_shard(block, mp_policy=policy, reshard_after_forward=True) + fully_shard(system, mp_policy=policy, reshard_after_forward=True) + system.eval().requires_grad_(False) + + dataset = _dataset(config, "val") + cases = _fixed_cases(config) + output_root = Path(args.output_root).resolve() + decoder = None + summaries: dict[str, object] = { + "checkpoint": str(Path(args.checkpoint).resolve()), + "checkpoint_step": args.checkpoint_step, + "source": source, + "fixed_seed": config.validation.fixed_seed, + "cases": len(cases), + "results": {}, + } + + for sample_steps in args.sampling_steps: + run_config = config.model_copy(deep=True) + run_config.validation.sample_steps = sample_steps + run_output = output_root / f"sampling_steps_{sample_steps}" + metrics = _save_fixed_h1_case( + system, + dataset, + cases, + run_config, + output=run_output, + completed=args.checkpoint_step, + device=device, + rank=rank, + world_size=world_size, + ) + if rank == 0: + decoder = _decode_fixed_h1_cases( + decoder, + config=run_config, + output=run_output, + completed=args.checkpoint_step, + device=device, + ) + summaries["results"][str(sample_steps)] = { + "metrics": metrics, + "videos": str(run_output / "fixed_videos" / "online"), + "latents": str(run_output / "fixed_cases" / "online"), + } + dist.barrier() + + if rank == 0: + output_root.mkdir(parents=True, exist_ok=True) + summary_path = output_root / "summary.json" + summary_path.write_text(json.dumps(summaries, indent=2) + "\n", encoding="utf-8") + print(json.dumps(summaries, indent=2), flush=True) + + dist.barrier() + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/select_action_world_weights.py b/release-20261107/source/workspace_joint/mira/scripts/select_action_world_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..377ba72dc1647f285cce10f636217d0538367020 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/select_action_world_weights.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Paired online/EMA selection for the frozen Action-stage World artifact.""" + +from __future__ import annotations + +import argparse +import ctypes +import hashlib +import json +import os +from pathlib import Path + +import numpy as np +import torch +from torch.utils.data import DataLoader, Subset + +from mira.action.world_checkpoint import ( + apply_ema_to_model, + hash_tensor_state, + load_world_online_and_ema, + selected_state_encoder, +) +from mira.data.robotwin_wam_loader import RoboTwinWAMDataset, collate_robotwin_wam +from mira.data.robotwin_wam_schema import sha256_file + + +def _set_process_name() -> None: + ctypes.CDLL(None).prctl(15, b"syncnet_act_w", 0, 0, 0) + + +def _seed(window_id: str) -> int: + return int.from_bytes(hashlib.sha256(f"action-world-select:{window_id}:2026".encode()).digest()[:8], "big") + + +@torch.inference_mode() +def _evaluate(model, loader, device: torch.device, latent_std: float) -> np.ndarray: + rows = [] + model.eval() + for batch, metadata in loader: + batch = batch.to(device) + identifier = f"{metadata[0]['episode_sha256']}:{metadata[0]['latent_start']}" + generator = torch.Generator(device=device).manual_seed(_seed(identifier)) + noise = torch.randn( + batch.world_future_raw.shape, + device=device, + dtype=torch.bfloat16, + generator=generator, + ) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + prediction = model.sample_future(batch, steps=10, noise=noise) + squared = ((prediction.float() - batch.world_future_raw.float()) / latent_std).square() + rows.append( + [ + float(squared.mean()), + float(squared[:, 0].mean()), + float(squared[:, 1].mean()), + float(squared[:, 2].mean()), + ] + ) + return np.asarray(rows, dtype=np.float64) + + +def _bootstrap_ci(delta: np.ndarray, seed: int = 2026) -> tuple[float, float]: + rng = np.random.default_rng(seed) + means = np.empty(10_000, dtype=np.float64) + for index in range(len(means)): + means[index] = rng.choice(delta, size=len(delta), replace=True).mean() + return tuple(float(value) for value in np.quantile(means, [0.025, 0.975])) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--val-manifest", required=True) + parser.add_argument("--state-stats", required=True) + parser.add_argument("--output-dir", required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--cases", type=int, default=64) + parser.add_argument("--force-branch", choices=("auto", "online", "ema"), default="auto") + args = parser.parse_args() + _set_process_name() + if args.cases < 2: + raise ValueError("At least two paired cases are required") + output = Path(args.output_dir).expanduser().resolve() + output.mkdir(parents=True, exist_ok=True) + model, ema, checkpoint_metadata = load_world_online_and_ema(args.checkpoint) + config = model.config + online_hash = hash_tensor_state(model.state_dict()) + ema_hash = hash_tensor_state(ema.state) + online_state_encoder = selected_state_encoder(model, ema, "online") + ema_state_encoder = selected_state_encoder(model, ema, "ema") + + dataset = RoboTwinWAMDataset(args.val_manifest, args.state_stats, require_real_text=True) + count = min(args.cases, len(dataset)) + indices = np.linspace(0, len(dataset) - 1, count, dtype=np.int64).tolist() + loader = DataLoader( + Subset(dataset, indices), + batch_size=1, + shuffle=False, + num_workers=0, + collate_fn=collate_robotwin_wam, + ) + device = torch.device(args.device) + model = model.to(device=device, dtype=torch.bfloat16) + online = _evaluate(model, loader, device, config.latent_std) + apply_ema_to_model(model, ema) + ema_metrics = _evaluate(model, loader, device, config.latent_std) + delta = ema_metrics[:, 0] - online[:, 0] + ci = _bootstrap_ci(delta) + ema_view_ok = bool(np.all(ema_metrics[:, 1:].mean(axis=0) <= 1.02 * online[:, 1:].mean(axis=0))) + automatic = "ema" if ci[1] < 0 and ema_view_ok else "online" + selected = automatic if args.force_branch == "auto" else args.force_branch + config_payload = checkpoint_metadata["resolved_config"]["model"] + config_sha = hashlib.sha256( + json.dumps(config_payload, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest() + checkpoint = Path(args.checkpoint).expanduser().resolve() + selection = { + "format_version": 1, + "checkpoint": str(checkpoint), + "checkpoint_step": int(checkpoint_metadata["completed_steps"]), + "checkpoint_metadata_sha256": sha256_file(checkpoint / "distributed" / ".metadata"), + "trainer_state_sha256": sha256_file(checkpoint / "trainer_state.json"), + "world_config_sha256": config_sha, + "world_parameters": model.parameter_report()["total"], + "selected_branch": selected, + "selected_state_dict_sha256": online_hash if selected == "online" else ema_hash, + "online_state_dict_sha256": online_hash, + "ema_state_dict_sha256": ema_hash, + "selection": { + "cases": count, + "indices": indices, + "primary": "standardized_future_latent_mse", + "online_mean": online.mean(axis=0).tolist(), + "ema_mean": ema_metrics.mean(axis=0).tolist(), + "columns": ["all", "left", "global", "right"], + "ema_minus_online_mean": float(delta.mean()), + "bootstrap_95ci": list(ci), + "ema_view_within_2pct": ema_view_ok, + "automatic_decision": automatic, + "forced": args.force_branch != "auto", + }, + "latent_mean": config.latent_mean, + "latent_std": config.latent_std, + "view_order": ["left", "global", "right"], + "world_sampler": {"steps": 10, "schedule": "linear_quadratic", "solver": "euler"}, + } + state_encoder = online_state_encoder if selected == "online" else ema_state_encoder + state_path = output / "selected_state_encoder.pt" + state_tmp = state_path.with_suffix(".pt.tmp") + torch.save(state_encoder, state_tmp) + os.replace(state_tmp, state_path) + selection["selected_state_encoder"] = str(state_path) + selection["selected_state_encoder_sha256"] = sha256_file(state_path) + selection_path = output / "world_selection.json" + tmp = selection_path.with_suffix(".json.tmp") + tmp.write_text(json.dumps(selection, indent=2) + "\n", encoding="utf-8") + os.replace(tmp, selection_path) + print(json.dumps(selection, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/summarize_robotwin_eval.py b/release-20261107/source/workspace_joint/mira/scripts/summarize_robotwin_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..50863241c58509f1e74dd6bd230dd94d5c2d0de5 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/summarize_robotwin_eval.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Summarize one protocol/run; never drop failed or zero-replan episodes.""" +import argparse +from collections import defaultdict +import json +from pathlib import Path + + +def summarize(root: Path, expected_tasks: list[str] | None, episodes_per_task: int) -> dict: + tasks = defaultdict(lambda: {'success': 0, 'episodes': 0, 'zero_replans': 0}) + seen, models = set(), set() + for path in sorted(root.rglob('episodes.jsonl')): + for line in path.read_text().splitlines(): + if not line.strip(): + continue + row = json.loads(line) + key = (row['task'], row['env_seed'], row['instruction']) + if key in seen: + raise ValueError(f'Duplicate task/seed/instruction: {key}') + seen.add(key) + if not isinstance(row['success'], bool): + raise ValueError(f'Non-boolean success in {path}') + value = tasks[row['task']] + value['episodes'] += 1 + value['success'] += int(row['success']) + value['zero_replans'] += int(row.get('replans', len(row.get('plan_diagnostics', []))) == 0) + provenance = row.get('runtime_provenance', {}) + models.add((provenance.get('world_checkpoint_fingerprint'), provenance.get('action_checkpoint_fingerprint'), + provenance.get('world_steps'), provenance.get('action_steps'), provenance.get('execute_steps'))) + if not tasks: + raise ValueError('No episode records found') + if len(models) != 1: + raise ValueError('Mixed model/sampling provenance; summarize each run separately') + for value in tasks.values(): + value['success_rate'] = value['success'] / value['episodes'] + total = sum(value['episodes'] for value in tasks.values()) + successes = sum(value['success'] for value in tasks.values()) + complete = bool(expected_tasks) and set(tasks) == set(expected_tasks) and all( + value['episodes'] == episodes_per_task for value in tasks.values()) + return {'complete_protocol': complete, 'observed_tasks': len(tasks), 'episodes': total, + 'successes': successes, 'observed_micro_success': successes / total, + 'observed_task_macro_success': sum(value['success_rate'] for value in tasks.values()) / len(tasks), + 'zero_replans_included_in_denominator': sum(v['zero_replans'] for v in tasks.values()), + 'zero_replans_meaning': 'not automatically a policy failure or infrastructure error; inspect diagnostics', + 'missing_tasks': sorted(set(expected_tasks or []) - set(tasks)), 'per_task': dict(sorted(tasks.items())), + 'warning': 'Completeness counts do not verify seed list, seen/unseen instructions or simulator environment.'} + + +def main(): + p = argparse.ArgumentParser() + p.add_argument('root', type=Path) + p.add_argument('--expected-tasks', type=Path, help='JSON list of task names') + p.add_argument('--episodes-per-task', type=int, default=100) + p.add_argument('--output', type=Path) + args = p.parse_args() + expected = json.loads(args.expected_tasks.read_text()) if args.expected_tasks else None + report = summarize(args.root, expected, args.episodes_per_task) + text = json.dumps(report, indent=2) + '\n' + if args.output: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(text) + print(text) + + +if __name__ == '__main__': + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/syncnet_torchrun.py b/release-20261107/source/workspace_joint/mira/scripts/syncnet_torchrun.py new file mode 100644 index 0000000000000000000000000000000000000000..6af32f9e88da5b461defb1b896515ea60727483c --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/syncnet_torchrun.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +"""Run torch.distributed.run while keeping the elastic launcher visibly named syncnet.""" + +from __future__ import annotations + +import ctypes +import os + +import setproctitle +import torch.multiprocessing +from torch.distributed.run import main + +_PROCESS_TITLE = os.environ.get("MIRA_LAUNCHER_PROCESS_NAME", "syncnet_codec_launch") +_set_thread_name = torch.multiprocessing._set_thread_name + + +def _set_launcher_name() -> None: + setproctitle.setproctitle(_PROCESS_TITLE) + ctypes.CDLL(None).prctl(15, _PROCESS_TITLE.encode()[:15], 0, 0, 0) + + +def _keep_launcher_named(name: str) -> None: + """Prevent torchrun from replacing the launcher comm name with ``pt_elastic``.""" + _set_thread_name(_PROCESS_TITLE[:15] if name == "pt_elastic" else name) + + +if __name__ == "__main__": + _set_launcher_name() + torch.multiprocessing._set_thread_name = _keep_launcher_named + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/train_action_head.py b/release-20261107/source/workspace_joint/mira/scripts/train_action_head.py new file mode 100644 index 0000000000000000000000000000000000000000..dcf3addd4e3671b113854182860470afa9499231 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/train_action_head.py @@ -0,0 +1,801 @@ +#!/usr/bin/env python3 +"""Train the frozen-world Joint Bimanual Action Flow with FSDP2.""" + +from __future__ import annotations + +import ctypes +import hashlib +import json +import logging +import math +import random +import time +from pathlib import Path +from typing import Any + +import hydra +import numpy as np +import torch +import torch.distributed as dist +from omegaconf import DictConfig, OmegaConf +from torch import Tensor +from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( + CheckpointImpl, + checkpoint_wrapper, +) +from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard +from torch.utils.data import DataLoader + +from mira.action.checkpoint import ( + latest_action_checkpoint, + load_action_checkpoint, + save_action_checkpoint, +) +from mira.action.config import ActionHeadConfig +from mira.action.curriculum import choose_gt_future +from mira.action.data import ( + DeterministicActionSampler, + RoboTwinActionBatch, + RoboTwinActionDataset, + collate_robotwin_action, +) +from mira.action.flow_matching import ( + masked_action_flow_loss, + sample_action_euler, + sample_flow_batch, +) +from mira.action.joint_action_flow import JointBimanualActionFlow +from mira.action.visualization import save_action_trajectory_case +from mira.data.robotwin_wam_schema import sha256_file +from mira.training.distributed import set_up_distributed +from mira.training.ema import ModelEMA +from mira.training.swanlab_tracker import SwanLabTracker + +logger = logging.getLogger(__name__) + + +def _set_process_name(rank: int) -> None: + title = f"syncnet_act_worker_{rank}" + try: + import setproctitle + + setproctitle.setproctitle(title) + except ImportError: + pass + ctypes.CDLL(None).prctl(15, f"syncnet_act_r{rank}".encode()[:15], 0, 0, 0) + + +def _autocast(): + return torch.autocast(device_type="cuda", dtype=torch.bfloat16) + + +def _all_reduce_mean(value: Tensor) -> Tensor: + output = value.detach().float().clone() + if dist.is_initialized(): + dist.all_reduce(output, op=dist.ReduceOp.SUM) + output /= dist.get_world_size() + return output + + +def _all_reduce_sum(value: Tensor) -> Tensor: + output = value.detach().clone() + if dist.is_initialized(): + dist.all_reduce(output, op=dist.ReduceOp.SUM) + return output + + +def _write_jsonl(path: Path, value: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(value, default=float) + "\n") + + +def _validate_configuration(cfg: DictConfig, world_size: int) -> None: + if cfg.training.scope != "action_head_only": + raise ValueError("Action trainer only authorizes action_head_only") + if cfg.training.distributed.strategy != "fsdp2_full_shard": + raise ValueError("Action trainer requires FSDP2 full shard") + if world_size != int(cfg.training.distributed.expected_world_size): + raise ValueError( + f"Configured Action world size is {cfg.training.distributed.expected_world_size}, " + f"but launcher created {world_size} ranks" + ) + effective = ( + world_size + * int(cfg.training.per_device_batch) + * int(cfg.training.gradient_accumulation_steps) + ) + if effective != int(cfg.training.effective_global_batch): + raise ValueError( + f"Effective global batch is {effective}, expected {cfg.training.effective_global_batch}" + ) + if not bool(cfg.run.debug_smoke): + expected = (1024, 16, 16, 4096, 2) + actual = ( + int(cfg.model.hidden_dim), + int(cfg.model.layers), + int(cfg.model.heads), + int(cfg.model.ffn_dim), + int(cfg.model.noise_repeats), + ) + if actual != expected: + raise ValueError(f"Formal Action architecture must be {expected}, got {actual}") + + +def _future_contract_sha( + *, + manifest: str | Path, + cache_root: str | Path, + selection: dict[str, Any], + allow_incomplete: bool, +) -> str: + contract = { + "format_version": 1, + "action_manifest_sha256": sha256_file(manifest), + "world_state_dict_sha256": selection["selected_state_dict_sha256"], + "world_branch": selection["selected_branch"], + "world_steps": 10, + "world_schedule": "linear_quadratic", + "world_solver": "euler", + "seed_rule": ( + "sha256(world_sha,split,window_id,world_steps=10,base_seed=2026)" + ), + "view_order": ["left", "global", "right"], + "pooling": "adaptive_avg_pool2d_3x4", + "latent_space": "world_standardized", + "shape_per_row": [3, 10, 32, 3, 4], + "dtype": "float16", + } + root = Path(cache_root) + if (root / "COMPLETE").is_file(): + metadata = json.loads((root / "metadata.json").read_text(encoding="utf-8")) + for name, value in contract.items(): + if metadata.get(name) != value: + raise ValueError( + f"Future-cache contract mismatch for {name}: " + f"expected={value!r} actual={metadata.get(name)!r}" + ) + elif not allow_incomplete: + raise ValueError(f"Predicted-future cache is incomplete: {root}") + payload = json.dumps(contract, sort_keys=True, separators=(",", ":")).encode() + return hashlib.sha256(payload).hexdigest() + + +def _artifact_identity(cfg: DictConfig) -> dict[str, Any]: + selection_path = Path(cfg.upstream.world_selection).expanduser().resolve() + selection = json.loads(selection_path.read_text(encoding="utf-8")) + if int(selection["world_parameters"]) != int(cfg.upstream.expected_world_params): + raise ValueError("World selection points to the wrong model size") + if selection["view_order"] != list(cfg.upstream.expected_view_order): + raise ValueError("World selection view order mismatch") + state_encoder = Path(cfg.upstream.state_encoder).expanduser().resolve() + if sha256_file(state_encoder) != selection["selected_state_encoder_sha256"]: + raise ValueError("Selected state-encoder artifact does not match world_selection.json") + allow_incomplete = bool(cfg.data.get("allow_incomplete_future_cache", False)) + identity = { + "world_selection_sha256": sha256_file(selection_path), + "world_state_dict_sha256": selection["selected_state_dict_sha256"], + "world_branch": selection["selected_branch"], + "state_encoder_sha256": sha256_file(state_encoder), + "train_manifest_sha256": sha256_file(cfg.data.train_manifest), + "val_manifest_sha256": sha256_file(cfg.data.val_manifest), + "state_stats_sha256": sha256_file(cfg.data.state_stats), + "action_stats_sha256": sha256_file(cfg.data.action_stats), + "train_future_contract_sha256": _future_contract_sha( + manifest=cfg.data.train_manifest, + cache_root=cfg.data.train_future_cache, + selection=selection, + allow_incomplete=allow_incomplete, + ), + "val_future_contract_sha256": _future_contract_sha( + manifest=cfg.data.val_manifest, + cache_root=cfg.data.val_future_cache, + selection=selection, + allow_incomplete=allow_incomplete, + ), + } + action_stats = json.loads(Path(cfg.data.action_stats).read_text(encoding="utf-8")) + if action_stats.get("smoke_only") and not bool(cfg.run.debug_smoke): + raise ValueError("Formal Action training refuses smoke-only normalization statistics") + return identity + + +def _optimizer(model: torch.nn.Module, cfg: DictConfig) -> torch.optim.Optimizer: + groups: dict[tuple[str, bool], list[Tensor]] = { + ("main", True): [], + ("main", False): [], + ("state", True): [], + ("state", False): [], + } + no_decay_tokens = ("bias", "norm", "embedding", "modulation", "null_future") + for name, parameter in model.named_parameters(): + if not parameter.requires_grad: + continue + family = "state" if name.startswith("state_encoder.") else "main" + use_decay = parameter.ndim >= 2 and not any( + token in name.lower() for token in no_decay_tokens + ) + groups[(family, use_decay)].append(parameter) + param_groups = [] + for family in ("main", "state"): + lr = float(cfg.main_lr if family == "main" else cfg.state_copy_lr) + for use_decay in (True, False): + parameters = groups[(family, use_decay)] + if parameters: + param_groups.append( + { + "params": parameters, + "lr": lr, + "weight_decay": float(cfg.weight_decay) if use_decay else 0.0, + "group_name": f"{family}_{'decay' if use_decay else 'no_decay'}", + } + ) + return torch.optim.AdamW( + param_groups, + betas=tuple(cfg.betas), + eps=float(cfg.eps), + ) + + +def _scheduler(optimizer: torch.optim.Optimizer, cfg: DictConfig, total_steps: int): + warmup = int(cfg.warmup_steps) + floor = float(cfg.min_lr) / float(cfg.main_lr) + + def scale(step: int) -> float: + if step < warmup: + return max(floor, (step + 1) / max(1, warmup)) + progress = min(max((step - warmup) / max(1, total_steps - warmup), 0.0), 1.0) + return floor + (1.0 - floor) * 0.5 * (1.0 + math.cos(math.pi * progress)) + + return torch.optim.lr_scheduler.LambdaLR(optimizer, scale) + + +def _conditions( + batch: RoboTwinActionBatch, + future: Tensor, + future_drop_mask: Tensor, +) -> dict[str, Tensor]: + return { + "current_latent": batch.current_latent, + "future_latent": future, + "joint_target_history": batch.joint_target_history, + "action_history": batch.action_history, + "history_valid": batch.history_valid, + "text_hidden": batch.text_hidden, + "text_mask": batch.text_mask, + "future_drop_mask": future_drop_mask, + } + + +@torch.inference_mode() +def _validate_once( + model: torch.nn.Module, + loader: DataLoader, + *, + batches: int, + sample_batches: int, + action_steps: int, + device: torch.device, + seed: int, + case_output_dir: Path | None = None, + case_limit: int = 0, + action_mean: Tensor | None = None, + action_std: Tensor | None = None, +) -> dict[str, float]: + model.eval() + totals: dict[str, Tensor] = {} + sampled = 0 + iterator = iter(loader) + for index in range(batches): + try: + batch, metadata = next(iterator) + except StopIteration: + iterator = iter(loader) + batch, metadata = next(iterator) + batch = batch.to(device, non_blocking=True) + generator = torch.Generator(device=device).manual_seed(seed + index) + flow = sample_flow_batch( + batch.action_target, + alpha=1.5, + scale=0.999, + generator=generator, + ) + drop = torch.zeros(batch.action_target.shape[0], dtype=torch.bool, device=device) + with _autocast(): + output = model( + flow.noisy_action, + flow.flow_time, + **_conditions(batch, batch.future_pred_pooled, drop), + ) + loss, region = masked_action_flow_loss( + output["velocity"], + flow.target_velocity, + batch.action_valid, + ) + totals["loss"] = totals.get("loss", torch.zeros((), device=device)) + loss + for name, value in region.items(): + totals[name] = totals.get(name, torch.zeros((), device=device)) + value + if index < sample_batches: + sample_generator = torch.Generator(device=device).manual_seed(seed + 100_000 + index) + with _autocast(): + prediction, attention = sample_action_euler( + model, + conditions=_conditions(batch, batch.future_pred_pooled, drop), + batch_size=batch.action_target.shape[0], + steps=action_steps, + generator=sample_generator, + return_attention=True, + ) + absolute = (prediction.float() - batch.action_target.float()).abs() + totals["sample_mae"] = totals.get( + "sample_mae", torch.zeros((), device=device) + ) + absolute.mean() + totals["sample_first10_mae"] = totals.get( + "sample_first10_mae", torch.zeros((), device=device) + ) + absolute[:, :10].mean() + for key, value in attention.items(): + totals[key] = totals.get(key, torch.zeros((), device=device)) + value + if ( + case_output_dir is not None + and index < case_limit + and (not dist.is_initialized() or dist.get_rank() == 0) + ): + if action_mean is None or action_std is None: + raise ValueError("Action statistics are required for trajectory cases") + save_action_trajectory_case( + case_output_dir, + case_index=index, + prediction=prediction[0], + target=batch.action_target[0], + action_mean=action_mean, + action_std=action_std, + metadata=metadata[0], + attention=attention, + ) + sampled += 1 + model.train() + result = { + f"flow_{name}": float(_all_reduce_mean(value / batches)) + for name, value in totals.items() + if not name.startswith("sample") and not name.startswith("attention/") + } + if sampled: + for name in ("sample_mae", "sample_first10_mae"): + result[name] = float(_all_reduce_mean(totals[name] / sampled)) + for name in ("attention/current_mass", "attention/future_mass"): + if name in totals: + result[name] = float(_all_reduce_mean(totals[name] / sampled)) + return result + + +def _validation( + model: torch.nn.Module, + ema: ModelEMA, + loader: DataLoader, + cfg: DictConfig, + device: torch.device, + *, + case_output_dir: Path | None = None, + case_limit: int = 0, + action_mean: Tensor | None = None, + action_std: Tensor | None = None, +) -> dict[str, float]: + online = _validate_once( + model, + loader, + batches=int(cfg.batches), + sample_batches=int(cfg.sample_batches), + action_steps=int(cfg.action_steps), + device=device, + seed=int(cfg.seed), + ) + with ema.average_parameters(): + averaged = _validate_once( + model, + loader, + batches=int(cfg.batches), + sample_batches=int(cfg.sample_batches), + action_steps=int(cfg.action_steps), + device=device, + seed=int(cfg.seed), + case_output_dir=case_output_dir, + case_limit=case_limit, + action_mean=action_mean, + action_std=action_std, + ) + return { + **{f"val/online_{key}": value for key, value in online.items()}, + **{f"val/ema_{key}": value for key, value in averaged.items()}, + } + + +def _cloud_metrics(metrics: dict[str, Any]) -> dict[str, float]: + prefixes = ("train/", "performance/", "curriculum/", "val/") + return { + key: float(value) + for key, value in metrics.items() + if key.startswith(prefixes) and isinstance(value, (int, float)) + } + + +@hydra.main(version_base=None, config_path="../configs", config_name="train_action_head") +def train(cfg: DictConfig) -> None: + settings = set_up_distributed() + rank, world_size = settings.rank, settings.world_size + device = torch.device("cuda", settings.device) + _set_process_name(rank) + logging.basicConfig( + level=logging.INFO if rank == 0 else logging.WARNING, + format=f"[%(asctime)s][%(levelname)s][rank={rank}] %(message)s", + ) + _validate_configuration(cfg, world_size) + artifact_identity = _artifact_identity(cfg) + seed = int(cfg.run.seed) + rank + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + torch.backends.cuda.matmul.allow_tf32 = True + + output_dir = Path(cfg.run.output_dir).expanduser().resolve() + resolved = OmegaConf.to_container(cfg, resolve=True) + assert isinstance(resolved, dict) + if rank == 0: + output_dir.mkdir(parents=True, exist_ok=True) + (output_dir / "resolved_config.yaml").write_text( + OmegaConf.to_yaml(cfg, resolve=True), + encoding="utf-8", + ) + (output_dir / "artifact_identity.json").write_text( + json.dumps(artifact_identity, indent=2) + "\n", + encoding="utf-8", + ) + + model_config = ActionHeadConfig.model_validate(OmegaConf.to_container(cfg.model, resolve=True)) + model = JointBimanualActionFlow(model_config) + state_dict = torch.load(cfg.upstream.state_encoder, map_location="cpu", weights_only=True) + model.load_state_encoder_copy(state_dict) + report = model.parameter_report() + if int(report["total"]) > 700_000_000: + raise ValueError(f"Action model exceeds the 0.70B review gate: {report}") + if rank == 0: + logger.info("Action parameter report: %s", report) + model = model.to(device) + policy = MixedPrecisionPolicy( + param_dtype=torch.bfloat16, + reduce_dtype=torch.float32, + output_dtype=torch.bfloat16, + ) + if model_config.activation_checkpointing: + model.external_activation_checkpointing = True + for index, block in enumerate(model.blocks): + model.blocks[index] = checkpoint_wrapper( + block, + checkpoint_impl=CheckpointImpl.NO_REENTRANT, + preserve_rng_state=True, + ) + for block in model.blocks: + fully_shard(block, mp_policy=policy, reshard_after_forward=True) + fully_shard(model, mp_policy=policy, reshard_after_forward=True) + + train_dataset = RoboTwinActionDataset( + cfg.data.train_manifest, + state_stats=cfg.data.state_stats, + action_stats=cfg.data.action_stats, + future_cache=cfg.data.train_future_cache, + latent_mean=float(cfg.data.latent_mean), + latent_std=float(cfg.data.latent_std), + require_real_text=True, + allow_incomplete_future=bool( + cfg.data.get("allow_incomplete_future_cache", False) + ), + ) + val_dataset = RoboTwinActionDataset( + cfg.data.val_manifest, + state_stats=cfg.data.state_stats, + action_stats=cfg.data.action_stats, + future_cache=cfg.data.val_future_cache, + latent_mean=float(cfg.data.latent_mean), + latent_std=float(cfg.data.latent_std), + require_real_text=True, + allow_incomplete_future=bool( + cfg.data.get("allow_incomplete_future_cache", False) + ), + ) + action_stats = json.loads(Path(cfg.data.action_stats).read_text(encoding="utf-8")) + action_mean = torch.tensor(action_stats["mean"], dtype=torch.float32) + action_std = torch.tensor(action_stats["std"], dtype=torch.float32) + sampler = DeterministicActionSampler( + train_dataset, + seed=int(cfg.run.seed), + rank=rank, + world_size=world_size, + clean_probability=float(cfg.data.clean_probability), + ) + optimizer = _optimizer(model, cfg.training.optimizer) + scheduler = _scheduler(optimizer, cfg.training.optimizer, int(cfg.training.steps)) + ema = ModelEMA(model, decay=float(cfg.training.optimizer.ema_decay), unbias=False) + start_step = 0 + resume_path = cfg.run.get("continue_from") + if not resume_path and bool(cfg.run.auto_resume): + resume_path = latest_action_checkpoint(output_dir) + if resume_path: + start_step = load_action_checkpoint( + resume_path, + model=model, + optimizer=optimizer, + scheduler=scheduler, + ema=ema, + sampler=sampler, + expected_artifact_identity=artifact_identity, + ) + if rank == 0: + logger.info("Resumed Action training from %s at step %d", resume_path, start_step) + + train_loader = DataLoader( + train_dataset, + batch_size=int(cfg.training.per_device_batch), + sampler=sampler, + num_workers=int(cfg.dataloader.num_workers), + prefetch_factor=int(cfg.dataloader.prefetch_factor) + if int(cfg.dataloader.num_workers) + else None, + persistent_workers=int(cfg.dataloader.num_workers) > 0, + pin_memory=True, + collate_fn=collate_robotwin_action, + generator=torch.Generator().manual_seed(int(cfg.run.seed) + rank), + ) + val_loader = DataLoader( + val_dataset, + batch_size=int(cfg.validation.per_device_batch), + shuffle=False, + num_workers=0, + collate_fn=collate_robotwin_action, + ) + iterator = iter(train_loader) + tracker = SwanLabTracker.disabled() + if rank == 0: + tracker = SwanLabTracker.initialize( + OmegaConf.to_container(cfg.swanlab, resolve=True), + output_dir=output_dir, + run_config=resolved, + ) + + total_steps = int(cfg.training.steps) + accumulation = int(cfg.training.gradient_accumulation_steps) + per_device_batch = int(cfg.training.per_device_batch) + noise_repeats = int(model_config.noise_repeats) + log_path = output_dir / "metrics.jsonl" + last_metrics: dict[str, Any] = {} + interval_start = time.monotonic() + interval_windows = 0 + torch.cuda.reset_peak_memory_stats(device) + model.train() + try: + for step in range(start_step, total_steps): + optimizer.zero_grad(set_to_none=True) + accumulated: dict[str, Tensor] = {} + source_counts = torch.zeros(3, dtype=torch.long, device=device) + flow_times = [] + for micro in range(accumulation): + data_started = time.monotonic() + batch, _ = next(iterator) + accumulated["data_seconds"] = accumulated.get( + "data_seconds", torch.zeros((), device=device) + ) + torch.tensor(time.monotonic() - data_started, device=device) + batch = batch.to(device, non_blocking=True) + interval_windows += per_device_batch + rank_offset = micro * per_device_batch + torch.arange( + per_device_batch, device=device + ) + global_indices = ( + (step * accumulation * per_device_batch + rank_offset) * world_size + rank + ) + use_gt = choose_gt_future( + step, + global_indices, + gt_only_until=int(cfg.training.future_curriculum.gt_only_until), + transition_end=int(cfg.training.future_curriculum.transition_end), + ) + if not train_dataset.future_cache.complete and not bool(use_gt.all()): + raise RuntimeError( + "Predicted future was selected before its deterministic cache completed" + ) + if step >= int(cfg.training.future_curriculum.transition_end) and bool(use_gt.any()): + raise RuntimeError("GT future condition is forbidden after curriculum transition") + future = torch.where( + use_gt[:, None, None, None, None, None], + batch.future_gt_pooled, + batch.future_pred_pooled, + ) + future_drop = torch.rand(per_device_batch, device=device) < model_config.future_drop_prob + source_counts[0] += use_gt.sum() + source_counts[1] += (~use_gt).sum() + source_counts[2] += future_drop.sum() + for repeat in range(noise_repeats): + last_backward = ( + micro == accumulation - 1 and repeat == noise_repeats - 1 + ) + model.set_requires_gradient_sync(last_backward) + model.set_is_last_backward(last_backward) + flow = sample_flow_batch( + batch.action_target, + alpha=model_config.flow_beta_alpha, + scale=model_config.flow_time_scale, + ) + flow_times.append(flow.flow_time.detach()) + with _autocast(): + output = model( + flow.noisy_action, + flow.flow_time, + **_conditions(batch, future, future_drop), + ) + loss, region = masked_action_flow_loss( + output["velocity"], + flow.target_velocity, + batch.action_valid, + ) + (loss / (accumulation * noise_repeats)).backward() + accumulated["loss"] = accumulated.get( + "loss", torch.zeros((), device=device) + ) + loss.detach() / (accumulation * noise_repeats) + for name, value in region.items(): + accumulated[name] = accumulated.get( + name, torch.zeros((), device=device) + ) + value / (accumulation * noise_repeats) + sampler.mark_consumed(per_device_batch) + + grad_norm = torch.nn.utils.clip_grad_norm_( + model.parameters(), + float(cfg.training.optimizer.grad_clip), + ) + optimizer.step() + scheduler.step() + ema.step() + completed = step + 1 + should_log = completed <= int(cfg.run.early_log_steps) or completed % int( + cfg.run.log_every + ) == 0 + if should_log or completed == total_steps: + elapsed = max(time.monotonic() - interval_start, 1.0e-6) + counts = _all_reduce_sum(source_counts) + all_times = torch.cat(flow_times) + metrics = { + "step": completed, + "phase": ( + "gt_only" + if completed <= int(cfg.training.future_curriculum.gt_only_until) + else "transition" + if completed <= int(cfg.training.future_curriculum.transition_end) + else "predicted_only" + ), + "train/loss_action_flow": float(_all_reduce_mean(accumulated["loss"])), + "train/loss_left_arm": float(_all_reduce_mean(accumulated["left_arm"])), + "train/loss_left_gripper": float( + _all_reduce_mean(accumulated["left_gripper"]) + ), + "train/loss_right_arm": float(_all_reduce_mean(accumulated["right_arm"])), + "train/loss_right_gripper": float( + _all_reduce_mean(accumulated["right_gripper"]) + ), + "train/grad_norm": float(grad_norm), + "train/lr_main": float(optimizer.param_groups[0]["lr"]), + "train/flow_time_mean": float(_all_reduce_mean(all_times.mean())), + "train/flow_time_std": float(_all_reduce_mean(all_times.std())), + "curriculum/gt_count": int(counts[0]), + "curriculum/pred10_count": int(counts[1]), + "curriculum/null_count": int(counts[2]), + "performance/windows_per_second": interval_windows * world_size / elapsed, + "performance/flow_trajectories_per_second": ( + interval_windows * world_size * noise_repeats / elapsed + ), + "performance/data_seconds": float( + _all_reduce_mean(accumulated["data_seconds"]) + ), + "performance/gpu_allocated_gib": torch.cuda.memory_allocated(device) / 2**30, + "performance/gpu_reserved_gib": torch.cuda.memory_reserved(device) / 2**30, + "performance/gpu_peak_allocated_gib": torch.cuda.max_memory_allocated(device) + / 2**30, + } + last_metrics = metrics + if rank == 0: + logger.info( + "step=%d phase=%s loss=%.6f grad=%.3f throughput=%.2f peak=%.2f GiB", + completed, + metrics["phase"], + metrics["train/loss_action_flow"], + metrics["train/grad_norm"], + metrics["performance/windows_per_second"], + metrics["performance/gpu_peak_allocated_gib"], + ) + _write_jsonl(log_path, metrics) + try: + tracker.log(_cloud_metrics(metrics), step=completed) + except Exception as exc: + logger.warning("SwanLab Action logging failed and was skipped: %s", exc) + interval_start = time.monotonic() + interval_windows = 0 + + validation_due = completed % int(cfg.validation.every) == 0 or ( + completed == total_steps and bool(cfg.validation.at_end) + ) + if validation_due and val_dataset.future_cache.complete: + visualize = completed % int(cfg.visualization.every) == 0 + validation = _validation( + model, + ema, + val_loader, + cfg.validation, + device, + case_output_dir=( + output_dir / "visualizations" / f"step-{completed}" + if visualize + else None + ), + case_limit=int(cfg.visualization.num_cases) if visualize else 0, + action_mean=action_mean, + action_std=action_std, + ) + last_metrics.update(validation) + if rank == 0: + _write_jsonl(log_path, {"step": completed, **validation}) + try: + tracker.log(validation, step=completed) + except Exception as exc: + logger.warning("SwanLab Action validation failed and was skipped: %s", exc) + elif validation_due and rank == 0: + logger.info( + "Skipping predicted-future validation at step %d while cache is incomplete", + completed, + ) + + curriculum_milestone = ( + not bool(cfg.run.debug_smoke) + and completed + in ( + int(cfg.training.future_curriculum.gt_only_until), + int(cfg.training.future_curriculum.transition_end), + ) + ) + should_checkpoint = ( + completed % int(cfg.checkpoint.every) == 0 + or curriculum_milestone + or (completed == total_steps and bool(cfg.checkpoint.save_final)) + ) + if should_checkpoint: + save_action_checkpoint( + output_dir, + completed_steps=completed, + model=model, + optimizer=optimizer, + scheduler=scheduler, + ema=ema, + sampler=sampler, + resolved_config=resolved, + artifact_identity=artifact_identity, + metrics=last_metrics, + keep_recent=int(cfg.checkpoint.keep_recent), + ) + stop_at = cfg.run.get("stop_at_step_if_future_incomplete") + if ( + stop_at is not None + and completed >= int(stop_at) + and not train_dataset.future_cache.complete + ): + if rank == 0: + logger.info( + "Completed GT-only warm-up at step %d; exiting cleanly until " + "predicted-future cache completion", + completed, + ) + break + finally: + if rank == 0: + tracker.finish() + if dist.is_initialized(): + dist.barrier() + dist.destroy_process_group() + + +if __name__ == "__main__": + train() diff --git a/release-20261107/source/workspace_joint/mira/scripts/train_bihub_wam_world.py b/release-20261107/source/workspace_joint/mira/scripts/train_bihub_wam_world.py new file mode 100644 index 0000000000000000000000000000000000000000..938f2992266c1d887b2d09ea7f41b8bc8a438ce8 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/train_bihub_wam_world.py @@ -0,0 +1,671 @@ +#!/usr/bin/env python3 +"""Train the world-only BiHub Stage-W model with FSDP2 full sharding.""" + +from __future__ import annotations + +import ctypes +import json +import logging +import random +import time +from pathlib import Path +from typing import Any + +import hydra +import numpy as np +import torch +import torch.distributed as dist +from omegaconf import DictConfig, OmegaConf +from PIL import Image, ImageDraw +from torch import Tensor +from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( + CheckpointImpl, + checkpoint_wrapper, +) +from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard +from torch.utils.data import DataLoader + +from mira.codec.codec_model import VideoCodec +from mira.data.robotwin_wam_loader import ( + DeterministicBalancedSampler, + RoboTwinWAMDataset, + collate_robotwin_wam, +) +from mira.training.bihub_checkpoint import ( + latest_checkpoint, + load_bihub_checkpoint, + save_bihub_checkpoint, +) +from mira.training.distributed import set_up_distributed +from mira.training.ema import ModelEMA +from mira.training.swanlab_tracker import SwanLabTracker +from mira.training.visualization import write_video_ffmpeg +from mira.world_model.bihub_config import BiHubWorldModelConfig +from mira.world_model.bihub_latent_world_model import BiHubLatentWorldModel + +logger = logging.getLogger(__name__) + +# Loaded lazily on rank zero at the first formal visualization. Keeping only the decoder avoids +# retaining the frozen LingBot encoder, and keeping the decoder resident avoids re-reading a 3.4 GiB +# checkpoint for every fixed-case evaluation. +_VISUALIZATION_DECODER: torch.nn.Module | None = None + + +def _set_process_name(rank: int) -> None: + process_title = f"syncnet_core_worker_{rank}" + try: + import setproctitle + + setproctitle.setproctitle(process_title) + except ImportError: + pass + ctypes.CDLL(None).prctl(15, f"syncnet_core_r{rank}".encode()[:15], 0, 0, 0) + + +def _all_reduce_mean(value: torch.Tensor) -> torch.Tensor: + output = value.detach().float().clone() + if dist.is_initialized(): + dist.all_reduce(output, op=dist.ReduceOp.SUM) + output /= dist.get_world_size() + return output + + +def _autocast(): + return torch.autocast(device_type="cuda", dtype=torch.bfloat16) + + +def _optimizer(model: torch.nn.Module, cfg: DictConfig) -> torch.optim.Optimizer: + decay, no_decay = [], [] + exclusions = ("bias", "norm", "gate", "embedding", "bos", "register") + for name, parameter in model.named_parameters(): + if not parameter.requires_grad: + continue + if parameter.ndim < 2 or any(token in name.lower() for token in exclusions): + no_decay.append(parameter) + else: + decay.append(parameter) + return torch.optim.AdamW( + [ + {"params": decay, "weight_decay": float(cfg.weight_decay)}, + {"params": no_decay, "weight_decay": 0.0}, + ], + lr=float(cfg.lr), + betas=tuple(cfg.betas), + eps=float(cfg.eps), + ) + + +def _scheduler(optimizer: torch.optim.Optimizer, cfg: DictConfig): + warmup = int(cfg.warmup_steps) + floor = float(cfg.min_lr) / float(cfg.lr) + + def scale(step: int) -> float: + return max(floor, min(1.0, (step + 1) / max(1, warmup))) + + return torch.optim.lr_scheduler.LambdaLR(optimizer, scale) + + +def _validate_configuration(cfg: DictConfig, world_size: int) -> None: + if cfg.training.current_scope != "world_only": + raise ValueError("This revision authorizes world_only Stage W") + if bool(cfg.get("deferred_action", {}).get("enabled", False)): + raise ValueError("The action head must not be instantiated in Stage W") + if cfg.training.distributed.strategy != "fsdp2_full_shard": + raise ValueError("Formal three-view training requires FSDP2 full sharding") + effective = ( + world_size + * int(cfg.training.per_device_batch) + * int(cfg.training.gradient_accumulation_steps) + ) + if effective != int(cfg.training.effective_global_batch): + raise ValueError(f"effective global batch is {effective}, expected {cfg.training.effective_global_batch}") + if not bool(cfg.run.debug_smoke): + expected = (2048, 16, 16, 4) + actual = ( + int(cfg.model.hidden_dim), + int(cfg.model.layers), + int(cfg.model.heads), + int(cfg.model.kv_heads), + ) + if actual != expected: + raise ValueError(f"Formal training must use MIRA 1B backbone dimensions {expected}, got {actual}") + summary = json.loads((Path(cfg.dataset.raw_manifest_dir) / "summary.json").read_text()) + if not summary.get("complete_audit"): + raise ValueError("Formal Stage-W refuses a bounded smoke data audit") + + +def _single_view_roles( + step: int, + micro: int, + rank: int, + world_size: int, + accumulation: int, + per_device_batch: int, + device: torch.device, +) -> Tensor: + """Assign roles per sample while preserving the global 11/11/10 rotation. + + The mapping is independent of how the fixed global batch is partitioned into micro-batches. + Consequently 1x4, 2x2, and 4x1 all optimize the same role-balanced objective. + """ + samples_per_rank = accumulation * per_device_batch + rank_stream_offset = micro * per_device_batch + torch.arange(per_device_batch, device=device) + # This sample-major ordering preserves the role attached to every rank-local sampler item when + # 1x4 is repartitioned as 2x2 or 4x1; only the tensor grouping changes. + indices = (step * samples_per_rank + rank_stream_offset) * world_size + rank + return indices.remainder(3) + + +def _write_jsonl(path: Path, value: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(value, default=float) + "\n") + + +def _swanlab_training_metrics(metrics: dict[str, Any]) -> dict[str, float]: + """Return the compact cloud dashboard contract; local JSONL keeps the full diagnostics.""" + role_counts = [ + int(metrics["curriculum/left_samples"]), + int(metrics["curriculum/global_samples"]), + int(metrics["curriculum/right_samples"]), + ] + return { + "train/loss_world": float(metrics["train/loss_world"]), + "train/loss_left": float(metrics["train/loss_left"]), + "train/loss_global": float(metrics["train/loss_global"]), + "train/loss_right": float(metrics["train/loss_right"]), + "train/recovered_clean_mse": float(metrics["train/recovered_clean_mse"]), + "train/learning_rate": float(metrics["train/learning_rate"]), + "train/grad_norm": float(metrics["train/grad_norm"]), + "performance/windows_per_second": float(metrics["system/windows_per_second"]), + "performance/gpu_peak_allocated_gib": float(metrics["system/gpu_peak_allocated_gib"]), + "curriculum/full_bihub": float(metrics["stage"] == "full_bihub"), + "curriculum/role_imbalance": float(max(role_counts) - min(role_counts)), + } + + +def _latent_case_image(target: torch.Tensor, prediction: torch.Tensor, caption: str) -> Image.Image: + # Channel RMS is a stable, model-agnostic latent diagnostic. Rows are views; columns are + # target/prediction at horizons 1, 5, and 10. + horizons = (0, 4, 9) + tiles: list[list[Image.Image]] = [] + for view in range(3): + row = [] + for source in (target, prediction): + for horizon in horizons: + value = source[view, horizon].float().square().mean(dim=0).sqrt() + value = (value - value.min()) / (value.max() - value.min()).clamp_min(1.0e-6) + image = Image.fromarray((value.cpu().numpy() * 255).astype(np.uint8)).resize((192, 144)) + row.append(image.convert("RGB")) + tiles.append(row) + canvas = Image.new("RGB", (6 * 192, 3 * 144 + 30), "white") + for row_index, row in enumerate(tiles): + for column, image in enumerate(row): + canvas.paste(image, (column * 192, 30 + row_index * 144)) + ImageDraw.Draw(canvas).text((5, 5), caption[:150], fill="black") + return canvas + + +def _get_visualization_decoder(checkpoint: str | Path, device: torch.device) -> torch.nn.Module: + global _VISUALIZATION_DECODER + if _VISUALIZATION_DECODER is None: + codec = VideoCodec.load_from_checkpoint(checkpoint, device="cpu") + _VISUALIZATION_DECODER = codec.decoder.eval().requires_grad_(False).to(device) + del codec + return _VISUALIZATION_DECODER + + +@torch.inference_mode() +def _decoded_case_video( + context: Tensor, + target: Tensor, + prediction: Tensor, + *, + checkpoint: str | Path, + device: torch.device, +) -> Tensor: + """Decode a fixed case to a three-row (views), two-column (GT/prediction) RGB video.""" + decoder = _get_visualization_decoder(checkpoint, device) + rows: list[Tensor] = [] + # Decode one view and branch at a time to bound the temporary activation footprint. Context is + # deliberately identical in both columns, so discontinuities at the prediction boundary are + # visible rather than hidden by a custom rendering path. + for view in range(3): + ground_truth = torch.cat([context[view], target[view]], dim=0)[None].to(device) + predicted = torch.cat([context[view], prediction[view]], dim=0)[None].to(device) + with _autocast(): + ground_truth_rgb = decoder(ground_truth)[0] + predicted_rgb = decoder(predicted)[0] + row = torch.cat([ground_truth_rgb, predicted_rgb], dim=-1) + rows.append((row.float() * 0.5 + 0.5).clamp(0, 1).cpu()) + return torch.cat(rows, dim=-2) + + +@torch.inference_mode() +def _visualize_fixed_cases( + model: BiHubLatentWorldModel, + dataset: RoboTwinWAMDataset, + cfg: DictConfig, + *, + device: torch.device, + rank: int, + completed_steps: int, +) -> None: + case_count = min(int(cfg.visualization.num_cases), len(dataset)) + for case in range(case_count): + sample = dataset[case] + batch, metadata = collate_robotwin_wam([sample]) + batch = batch.to(device) + generator = torch.Generator(device=device).manual_seed(int(cfg.visualization.case_seed) + case) + noise = torch.randn(batch.world_future_raw.shape, generator=generator, device=device) + with _autocast(): + prediction = model( + batch, + sample_steps=int(cfg.visualization.sampling_steps), + noise=noise, + )["sample_future_raw"] + if rank == 0: + root = Path(cfg.run.output_dir) / "visualizations" / f"case-{case:02d}" + root.mkdir(parents=True, exist_ok=True) + torch.save( + { + "prediction_raw": prediction[0].cpu(), + "target_raw": batch.world_future_raw[0].cpu(), + "context_raw": batch.world_context_raw[0].cpu(), + "metadata": metadata[0], + }, + root / f"step-{completed_steps:07d}.pth", + ) + image = _latent_case_image( + batch.world_future_raw[0].cpu(), prediction[0].cpu(), metadata[0]["instruction"] + ) + temporary = root / f".step-{completed_steps:07d}.tmp.png" + image.save(temporary) + temporary.replace(root / f"step-{completed_steps:07d}.png") + if bool(cfg.visualization.get("decode_rgb", False)): + video = _decoded_case_video( + batch.world_context_raw[0], + batch.world_future_raw[0], + prediction[0], + checkpoint=cfg.visualization.codec_checkpoint, + device=device, + ) + final_video = root / f"step-{completed_steps:07d}.mp4" + temporary_video = root / f".step-{completed_steps:07d}.tmp.mp4" + write_video_ffmpeg( + temporary_video, + video, + fps=float(cfg.visualization.get("video_fps", 20)), + preset="fast", + ) + temporary_video.replace(final_video) + + +@torch.inference_mode() +def _validation( + model: BiHubLatentWorldModel, + loader: DataLoader, + *, + batches: int, + device: torch.device, + seed: int, +) -> dict[str, float]: + model.eval() + iterator = iter(loader) + totals: dict[str, torch.Tensor] = {} + for batch_index in range(batches): + try: + batch, _ = next(iterator) + except StopIteration: + iterator = iter(loader) + batch, _ = next(iterator) + batch = batch.to(device) + generator = torch.Generator(device=device).manual_seed(seed + batch_index) + noise = torch.randn( + batch.world_future_raw.shape, + generator=generator, + device=device, + dtype=torch.float32, + ) + future_tau = torch.rand( + batch.world_future_raw.shape[0], + 10, + 1, + 1, + 1, + generator=generator, + device=device, + dtype=torch.float32, + ) + with _autocast(): + output = model(batch, noise=noise, future_tau=future_tau) + for key in ("loss_world", "loss_left", "loss_global", "loss_right", "recovered_clean_mse"): + totals[key] = totals.get(key, torch.zeros((), device=device)) + output[key].nan_to_num() + model.train() + return {f"val/{key}": float(_all_reduce_mean(value / batches)) for key, value in totals.items()} + + +@hydra.main(version_base=None, config_path="../configs", config_name="train_bihub_wam_world") +def train(cfg: DictConfig) -> None: + settings = set_up_distributed() + rank, world_size = settings.rank, settings.world_size + device = torch.device("cuda", settings.device) + _set_process_name(rank) + logging.basicConfig( + level=logging.INFO if rank == 0 else logging.WARNING, + format="[%(asctime)s][%(levelname)s][rank=%(rank)s] %(message)s".replace("%(rank)s", str(rank)), + ) + _validate_configuration(cfg, world_size) + + seed = int(cfg.run.seed) + rank + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + torch.backends.cuda.matmul.allow_tf32 = True + output_dir = Path(cfg.run.output_dir).expanduser().resolve() + if rank == 0: + output_dir.mkdir(parents=True, exist_ok=True) + (output_dir / "resolved_config.yaml").write_text(OmegaConf.to_yaml(cfg, resolve=True), encoding="utf-8") + + model_config = BiHubWorldModelConfig.model_validate( + OmegaConf.to_container(cfg.model, resolve=True) + ) + model = BiHubLatentWorldModel(model_config).to(device) + parameter_report = model.parameter_report() + if rank == 0: + logger.info("Parameter report: %s", parameter_report) + + mp_policy = MixedPrecisionPolicy( + param_dtype=torch.bfloat16, + reduce_dtype=torch.float32, + output_dtype=torch.bfloat16, + ) + if model_config.activation_checkpointing: + model.world_model.external_activation_checkpointing = True + for index, block in enumerate(model.world_model.blocks): + model.world_model.blocks[index] = checkpoint_wrapper( + block, + checkpoint_impl=CheckpointImpl.NO_REENTRANT, + preserve_rng_state=True, + ) + for block in model.world_model.blocks: + fully_shard(block, mp_policy=mp_policy, reshard_after_forward=True) + fully_shard(model, mp_policy=mp_policy, reshard_after_forward=True) + + train_dataset = RoboTwinWAMDataset( + cfg.dataset.train_manifest, + cfg.dataset.dataset_stats, + require_real_text=not bool(cfg.run.debug_smoke), + ) + val_dataset = RoboTwinWAMDataset( + cfg.dataset.val_manifest, + cfg.dataset.dataset_stats, + require_real_text=not bool(cfg.run.debug_smoke), + ) + sampler = DeterministicBalancedSampler( + train_dataset, + seed=int(cfg.run.seed), + rank=rank, + world_size=world_size, + clean_probability=float(cfg.dataset.clean_probability), + ) + optimizer = _optimizer(model, cfg.training.optimizer) + scheduler = _scheduler(optimizer, cfg.training.optimizer) + ema = ModelEMA(model, decay=float(cfg.training.optimizer.ema_decay), unbias=False) + + resolved = OmegaConf.to_container(cfg, resolve=True) + assert isinstance(resolved, dict) + start_step = 0 + resume_path = cfg.run.get("continue_from") + if not resume_path and bool(cfg.run.auto_resume): + resume_path = latest_checkpoint(output_dir) + if resume_path: + start_step = load_bihub_checkpoint( + resume_path, + model=model, + optimizer=optimizer, + scheduler=scheduler, + ema=ema, + sampler=sampler, + ) + if rank == 0: + logger.info("Resumed from %s at optimizer step %d", resume_path, start_step) + + train_loader = DataLoader( + train_dataset, + batch_size=int(cfg.training.per_device_batch), + sampler=sampler, + num_workers=int(cfg.dataloader.num_workers), + prefetch_factor=int(cfg.dataloader.prefetch_factor) if int(cfg.dataloader.num_workers) else None, + persistent_workers=int(cfg.dataloader.num_workers) > 0, + pin_memory=True, + # Worker-base seed generation must not consume the model RNG restored from a checkpoint. + generator=torch.Generator().manual_seed(int(cfg.run.seed) + rank), + collate_fn=collate_robotwin_wam, + ) + val_loader = DataLoader( + val_dataset, + batch_size=int(cfg.validation.per_device_batch), + shuffle=False, + num_workers=0, + collate_fn=collate_robotwin_wam, + ) + iterator = iter(train_loader) + + tracker = SwanLabTracker.disabled() + if rank == 0: + tracker = SwanLabTracker.initialize( + OmegaConf.to_container(cfg.swanlab, resolve=True), + output_dir=output_dir, + run_config=resolved, + ) + + torch.cuda.reset_peak_memory_stats(device) + startup_allocated = torch.cuda.memory_allocated(device) + interval_roles = torch.zeros(3, dtype=torch.long, device=device) + interval_windows = 0 + interval_start = time.monotonic() + total_steps = int(cfg.training.steps) + accumulation = int(cfg.training.gradient_accumulation_steps) + log_path = output_dir / "metrics.jsonl" + last_metrics: dict[str, Any] = {} + model.train() + + try: + for step in range(start_step, total_steps): + optimizer.zero_grad(set_to_none=True) + accumulated: dict[str, Tensor] = {} + for micro in range(accumulation): + last_micro = micro == accumulation - 1 + model.set_requires_gradient_sync(last_micro) + model.set_is_last_backward(last_micro) + batch, _ = next(iterator) + batch = batch.to(device, non_blocking=True) + interval_windows += int(cfg.training.per_device_batch) + roles = ( + _single_view_roles( + step, + micro, + rank, + world_size, + accumulation, + int(cfg.training.per_device_batch), + device, + ) + if step < int(cfg.training.single_view_steps) + else None + ) + if roles is not None: + interval_roles += torch.bincount(roles, minlength=3) + with _autocast(): + output = model(batch, single_view_role=roles) + loss = output["loss_total"] / accumulation + loss.backward() + sampler.mark_consumed(int(cfg.training.per_device_batch)) + for key in ("loss_world", "loss_left", "loss_global", "loss_right", "recovered_clean_mse"): + value = output[key].detach().nan_to_num() / accumulation + accumulated[key] = accumulated.get(key, torch.zeros_like(value)) + value + + grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), float(cfg.training.optimizer.grad_clip)) + optimizer.step() + scheduler.step() + ema.step() + completed = step + 1 + + should_log = completed <= int(cfg.run.early_log_steps) or completed % int(cfg.run.log_every) == 0 + if should_log or completed == total_steps: + elapsed = max(time.monotonic() - interval_start, 1.0e-6) + roles = interval_roles.clone() + if dist.is_initialized(): + dist.all_reduce(roles, op=dist.ReduceOp.SUM) + metrics = { + "step": completed, + "stage": "single_view" if completed <= int(cfg.training.single_view_steps) else "full_bihub", + "train/loss_world": float(_all_reduce_mean(accumulated["loss_world"])), + "train/loss_left": float(_all_reduce_mean(accumulated["loss_left"])), + "train/loss_global": float(_all_reduce_mean(accumulated["loss_global"])), + "train/loss_right": float(_all_reduce_mean(accumulated["loss_right"])), + "train/recovered_clean_mse": float(_all_reduce_mean(accumulated["recovered_clean_mse"])), + "train/learning_rate": optimizer.param_groups[0]["lr"], + "train/grad_norm": float(grad_norm), + "curriculum/left_samples": int(roles[0]), + "curriculum/global_samples": int(roles[1]), + "curriculum/right_samples": int(roles[2]), + "system/windows_per_second": ( + interval_windows * world_size / elapsed + ), + "system/gpu_allocated_gib": torch.cuda.memory_allocated(device) / 2**30, + "system/gpu_reserved_gib": torch.cuda.memory_reserved(device) / 2**30, + "system/gpu_peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + } + last_metrics = metrics + if rank == 0: + logger.info( + "step=%d stage=%s loss=%.6f lr=%.3e grad=%.3f peak=%.2f GiB", + completed, + metrics["stage"], + metrics["train/loss_world"], + metrics["train/learning_rate"], + metrics["train/grad_norm"], + metrics["system/gpu_peak_allocated_gib"], + ) + _write_jsonl(log_path, metrics) + try: + tracker.log(_swanlab_training_metrics(metrics), step=completed) + except Exception as exc: # media/network failure must never kill training + logger.warning("SwanLab scalar logging failed and was skipped: %s", exc) + interval_roles.zero_() + interval_windows = 0 + interval_start = time.monotonic() + + if completed % int(cfg.validation.every) == 0 or ( + completed == total_steps and bool(cfg.validation.get("at_end", True)) + ): + with ema.average_parameters(): + validation = _validation( + model, + val_loader, + batches=int(cfg.validation.batches), + device=device, + seed=int(cfg.validation.seed), + ) + last_metrics.update(validation) + if rank == 0: + _write_jsonl(log_path, {"step": completed, **validation}) + try: + tracker.log(validation, step=completed) + except Exception as exc: + logger.warning("SwanLab validation logging failed and was skipped: %s", exc) + + if bool(cfg.visualization.enabled) and ( + completed % int(cfg.visualization.every) == 0 or completed == total_steps + ): + with ema.average_parameters(): + _visualize_fixed_cases( + model, + val_dataset, + cfg, + device=device, + rank=rank, + completed_steps=completed, + ) + if dist.is_initialized(): + dist.barrier() + + checkpoint_due = completed % int(cfg.checkpoint.every) == 0 + curriculum_switch = bool(cfg.checkpoint.get("on_curriculum_switch", True)) and ( + completed == int(cfg.training.single_view_steps) + ) + if checkpoint_due or curriculum_switch: + save_bihub_checkpoint( + output_dir, + completed_steps=completed, + model=model, + optimizer=optimizer, + scheduler=scheduler, + ema=ema, + sampler=sampler, + resolved_config=resolved, + metrics=last_metrics, + keep_recent=int(cfg.checkpoint.keep_recent), + ) + + if bool(cfg.checkpoint.get("save_final", True)): + save_bihub_checkpoint( + output_dir, + completed_steps=total_steps, + model=model, + optimizer=optimizer, + scheduler=scheduler, + ema=ema, + sampler=sampler, + resolved_config=resolved, + metrics=last_metrics, + permanent_name="stage-w-complete" if not bool(cfg.run.debug_smoke) else "smoke-complete", + keep_recent=int(cfg.checkpoint.keep_recent), + ) + finally: + peak = torch.tensor( + [torch.cuda.max_memory_allocated(device), torch.cuda.max_memory_reserved(device)], + dtype=torch.int64, + device=device, + ) + gathered = [torch.zeros_like(peak) for _ in range(world_size)] + if dist.is_initialized(): + dist.all_gather(gathered, peak) + else: + gathered = [peak] + if rank == 0: + memory = { + "startup_allocated_bytes_per_rank0": startup_allocated, + "per_rank": [ + {"rank": index, "max_allocated_bytes": int(value[0]), "max_reserved_bytes": int(value[1])} + for index, value in enumerate(gathered) + ], + "maximum_allocated_bytes": max(int(value[0]) for value in gathered), + "maximum_reserved_bytes": max(int(value[1]) for value in gathered), + "maximum_allocated_gib": max(int(value[0]) for value in gathered) / 2**30, + "maximum_reserved_gib": max(int(value[1]) for value in gathered) / 2**30, + "gpu_name": torch.cuda.get_device_name(device), + "world_size": world_size, + "steps": total_steps, + "profile": str( + cfg.run.get( + "profile_name", + "debug_isomorphic_smoke" + if bool(cfg.run.debug_smoke) + else "formal_mira_1b_backbone", + ) + ), + } + (output_dir / "memory_report.json").write_text(json.dumps(memory, indent=2) + "\n", encoding="utf-8") + logger.info("Peak training memory: %.3f GiB allocated", memory["maximum_allocated_gib"]) + tracker.finish() + if dist.is_initialized(): + dist.barrier() + dist.destroy_process_group() + + +if __name__ == "__main__": + train() diff --git a/release-20261107/source/workspace_joint/mira/scripts/train_codec.py b/release-20261107/source/workspace_joint/mira/scripts/train_codec.py new file mode 100644 index 0000000000000000000000000000000000000000..a28675bee4aead605a524c96fa2e500ad799123c --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/train_codec.py @@ -0,0 +1,723 @@ +"""Train the RAEv2 temporal-downsampling video codec. + +A single-GPU-safe trainer: reconstruction losses only (L1 + LPIPS + frozen-backbone feature +consistency), video-only. It supports the native zipped RoboTwin HDF5 loader and the original +Rocket League loader. Launch with Hydra: + + python scripts/train_codec.py dataset.train_index=/path/to/train dataset.test_index=/path/to/test + +Multi-GPU runs go through ``torchrun`` (the distributed setup no-ops for a single process). +""" + +from __future__ import annotations + +import contextlib +import ctypes +import logging +import os +import time +from collections import defaultdict +from collections.abc import Iterator +from datetime import datetime +from pathlib import Path + +import hydra +import torch +import torch.distributed as dist +import tqdm +from hydra.utils import instantiate +from omegaconf import DictConfig, OmegaConf +from rich.logging import RichHandler +from torch.nn.parallel import DistributedDataParallel + +from mira.codec import CodecLoss, VideoCodec, VideoCodecOutputs +from mira.codec.viz import ( + visualize_latent_correlation, + visualize_latent_std, + visualize_side_by_side, +) +from mira.data.robotwin_loader import ( + CAMERA_NAMES, + FixedRoboTwinCase, + create_robotwin_loader, + load_fixed_robotwin_case, + prepare_fixed_robotwin_cases, +) +from mira.data.training_loader import ClipMeta +from mira.data.training_loader import create_loader as create_rocket_league_loader +from mira.training.checkpoint_manager import CheckpointManager +from mira.training.distributed import get_distributed_settings, set_up_distributed +from mira.training.ema import DistributedEMA +from mira.training.lr_schedule import WarmupConstantCosineDecayLR +from mira.training.metrics.distributed_metric import DistributedMetric +from mira.training.swanlab_tracker import SwanLabTracker +from mira.training.tracker import TrainingTracker, display_execution_time, periodic_event +from mira.training.visualization import ( + VideoForWandb, + draw_text_on_first_frame, + video_to_uint8, + videos_for_wandb, + write_video_ffmpeg, + write_video_gif, +) + +logging.basicConfig(format="%(message)s", datefmt="[%X]", handlers=[RichHandler()]) + +logger = logging.getLogger(__name__) + +_wandb_enabled = False +_swanlab_tracker = SwanLabTracker.disabled() + + +def _set_process_name() -> None: + """Set both the short Linux comm name and the full process title.""" + base_name = os.environ.get("MIRA_PROCESS_NAME") + if not base_name: + return + + local_rank = os.environ.get("LOCAL_RANK") + process_title = f"{base_name}_{local_rank}" if local_rank is not None else base_name + process_name = process_title[:15] # Linux PR_SET_NAME includes a trailing NUL in its 16-byte limit. + + try: + import setproctitle # noqa: PLC0415 -- optional on non-training installs + + setproctitle.setproctitle(process_title) + except ImportError: + logger.warning("setproctitle is unavailable; only the short process name will be changed") + + try: + libc = ctypes.CDLL(None, use_errno=True) + libc.prctl.argtypes = [ + ctypes.c_int, + ctypes.c_char_p, + ctypes.c_ulong, + ctypes.c_ulong, + ctypes.c_ulong, + ] + libc.prctl.restype = ctypes.c_int + result = libc.prctl(15, process_name.encode(), 0, 0, 0) # PR_SET_NAME + if result != 0: + logger.warning("Could not set process name to %s (errno=%d)", process_name, ctypes.get_errno()) + except (AttributeError, OSError): + logger.warning("Could not set process name to %s on this platform", process_name) + + +def _autocast(device: int | str | torch.device): + """bfloat16 autocast on CUDA, a no-op elsewhere (so the trainer runs on CPU too).""" + if torch.cuda.is_available(): + return torch.autocast(device_type="cuda", dtype=torch.bfloat16) + return contextlib.nullcontext() + + +def _frame_size(cfg: DictConfig) -> tuple[int, int] | None: + fs = cfg.dataset.get("frame_size") + return tuple(fs) if fs is not None else None # type: ignore[return-value] + + +@hydra.main(version_base=None, config_path="../configs", config_name="train_codec") +def train(cfg: DictConfig) -> None: + _set_process_name() + distributed_settings = set_up_distributed() + is_main_process = distributed_settings.is_main_process + device = distributed_settings.device + + torch.manual_seed(cfg.run.seed + distributed_settings.rank) + logging.getLogger().setLevel(logging.INFO if is_main_process else logging.ERROR) + + logger.info("[magenta]" + "=" * 60 + "[/magenta]") + logger.info("[magenta]Training configuration:[/magenta]") + logger.info(OmegaConf.to_yaml(cfg)) + + if is_main_process: + _init_tracking(cfg) + + # Build the codec and (optionally) wrap it for distributed data parallelism. + raw_model: VideoCodec = instantiate(cfg.model.architecture) + raw_model.train().to(device) + is_distributed = dist.is_available() and dist.is_initialized() + model = DistributedDataParallel(raw_model, device_ids=[device]) if is_distributed else raw_model + + if cfg.run.get("compile"): + model.compile() + + if is_main_process: + n_params = sum(p.numel() for p in raw_model.parameters()) / 1e6 + logger.info(f"Initialized codec model with {n_params:.2f}M parameters") + _tracking_log({"System/model_parameters_m": n_params}, step=0) + + loss = CodecLoss(instantiate(cfg.model.loss.weights)) + loss.to(device) + if loss.weights.auto_weight: + loss.bind_last_layer(raw_model.decoder.last_layer_weight) + if loss.weights.loss_dino_latent_consistency > 0 or loss.weights.loss_lingbot_feature_consistency > 0: + loss.bind_encoder_backbone(raw_model.encoder.rae_backbone) + + train_loader, val_loader = _create_dataloaders(cfg, model=raw_model) + fixed_cases: list[FixedRoboTwinCase] = [] + if is_main_process: + fixed_cases = _prepare_fixed_visualization_cases(cfg, raw_model) + if is_distributed: + dist.barrier() + + optimizer = torch.optim.AdamW( + model.parameters(), + # `lr` needs to be a tensor to compile the backward pass. + **{**cfg.optim.optimizer, "lr": torch.tensor(cfg.optim.optimizer.lr)}, + ) + lr_scheduler = WarmupConstantCosineDecayLR(optimizer, **cfg.optim.scheduler) + + @torch.compile(disable=not cfg.run.get("compile")) + def optimizer_step() -> None: + optimizer.step() + lr_scheduler.step() + + iter_train_loader = iter(train_loader) + iter_val_loader = iter(val_loader) + with display_execution_time("Warming up dataloader", print_output=is_main_process): + # First batch takes longer; warm it up before the timed loop. + next(iter_train_loader) + + training_tracker = TrainingTracker( + world_size=distributed_settings.world_size, device=device, total_steps=int(cfg.run.steps) + ) + robotwin_view_counts = torch.zeros(len(CAMERA_NAMES), dtype=torch.long, device=device) + checkpoint_manager = CheckpointManager( + raw_model, + checkpoint_dir=cfg.run.output_dir, + save_every=cfg.run.checkpoint_every, + keep_recent=cfg.run.checkpoint_keep_recent, + keep_permanent_every=cfg.run.checkpoint_keep_permanent_every, + total_steps=int(cfg.run.steps), + model_ema_decay=cfg.optim.model_ema_decay, + ) + ema_latent_mean = DistributedEMA(decay=cfg.run.latents_ema_decay, device=device) + ema_latent_std = DistributedEMA(decay=cfg.run.latents_ema_decay, initial_value=1.0, device=device) + checkpoint_manager.register( + { + "optimizer": optimizer, + "lr_scheduler": lr_scheduler, + "ema_latent_mean": ema_latent_mean, + "ema_latent_std": ema_latent_std, + } + ) + + start_step = _resume(cfg, checkpoint_manager, ema_latent_mean, ema_latent_std) + + losses: dict[str, torch.Tensor] = {} + iter_num = start_step - 1 # so the final save below is well-defined even if the loop never runs + for iter_num in range(start_step, int(cfg.run.steps)): + step_start_time = time.monotonic() + + batch, metadata = next(iter_train_loader) + batch = batch.to(device) + if cfg.dataset.get("loader") == "robotwin2": + for item in metadata: + robotwin_view_counts[CAMERA_NAMES.index(item.camera)] += 1 + + optimizer.zero_grad(set_to_none=True) + with _autocast(device): + model_outputs = model(batch) + # Feature consistency runs the frozen backbone, so keep autocast active here too. + losses = loss(model_outputs, global_step=iter_num) + + with torch.no_grad(): + z = model_outputs.z.float() # from bfloat16 to float32 + ema_latent_mean.update(z) + ema_latent_std.update(z.std(keepdim=True)) + + losses["loss_total"].backward() + optimizer_step() + checkpoint_manager.model_ema.step() + + training_tracker.on_batch_processed(batch, losses) + + early_logging_steps = 10 + if periodic_event(iter_num, cfg.run.log_every, cfg.run.steps) or iter_num < early_logging_steps: + # All ranks must call get_stats()/compute() so the inner all_reduce completes. + stats = training_tracker.get_stats(step=iter_num) + stats["train/learning_rate"] = optimizer.param_groups[0]["lr"] + stats["train/latent_mean"] = ema_latent_mean.compute() + stats["train/latent_std"] = ema_latent_std.compute() + view_counts_to_log = robotwin_view_counts.clone() + if is_distributed: + dist.all_reduce(view_counts_to_log) + robotwin_view_counts.zero_() + if is_main_process: + total_views = int(view_counts_to_log.sum().item()) + if total_views > 0: + for view_index, view_name in enumerate(CAMERA_NAMES): + count = int(view_counts_to_log[view_index].item()) + stats[f"Data/view_count/{view_name}"] = count + stats[f"Data/view_fraction/{view_name}"] = count / total_views + stats["System/step_ms"] = (time.monotonic() - step_start_time) * 1000 + if torch.cuda.is_available(): + stats["System/gpu_memory_allocated_gb"] = ( + torch.cuda.memory_allocated(device) / 1024**3 + ) + stats["System/gpu_memory_reserved_gb"] = ( + torch.cuda.memory_reserved(device) / 1024**3 + ) + stats["System/gpu_max_memory_allocated_gb"] = ( + torch.cuda.max_memory_allocated(device) / 1024**3 + ) + stats |= {f"grad_norm/{k}": v.item() for k, v in loss.backward_metrics.items()} + logger.info(f"Step {iter_num}: total loss {stats['train/loss_total']:.4f}") + _tracking_log(stats, step=iter_num) + + if periodic_event( + iter_num, + cfg.visualization.every, + cfg.run.steps, + include_0=cfg.visualization.first, + ): + if is_main_process and fixed_cases: + with checkpoint_manager.model_ema.average_parameters(): + _visualize_fixed_robotwin_cases( + cfg, + raw_model, + fixed_cases, + device=device, + iter_num=iter_num, + ) + if is_distributed: + dist.barrier() + + if periodic_event( + iter_num, cfg.validation.val_every, cfg.run.steps, include_0=cfg.validation.val_first + ): + with checkpoint_manager.model_ema.average_parameters(): + run_validation(cfg, device, raw_model, iter_val_loader, loss, iter_num) + + if periodic_event(iter_num, cfg.run.checkpoint_every, cfg.run.steps, include_0=False): + if is_main_process: + checkpoint_manager.maybe_save_checkpoint( + iter_num, + extra_data=_extra_data(iter_num, losses, ema_latent_mean, ema_latent_std), + ) + if is_distributed: + dist.barrier() + + if is_distributed: + dist.barrier() + + if is_main_process and iter_num >= start_step: # skip when resuming an already-finished run + checkpoint_manager.maybe_save_checkpoint( + iter_num, extra_data=_extra_data(iter_num, losses, ema_latent_mean, ema_latent_std), final=True + ) + logger.info("Done training") + if is_main_process: + _finish_tracking() + if is_distributed: + dist.barrier() + dist.destroy_process_group() + + +def _extra_data( + iter_num: int, + losses: dict[str, torch.Tensor], + ema_latent_mean: DistributedEMA, + ema_latent_std: DistributedEMA, +) -> dict: + extra_data = {k: v.item() for k, v in losses.items()} + extra_data["iter_num"] = iter_num + extra_data["latent_mean_std"] = [ema_latent_mean.value, ema_latent_std.value] + return extra_data + + +def _init_tracking(cfg: DictConfig) -> None: + """Initialize configured trackers and persist the exact resolved codec configuration.""" + global _swanlab_tracker # noqa: PLW0603 -- one rank-zero tracker for this training process + + Path(cfg.run.output_dir).mkdir(parents=True, exist_ok=True) + # The codec checkpoint loader reads codec_config.yaml from a parent dir of the checkpoint. + OmegaConf.save(cfg, Path(cfg.run.output_dir) / VideoCodec.CONFIG_FILENAME, resolve=True) + + if str(cfg.wandb.mode).lower() != "disabled": + _init_wandb(cfg) + + swanlab_config = OmegaConf.to_container(cfg.swanlab, resolve=True) + run_config = OmegaConf.to_container(cfg, resolve=True) + assert isinstance(swanlab_config, dict) + assert isinstance(run_config, dict) + _swanlab_tracker = SwanLabTracker.initialize( + swanlab_config, + output_dir=cfg.run.output_dir, + run_config=run_config, + ) + + +def _init_wandb(cfg: DictConfig) -> None: + global _wandb_enabled # noqa: PLW0603 -- one rank-zero tracker for this training process + + import wandb # noqa: PLC0415 -- optional dep, used only on the main process + + if cfg.wandb.remove_old_runs: + try: + api = wandb.Api() + runs = api.runs( + f"{cfg.wandb.entity}/{cfg.wandb.project}", filters={"display_name": cfg.wandb.name} + ) + for run in runs: + logger.info(f"Deleting existing run: {run.id}") + run.delete() + except Exception: # noqa: BLE001 -- skip if the project does not exist yet + pass + else: + timestamp = datetime.now().strftime("%y%m%d-%H%M") + cfg.wandb.name = f"{cfg.wandb.name}-{timestamp}" + if cfg.wandb.group is not None: + cfg.wandb.group = f"{cfg.wandb.group}-{timestamp}" + + wandb.init( + entity=cfg.wandb.entity, + project=cfg.wandb.project, + name=cfg.wandb.name, + group=cfg.wandb.group, + config=OmegaConf.to_container(cfg, resolve=True), + dir=cfg.run.output_dir, + mode=cfg.wandb.mode, + ) + _wandb_enabled = wandb.run is not None + + +def _wandb_log(stats: dict, step: int) -> None: + if not _wandb_enabled: + return + + import wandb # noqa: PLC0415 -- optional dep, used only on the main process + + if wandb.run is not None: + wandb.log(stats, step=step) + + +def _tracking_log(stats: dict, step: int) -> None: + _wandb_log(stats, step=step) + _swanlab_tracker.log(stats, step=step) + + +def _finish_tracking() -> None: + if _wandb_enabled: + import wandb # noqa: PLC0415 -- optional dep, used only on the main process + + wandb.finish() + _swanlab_tracker.finish() + + +def _resume( + cfg: DictConfig, + checkpoint_manager: CheckpointManager, + ema_latent_mean: DistributedEMA, + ema_latent_std: DistributedEMA, +) -> int: + """Resume from continue_from / finetune_from / an auto-discovered checkpoint, else start at 0.""" + continue_from = cfg.run.get("continue_from") + finetune_from = cfg.run.get("finetune_from") + if continue_from and finetune_from: + raise ValueError("Set at most one of run.continue_from and run.finetune_from") + + if continue_from: + return checkpoint_manager.continue_from(continue_from) + if finetune_from: + init_extra_data = checkpoint_manager.finetune_from(finetune_from) + if "latent_mean_std" in init_extra_data: + init_mean, init_std = init_extra_data["latent_mean_std"] + ema_latent_mean._ema.fill_(float(init_mean)) + ema_latent_std._ema.fill_(float(init_std)) + logger.info(f"Seeded latent EMA from finetune checkpoint: mean={init_mean}, std={init_std}") + return 0 + if checkpoint_manager.latest_checkpoint is not None: + logger.info(f"Auto-resuming from existing checkpoint in {cfg.run.output_dir}") + return checkpoint_manager.continue_from(checkpoint_manager.latest_checkpoint) + return 0 + + +def _create_dataloaders(cfg: DictConfig, model: VideoCodec): + if cfg.dataset.get("loader") == "robotwin2": + common = dict( + dataset_root=cfg.dataset.root, + clip_len=model.config.encoder.video.timesteps, + source_fps=cfg.dataset.source_fps, + target_fps=model.config.encoder.video.fps, + num_workers=cfg.dataloader.num_workers, + archive_mix_size=cfg.dataloader.archive_mix_size, + tasks=list(cfg.dataset.tasks), + robots=list(cfg.dataset.robots), + domains=list(cfg.dataset.domains), + prefetch_factor=cfg.dataloader.prefetch_factor, + infinite=True, + ) + train_loader = create_robotwin_loader( + manifest_path=cfg.dataset.train_manifest, + batch_size=cfg.run.batch_size, + seed=cfg.run.seed, + shuffle=True, + **common, + ) + val_loader = create_robotwin_loader( + manifest_path=cfg.dataset.val_manifest, + batch_size=cfg.validation.batch_size or cfg.run.batch_size, + seed=37, + shuffle=False, + **common, + ) + return train_loader, val_loader + + common = dict( + clip_len=model.config.encoder.video.timesteps, + target_fps=model.config.encoder.video.fps, + n_players=cfg.dataset.n_players, + num_workers=cfg.dataloader.num_workers, + shuffle_buffer_size=cfg.dataloader.shuffle_buffer_size, + frame_size=_frame_size(cfg), + valid_keys=list(cfg.actions.valid_keys), + infinite=True, + ) + train_loader = create_rocket_league_loader( + index_path=cfg.dataset.train_index, + batch_size=cfg.run.batch_size, + seed=cfg.run.seed, + exclude_replays=cfg.dataset.exclude_replays, + **common, + ) + val_loader = create_rocket_league_loader( + index_path=cfg.dataset.test_index, + batch_size=cfg.validation.batch_size or cfg.run.batch_size, + seed=37, + exclude_replays=True, + **common, + ) + return train_loader, val_loader + + +def _prepare_fixed_visualization_cases( + cfg: DictConfig, + model: VideoCodec, +) -> list[FixedRoboTwinCase]: + """Persist a diverse fixed-case set once, then reuse it across resumes.""" + if not cfg.visualization.enabled or cfg.dataset.get("loader") != "robotwin2": + return [] + cases_path = Path(cfg.run.output_dir) / cfg.visualization.output_subdir / "cases.json" + cases = prepare_fixed_robotwin_cases( + dataset_root=cfg.dataset.root, + manifest_path=cfg.dataset.val_manifest, + cases_path=cases_path, + num_cases=cfg.visualization.num_cases, + clip_len=model.config.encoder.video.timesteps, + source_fps=cfg.dataset.source_fps, + target_fps=model.config.encoder.video.fps, + seed=cfg.visualization.case_seed, + tasks=list(cfg.dataset.tasks), + robots=list(cfg.dataset.robots), + domains=list(cfg.dataset.domains), + ) + logger.info("Fixed RoboTwin visualization cases: %s", cases_path) + return cases + + +def _write_video_atomic(path: Path, video: torch.Tensor, fps: int) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.stem}.tmp.mp4") + write_video_ffmpeg(temporary, video, fps=fps) + temporary.replace(path) + + +def _write_gif_atomic( + path: Path, + video: torch.Tensor, + *, + source_fps: int, + target_fps: float, + max_side: int, +) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.stem}.tmp.gif") + write_video_gif( + temporary, + video, + source_fps=source_fps, + target_fps=target_fps, + max_side=max_side, + ) + temporary.replace(path) + + +def _visualize_fixed_robotwin_cases( + cfg: DictConfig, + model: VideoCodec, + cases: list[FixedRoboTwinCase], + *, + device: torch.device | int | str, + iter_num: int, +) -> None: + """Save aligned head/left/right reconstruction videos for fixed cases (rank 0 only).""" + model.eval() + fps = model.config.encoder.video.fps + output_root = Path(cfg.run.output_dir) / cfg.visualization.output_subdir + wandb_payload: dict = {} + swanlab_payload: dict = {} + + try: + for case_index, case in enumerate(cases): + loaded_views = load_fixed_robotwin_case( + cfg.dataset.root, + case, + clip_len=model.config.encoder.video.timesteps, + source_fps=cfg.dataset.source_fps, + target_fps=fps, + ) + reconstruction_rows: list[torch.Tensor] = [] + reference_rows: list[torch.Tensor] = [] + for batch, metadata in loaded_views: + batch = batch.to(device) + with torch.no_grad(), _autocast(device): + model_outputs: VideoCodecOutputs = model(batch) + + reconstruction = visualize_side_by_side(model_outputs)["viz_video"] + reconstruction = draw_text_on_first_frame( + reconstruction, [f"GT | reconstruction | {metadata.caption}"] + ) + reconstruction_rows.append(reconstruction[0].cpu()) + + reference = video_to_uint8(model_outputs.input_video * 0.5 + 0.5) + reference = draw_text_on_first_frame(reference, [metadata.caption]) + reference_rows.append(reference[0].cpu()) + + # Each row is one aligned camera. Reconstruction rows contain GT | prediction. + all_views = torch.cat(reconstruction_rows, dim=-2) + references = torch.cat(reference_rows, dim=-2) + case_dir = output_root / f"case-{case_index:02d}_{case.slug}" + reference_path = case_dir / "reference_all_views.mp4" + if not reference_path.exists(): + _write_video_atomic(reference_path, references, fps) + output_path = case_dir / f"step-{iter_num:07d}_all_views.mp4" + _write_video_atomic(output_path, all_views, fps) + + caption = ( + f"{case.entry.task} | {case.entry.robot}/{case.entry.domain} | " + f"episode {case.entry.episode} | step {iter_num}" + ) + if _wandb_enabled: + import wandb # noqa: PLC0415 -- only used by rank 0 when a run exists + + wandb_payload[f"fixed_cases/case_{case_index:02d}"] = wandb.Video( + str(output_path), format="mp4", caption=caption + ) + if _swanlab_tracker.enabled and cfg.swanlab.log_videos: + cloud_path = case_dir / f"step-{iter_num:07d}_cloud.gif" + _write_gif_atomic( + cloud_path, + all_views, + source_fps=fps, + target_fps=float(cfg.swanlab.video_fps), + max_side=int(cfg.swanlab.video_max_side), + ) + swanlab_payload[f"fixed_cases/case_{case_index:02d}"] = _swanlab_tracker.video( + cloud_path, + caption=caption, + ) + if wandb_payload: + _wandb_log(wandb_payload, step=iter_num) + if swanlab_payload: + _swanlab_tracker.log(swanlab_payload, step=iter_num) + logger.info( + "Saved %d fixed three-view reconstruction case(s) at step %d under %s", + len(cases), + iter_num, + output_root, + ) + finally: + model.train() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + + +def run_validation( + cfg: DictConfig, + device: torch.device | int | str, + model: VideoCodec, + iter_val_loader: Iterator[tuple], + loss: CodecLoss, + iter_num: int, +) -> None: + t1 = time.time() + distributed_settings = get_distributed_settings() + is_distributed = dist.is_available() and dist.is_initialized() + model.eval() + world_size = distributed_settings.world_size + val_batch_size = cfg.validation.batch_size or cfg.run.batch_size + n_batches = cfg.validation.val_n_samples // (val_batch_size * world_size) + fps = model.config.encoder.video.fps + + if distributed_settings.is_main_process and cfg.validation.random_visualization: + _visualize(model, iter_val_loader, device, iter_num, fps) + if torch.cuda.is_available(): + torch.cuda.empty_cache() + if is_distributed: + dist.barrier() + + metric_trackers: dict[str, DistributedMetric] = defaultdict(lambda: DistributedMetric(device=device)) + for _ in tqdm.trange( + max(1, n_batches), disable=not distributed_settings.is_main_process, desc="Running validation" + ): + batch, _ = next(iter_val_loader) + batch = batch.to(device) + with torch.no_grad(), _autocast(device): + model_outputs: VideoCodecOutputs = model(batch) + for k, v in loss(model_outputs).items(): + metric_trackers[k].update(v) + + metrics = {k: tracker.compute_and_reset().item() for k, tracker in metric_trackers.items()} + if distributed_settings.is_main_process: + logger.info(f"Validation took {time.time() - t1:.2f}s") + logger.info( + f"Validation at step {iter_num}: " + ", ".join(f"{k}={v:.4f}" for k, v in metrics.items()) + ) + _tracking_log({f"test/{k}": v for k, v in metrics.items()}, step=iter_num) + + model.train() + if is_distributed: + dist.barrier() + + +def _visualize( + model: VideoCodec, + iter_val_loader: Iterator[tuple], + device: torch.device | int | str, + iter_num: int, + fps: int, +) -> None: + """Log a reconstruction side-by-side video and latent diagnostics to W&B (rank 0 only).""" + batch, metadata = next(iter_val_loader) + batch = batch.to(device) + with torch.no_grad(), _autocast(device): + model_outputs: VideoCodecOutputs = model(batch) + + meta: list[ClipMeta] = metadata + captions = [getattr(m, "caption", f"{m.match_id}:{m.perspective}") for m in meta] + caption = ", ".join(captions) + + viz_video = visualize_side_by_side(model_outputs)["viz_video"] + viz_video = draw_text_on_first_frame(viz_video, captions) + + with videos_for_wandb( + {"videos/reconstruction": VideoForWandb(video=viz_video, caption=caption)}, fps=fps + ) as wandb_videos: + _wandb_log(dict(wandb_videos), step=iter_num) + + _wandb_log( + { + "viz/latent_correlation_patch": visualize_latent_correlation(model_outputs, "patch", caption), + "viz/latent_correlation_channels": visualize_latent_correlation( + model_outputs, "channels", caption + ), + "viz/latent_correlation_time": visualize_latent_correlation(model_outputs, "time", caption), + "viz/latent_std_patch": visualize_latent_std(model_outputs, axis="patch"), + "viz/latent_std_channels": visualize_latent_std(model_outputs, axis="channels"), + }, + step=iter_num, + ) + + +if __name__ == "__main__": + train() diff --git a/release-20261107/source/workspace_joint/mira/scripts/train_joint_world_action.py b/release-20261107/source/workspace_joint/mira/scripts/train_joint_world_action.py new file mode 100644 index 0000000000000000000000000000000000000000..2fd5586af33f9f943cc64e5299aace649bc01589 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/train_joint_world_action.py @@ -0,0 +1,1143 @@ +#!/usr/bin/env python3 +"""Cache-free end-to-end fine-tuning of World-v12 and Action-v13.""" + +from __future__ import annotations + +import argparse +import json +import itertools +import logging +import math +import os +import random +import shutil +import signal +import time +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import torch.distributed as dist +import torch.distributed.checkpoint as dcp +from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( + CheckpointImpl, + checkpoint_wrapper, +) +from torch.distributed.checkpoint.state_dict import get_state_dict, set_state_dict +from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard +from torch.distributed.device_mesh import init_device_mesh +from torch.distributed.tensor import DTensor +from torch.utils.data import DataLoader + +from mira.action_v6.model import BiHubWAMActionStage +from mira.codec.codec_model import VideoCodec +from mira.data.joint_online import collate_joint_online +from mira.data.joint_eval_language import ( + JointEvalLanguageSampler as JointEvalAlignedSampler, + JointEvalLanguageDataset as JointOnlineRoboTwinDataset, + parse_instruction_mix, +) +from mira.data.robotwin_wam_schema import sha256_file +from mira.data.world_v6 import preprocess_qwen_rgb +from mira.inference.robotwin_v10_runtime import _load_online_model +from mira.inference.robotwin_v6_runtime import _empty_codec_batch +from mira.joint.model import JointWorldActionModel +from mira.joint.paths import workspace_path +from mira.joint.image_contract import TRAINING_IMAGE_CONTRACTS, codec_needs_bgr, require_resume_contract +from mira.joint.training_utils import ParameterEMA, load_task_weights, lr_scale as scheduled_lr_scale +from mira.data.robotwin_rgb import official_image_decoder +from mira.training.distributed import set_up_distributed +from mira.training.swanlab_tracker import SwanLabTracker +from mira.training.world_v6.artifacts import canonical_sha256 +from mira.training.world_v8.checkpoint import checkpoint_fingerprint, load_online_source +from mira.world_v6.config import WorldV6ModelConfig +from mira.world_v6.model import WorldV6System +from mira.world_v6.qwen_current_anchor import FrozenQwenCurrentLanes +from mira.world_v6.state_encoder import StateEncoderV6 + +LOGGER = logging.getLogger("joint_world_action") + + +def _defaults() -> dict[str, Path]: + mira_root = Path(__file__).resolve().parents[1] + workspace = mira_root.parent + bundle = workspace.parent if workspace.name == "source" else workspace + released = bundle / "release-20260902" / "workspace" + + def first(candidates: list[Path]) -> Path: + return next((path.resolve() for path in candidates if path.exists()), candidates[0]) + + return { + "world": first( + [ + workspace / "outputs/robotwin_bihub_world_v12_largebatch_remaining/main-checkpoint-25066", + released / "outputs/robotwin_bihub_world_v12_largebatch_remaining/main-checkpoint-25066", + ] + ), + "action": first( + [ + workspace + / "outputs/robotwin_bihub_wam_v13_action_eval_aligned_continue4epoch" + / "action-checkpoint-23016", + released + / "outputs/robotwin_bihub_wam_v13_action_eval_aligned_continue4epoch" + / "action-checkpoint-23016", + ] + ), + "codec": first( + [workspace / "outputs/mira_robotwin_codec/checkpoint-125000/checkpoint.pth"] + ), + "qwen": first( + [workspace / "models/Qwen3-VL-2B-Instruct"] + ), + "output": workspace / "outputs/robotwin_joint_world_action_rgb_v1", + } + + +def _parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description="Joint World-v12 + Action-v13 training directly from RoboTwin archives" + ) + parser.add_argument("dataset_root", help="RoboTwin2.0 root containing dataset/*/*.zip") + parser.add_argument("--manifest-dir") + parser.add_argument("--image-color-order", choices=("rgb",), default="rgb", + help="Frames are decoded to RGB with the official marker-aware decoder") + parser.add_argument( + "--image-contract", choices=tuple(TRAINING_IMAGE_CONTRACTS), default="codec-bgr-qwen-rgb", + help="codec-bgr-qwen-rgb keeps the released codec latent space and gives Qwen true RGB", + ) + parser.add_argument( + "--instruction-mix", default="seen=0.8,full_goal=0.2", + help="Instruction probabilities, e.g. seen=0.8,full_goal=0.2", + ) + parser.add_argument( + "--resume-from-joint-checkpoint", + help="Continue from an explicit joint checkpoint into a new output directory, including optimizer/sampler state", + ) + parser.add_argument( + "--init-from-joint-checkpoint", + help="Warm-start joint model weights from a checkpoint in a new output directory; reset optimizer and step count", + ) + parser.add_argument("--world-checkpoint") + parser.add_argument("--action-checkpoint") + parser.add_argument("--codec-checkpoint") + parser.add_argument("--qwen-root") + parser.add_argument("--output-dir") + parser.add_argument("--steps", type=int, default=20_000) + parser.add_argument("--per-device-batch", type=int, default=1) + parser.add_argument("--gradient-accumulation", type=int, default=4) + parser.add_argument("--num-workers", type=int, default=2) + parser.add_argument( + "--shard-group-size", type=int, default=0, + help="GPUs per FSDP shard group; 0 shards across the full world. Use 8 for 3x8 HSDP.", + ) + parser.add_argument("--world-rollout-steps", type=int, default=10) + parser.add_argument( + "--world-activation-checkpoint-blocks", + type=int, + default=-1, + help="Number of leading World blocks to checkpoint; -1 means all blocks.", + ) + parser.add_argument( + "--action-activation-checkpoint-blocks", + type=int, + default=7, + help="Number of leading Action blocks to checkpoint.", + ) + parser.add_argument( + "--world-partial-checkpoint-block", + type=int, + default=-1, + help="Optional unwrapped World block index whose selected submodules are checkpointed.", + ) + parser.add_argument( + "--world-partial-checkpoint-components", + default="", + help=( + "Comma-separated subset of hub,hub.attention,temporal_attention," + "condition,condition.attention,condition.attention.gate_proj," + "condition.attention.out_proj,mlp." + ), + ) + parser.add_argument("--lr-world", type=float, default=1.0e-5) + parser.add_argument("--lr-action", type=float, default=3.0e-5) + parser.add_argument("--warmup-steps", type=int, default=500) + parser.add_argument("--min-lr-ratio", type=float, default=0.05, + help="Cosine floor as a fraction of peak learning rate at --steps") + parser.add_argument("--ema-decay", type=float, default=0.0, + help="Keep an EMA of all trainable weights (0 disables); exported with --weights ema") + parser.add_argument("--rollout-grad-steps", type=int, default=0, + help="Backpropagate only through the last N World rollout steps (0 = all)") + parser.add_argument("--task-weights", + help="JSON {task: weight} for the training task draw (default uniform)") + parser.add_argument("--clean-probability", type=float, default=0.5, + help="Probability of drawing a clean episode for the chosen task") + parser.add_argument( + "--action-loss-mode", default="source", + choices=("source", "masked_action_flow_mse_only", "masked_action_flow_mse_execute8_gripper_weighted"), + help="Action flow loss; source keeps the Action checkpoint's loss", + ) + parser.add_argument("--state-noise-std", type=float, default=0.0, + help="Gaussian noise (normalized units) on valid state history during training") + parser.add_argument("--weight-world-flow", type=float, default=1.0) + parser.add_argument("--weight-latent", type=float, default=0.0) + parser.add_argument("--weight-pixel", type=float, default=0.0) + parser.add_argument("--weight-action", type=float, default=1.0) + parser.add_argument("--log-every", type=int, default=10) + parser.add_argument("--save-every", type=int, default=1_000) + parser.add_argument("--validate-every", type=int, default=500) + parser.add_argument("--validation-batches", type=int, default=8) + parser.add_argument("--keep-last", type=int, default=3) + parser.add_argument("--keep-every", type=int, default=5000) + parser.add_argument("--seed", type=int, default=2026) + parser.add_argument("--no-auto-resume", action="store_true") + parser.add_argument("--max-steps", type=int) + parser.add_argument( + "--max-runtime-seconds", type=int, default=0, + help="Gracefully checkpoint and stop after this many training seconds; 0 disables the limit.", + ) + parser.add_argument( + "--probe-only", + action="store_true", + help="Run optimizer steps and memory/gradient checks without validation or checkpoints.", + ) + parser.add_argument("--swanlab-mode", choices=("online", "offline", "disabled"), default="online") + parser.add_argument("--swanlab-project", default="Multi_WAM") + parser.add_argument("--swanlab-experiment-name", default="Joint-Eval-Language-V3") + parser.add_argument( + "--swanlab-token-file", + default=str(Path(__file__).resolve().parents[2] / "z_oranger/token.txt"), + ) + return parser + + +def _barrier() -> None: + if dist.is_initialized(): + dist.barrier() + + +def _world_config(checkpoint: Path) -> tuple[WorldV6ModelConfig, dict[str, Any]]: + metadata = json.loads((checkpoint / "trainer_state.json").read_text(encoding="utf-8")) + if metadata.get("architecture") != "bihub-world-v12-largebatch-remaining-online": + raise ValueError("joint training requires the final online World-v12 checkpoint") + if int(metadata.get("completed_steps", -1)) != 25_066: + raise ValueError("joint training requires World-v12 step 25066") + return WorldV6ModelConfig.model_validate(metadata["resolved_config"]["model"]), metadata + + +def _build_action(checkpoint: Path, loss_override: str = "source") -> tuple[BiHubWAMActionStage, dict[str, Any]]: + metadata = json.loads((checkpoint / "trainer_state.json").read_text(encoding="utf-8")) + if metadata.get("architecture") != "bihub-wam-v13-action-eval-aligned-continue4epoch": + raise ValueError("joint training requires the final Action-v13 checkpoint") + if int(metadata.get("completed_steps", -1)) not in (11_508, 23_016): + raise ValueError("joint training requires released Action-v13 step 11508 or 23016") + loss_mode = metadata["resolved_config"]["action"]["loss"] if loss_override == "source" else loss_override + stage = BiHubWAMActionStage( + state_encoder=StateEncoderV6(hidden_size=512, layers=2, heads=8, history_steps=20), + delta_scale=torch.ones(3, 10, 32), + action_mean=torch.zeros(14), + action_std=torch.ones(14), + loss_mode=loss_mode, + ) + _load_online_model(stage, checkpoint) + return stage, metadata + + +def _prepare_qwen_identity(output: Path, qwen_root: Path, rank: int, contract: dict) -> Path: + path = output / "qwen_online_identity.json" + if rank == 0: + payload = { + "format_version": 1, + "repo": "Qwen/Qwen3-VL-2B-Instruct", + "local_root": str(qwen_root), + "prompt_version": "bihub-v6-role-v1", + "attention_implementation": "sdpa", + "dtype": "bfloat16", + "mode": "frozen_online_no_cache", + "image_contract": contract, + } + temporary = path.with_suffix(".json.tmp") + temporary.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + _barrier() + return path + + +def _identity(args: argparse.Namespace, paths: dict[str, Path], world_meta: dict, action_meta: dict, + contract: dict, sampling: dict, action_loss: str) -> dict: + values = { + "architecture": "bihub-joint-world-action-anchor-v2", + "image_contract": contract, + "dataset_manifest_sha256": sha256_file(paths["manifest"]), + "dataset_stats_sha256": sha256_file(paths["stats"]), + "validation_manifest_sha256": sha256_file(paths["validation_manifest"]), + "world_source_artifact": world_meta.get("artifact_identity_sha256"), + "world_checkpoint_fingerprint": checkpoint_fingerprint(paths["world"]), + "action_source_artifact": action_meta.get("artifact_identity_sha256"), + "action_checkpoint_fingerprint": checkpoint_fingerprint(paths["action"]), + "codec_checkpoint_sha256": sha256_file(paths["codec"]), + "qwen_root": str(paths["qwen"]), + "qwen_config_sha256": sha256_file(paths["qwen"] / "config.json"), + "online_cache_policy": "no_latent_no_qwen_hidden_no_predicted_future_cache", + "language_sampling": {"version": "eval-language-v1", "mix": parse_instruction_mix(args.instruction_mix)}, + "history_contract": "all_20hz_anchors;adapter_duplicate_initial;separate_tail_masks_v2", + "loss_weights": { + "world_flow": args.weight_world_flow, + "latent": args.weight_latent, + "pixel": args.weight_pixel, + "action": args.weight_action, + }, + "world_rollout_steps": args.world_rollout_steps, + "world_schedule": "linear_quadratic", + "sampling": sampling, + "action_loss": action_loss, + "optimization": {key: getattr(args, key) for key in ( + "seed", "steps", "per_device_batch", "gradient_accumulation", "shard_group_size", "lr_world", + "lr_action", "warmup_steps", "min_lr_ratio", "ema_decay", "rollout_grad_steps", + "state_noise_std", "validation_batches", + "world_activation_checkpoint_blocks", "action_activation_checkpoint_blocks", + "world_partial_checkpoint_block", "world_partial_checkpoint_components")}, + "world_size": dist.get_world_size() if dist.is_initialized() else 1, + "implementation_sha256": {name: sha256_file(Path(__file__).resolve().parents[1] / name) + for name in ("scripts/train_joint_world_action.py", "src/mira/data/joint_online.py", + "src/mira/data/joint_eval_language.py", + "src/mira/data/robotwin_rgb.py", "src/mira/joint/image_contract.py", + "src/mira/joint/training_utils.py", "src/mira/joint/model.py", "src/mira/world_v6/model.py", "src/mira/action_v6/model.py")}, + } + values["sha256"] = canonical_sha256(values) + return values + + +def _complete_checkpoints(root: Path) -> list[tuple[int, Path]]: + result = [] + for path in root.glob("joint-checkpoint-*"): + suffix = path.name.rsplit("-", 1)[-1] + if suffix.isdecimal() and (path / "trainer_state.json").is_file(): + result.append((int(suffix), path)) + return sorted(result) + + +def _save_checkpoint( + root: Path, + *, + completed: int, + model: torch.nn.Module, + optimizer: torch.optim.Optimizer, + scheduler: Any, + sampler: JointEvalAlignedSampler, + identity: dict, + config: dict, + metrics: dict, + ema: ParameterEMA | None = None, +) -> None: + rank = dist.get_rank() if dist.is_initialized() else 0 + final = root / f"joint-checkpoint-{completed}" + temporary = root / f".{final.name}.tmp" + if rank == 0: + if temporary.exists(): + shutil.rmtree(temporary) + temporary.mkdir(parents=True) + _barrier() + model_state, optimizer_state = get_state_dict(model, optimizer) + payload_state = {"model": model_state, "optimizer": optimizer_state} + if ema is not None: + payload_state["ema"] = ema.state_dict() + dcp.save(payload_state, checkpoint_id=temporary / "distributed") + torch.save( + { + "scheduler": scheduler.state_dict(), + "sampler": sampler.state_dict(), + "python_rng": random.getstate(), + "numpy_rng": np.random.get_state(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state() if torch.cuda.is_available() else None, + }, + temporary / f"rank-{rank:05d}.pth", + ) + _barrier() + if rank == 0: + payload = { + "format_version": 1, + "architecture": identity["architecture"], + "completed_steps": completed, + "next_step": completed, + "artifact_identity": identity, + "artifact_identity_sha256": canonical_sha256(identity), + "resolved_config": config, + "metrics": metrics, + "frozen_modules_excluded": ["codec", "qwen"], + "ema": {"saved": ema is not None, "decay": ema.decay if ema is not None else None}, + } + (temporary / "trainer_state.json").write_text( + json.dumps(payload, indent=2, default=str) + "\n", encoding="utf-8" + ) + if final.exists(): + shutil.rmtree(final) + os.replace(temporary, final) + best_file = root / "best_validation.json" + best_step = json.loads(best_file.read_text())["step"] if best_file.exists() else None + for old_step, old in _complete_checkpoints(root)[:-config["keep_last"]]: + if old != final and old_step != best_step and old_step % config["keep_every"] != 0: + shutil.rmtree(old) + _barrier() + + +def _resume( + checkpoint: Path, + *, + model: torch.nn.Module, + optimizer: torch.optim.Optimizer, + scheduler: Any, + sampler: JointEvalAlignedSampler, + identity: dict, + ema: ParameterEMA | None = None, +) -> int: + rank = dist.get_rank() if dist.is_initialized() else 0 + metadata = json.loads((checkpoint / "trainer_state.json").read_text(encoding="utf-8")) + if metadata.get("architecture") != identity["architecture"]: + raise ValueError("joint checkpoint architecture differs from this run") + require_resume_contract(metadata, identity["image_contract"]) + ema_saved = bool(metadata.get("ema", {}).get("saved")) + if rank == 0: + LOGGER.info("Continuing joint state from %s; the new run records its own data/code identity", checkpoint) + model_state, optimizer_state = get_state_dict(model, optimizer) + state = {"model": model_state, "optimizer": optimizer_state} + if ema is not None and ema_saved: + state["ema"] = ema.state_dict() + dcp.load(state, checkpoint_id=checkpoint / "distributed") + set_state_dict( + model, + optimizer, + model_state_dict=state["model"], + optim_state_dict=state["optimizer"], + ) + if ema is not None and not ema_saved: + ema.copy_from_model() + rank_state = torch.load( + checkpoint / f"rank-{rank:05d}.pth", map_location="cpu", weights_only=False + ) + scheduler.load_state_dict(rank_state["scheduler"]) + sampler.load_state_dict(rank_state["sampler"]) + random.setstate(rank_state["python_rng"]) + np.random.set_state(rank_state["numpy_rng"]) + torch.set_rng_state(rank_state["torch_rng"]) + if torch.cuda.is_available() and rank_state["cuda_rng"] is not None: + torch.cuda.set_rng_state(rank_state["cuda_rng"]) + _barrier() + return int(metadata["next_step"]) + + +def _init_joint_weights(checkpoint: Path, *, model: torch.nn.Module) -> None: + metadata = json.loads((checkpoint / "trainer_state.json").read_text(encoding="utf-8")) + if metadata.get("architecture") != "bihub-joint-world-action-anchor-v2": + raise ValueError("Expected a joint anchor-v2 checkpoint for weight initialization") + from torch.distributed.checkpoint.state_dict import get_model_state_dict, set_model_state_dict + model_state = get_model_state_dict(model) + dcp.load({"model": model_state}, checkpoint_id=checkpoint / "distributed") + set_model_state_dict(model, model_state) + LOGGER.info("Initialized joint weights from %s at step %s", checkpoint, metadata["completed_steps"]) + + +def _mean(value: torch.Tensor) -> float: + result = value.detach().float() + if isinstance(result, DTensor): + result = result.full_tensor() + if dist.is_initialized(): + dist.all_reduce(result) + result /= dist.get_world_size() + return float(result) + + +def _max(value: torch.Tensor) -> float: + result = value.detach().float().clone() + if dist.is_initialized(): + dist.all_reduce(result, op=dist.ReduceOp.MAX) + return float(result) + + +@torch.no_grad() +def _validation(model, codec, qwen, loader, *, args, device, state_mean, state_std, state_clip, codec_flip): + """Fixed samples/noise on every rank; restore RNG so validation cannot change training.""" + was_training = model.training + model.eval() + totals = {} + with torch.random.fork_rng(devices=[device.index]): + torch.manual_seed(args.seed + 900_001) + torch.cuda.manual_seed(args.seed + 900_001) + for index, (batch, metadata) in enumerate(loader): + if index >= args.validation_batches: + break + rgb = torch.stack([preprocess_qwen_rgb(sample[:, 19]) for sample in batch.video]) + flat_video = batch.video.flatten(0, 1).to(device) + codec_batch = _empty_codec_batch(flat_video.flip(2) if codec_flip else flat_video) + with torch.autocast("cuda", dtype=torch.bfloat16): + codec.preprocess_batch(codec_batch) + _, encoded = codec.encode(codec_batch.video, trim_video=False) + hidden, mask = qwen(rgb, [str(item["instruction"]) for item in metadata]) + latent = encoded.z.reshape(batch.video.shape[0], 3, 20, 32, 9, 12) + result = model( + z_context_raw=latent[:, :, :10], z_future_raw=latent[:, :, 10:], + state_history=((batch.state_history_raw.to(device) - state_mean) / state_std).clamp(-state_clip, state_clip), + history_valid=batch.history_valid.to(device), context_valid=batch.context_valid.to(device), + action_gt=batch.action_gt.to(device), action_valid=batch.action_valid.to(device), + future_valid=batch.future_valid.to(device), qwen_hidden=hidden, qwen_mask=mask, + rollout_noise=torch.randn_like(latent[:, :, 10:], dtype=torch.float32), + action_noise=torch.randn_like(batch.action_gt.to(device)), + rollout_steps=args.world_rollout_steps, + ) + for key in ("loss_action", "loss_world_flow", "loss_world_latent", "world_recovered_clean_mse"): + totals[key] = totals.get(key, 0) + result[key].float() + model.train(was_training) + # Each rank evaluates a distinct, fixed shard; scalar means are reduced across ranks. + return {key: _mean(value / args.validation_batches) for key, value in totals.items()} + + +def train(args: argparse.Namespace) -> None: + # Fail before allocating GPU models or overwriting run metadata. + official_image_decoder() + preflight_output = Path(args.output_dir or _defaults()["output"]).expanduser().resolve() + resume = args.resume_from_joint_checkpoint + if not resume and not args.no_auto_resume and not args.init_from_joint_checkpoint: + existing = _complete_checkpoints(preflight_output) + resume = existing[-1][1] if existing else None + contract = TRAINING_IMAGE_CONTRACTS[args.image_contract] + codec_flip = codec_needs_bgr(contract) + if resume: + require_resume_contract( + json.loads((Path(resume).expanduser() / "trainer_state.json").read_text()), contract) + settings = set_up_distributed() + rank, world_size = settings.rank, settings.world_size + import setproctitle + setproctitle.setproctitle(os.environ.get("JOINT_PROCESS_NAME") or f"syncnet_joint_r{rank}") + if not torch.cuda.is_available(): + raise RuntimeError("joint World + Action training requires CUDA") + device = torch.device("cuda", settings.device) + logging.basicConfig( + level=logging.INFO if rank == 0 else logging.WARNING, + format="%(asctime)s | %(levelname)s | %(message)s", + ) + defaults = _defaults() + dataset_root = Path(args.dataset_root).expanduser().resolve() + manifest_dir = Path(args.manifest_dir or dataset_root / "mira_manifests/joint_eval_language_v3").resolve() + output = Path(args.output_dir or defaults["output"]).expanduser().resolve() + output.mkdir(parents=True, exist_ok=True) + if args.no_auto_resume and _complete_checkpoints(output): + raise ValueError("--no-auto-resume requires a new output directory; refusing checkpoint overwrite") + paths = { + "world": Path(args.world_checkpoint or defaults["world"]).resolve(), + "action": Path(args.action_checkpoint or defaults["action"]).resolve(), + "codec": Path(args.codec_checkpoint or defaults["codec"]).resolve(), + "qwen": Path(args.qwen_root or defaults["qwen"]).resolve(), + "manifest": manifest_dir / "train.jsonl", + "validation_manifest": manifest_dir / "val.jsonl", + "stats": manifest_dir / "dataset_stats.json", + } + world_config, world_meta = _world_config(paths["world"]) + # Warm-start must retain pretrained normalization, not silently recompute it on a new split. + paths["stats"] = workspace_path(world_meta["resolved_config"]["artifacts"]["dataset_stats"]) + for name, path in paths.items(): + if not path.exists(): + raise FileNotFoundError(f"Required {name} path does not exist: {path}") + if not 1 <= args.world_rollout_steps <= 10: + raise ValueError("--world-rollout-steps must be in [1,10]") + if not 0 <= args.rollout_grad_steps <= args.world_rollout_steps: + raise ValueError("--rollout-grad-steps must be in [0, --world-rollout-steps]") + if not 0.0 <= args.min_lr_ratio <= 1.0 or not (args.ema_decay == 0.0 or 0.0 < args.ema_decay < 1.0): + raise ValueError("--min-lr-ratio must be in [0,1] and --ema-decay 0 or in (0,1)") + if not math.isfinite(args.state_noise_std) or args.state_noise_std < 0: + raise ValueError("--state-noise-std must be finite and non-negative") + weights = (args.weight_world_flow, args.weight_latent, args.weight_pixel, args.weight_action) + if any(not math.isfinite(w) or w < 0 for w in weights) or sum(weights) == 0: + raise ValueError("Loss weights must be finite, non-negative and not all zero") + if min(args.steps, args.per_device_batch, args.gradient_accumulation, args.save_every, + args.log_every, args.validate_every, args.validation_batches, args.keep_last, args.keep_every) < 1: + raise ValueError("steps, batch, accumulation and save interval must be positive") + + initialization_seed = args.seed + random.seed(initialization_seed) + np.random.seed(initialization_seed) + torch.manual_seed(initialization_seed) + torch.cuda.manual_seed(initialization_seed) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cuda.enable_flash_sdp(True) + torch.set_float32_matmul_precision("high") + + if sha256_file(paths["stats"]) != world_meta["artifact_identity"]["state_stats"]: + raise ValueError("State normalization differs from released World checkpoint") + world = WorldV6System(world_config) + load_online_source(world, paths["world"], expected_step=25_066) + action, action_meta = _build_action(paths["action"], args.action_loss_mode) + action_loss = action.loss_mode + action_stats_path = workspace_path(action_meta["resolved_config"]["data"]["action_stats"]) + if sha256_file(action_stats_path) != action_meta["resolved_config"]["data"]["action_stats_sha256"]: + raise ValueError("Action bounds/statistics differ from source checkpoint") + action_stats = json.loads(action_stats_path.read_text()) + trainable = JointWorldActionModel(world, action).to(device) + + # Activation checkpointing is essential because one optimizer step includes both the flow + # objective and a differentiable rollout through the 1B World model. + trainable.world.world_model.external_activation_checkpointing = True + world_block_count = len(trainable.world.world_model.blocks) + world_checkpoint_blocks = ( + world_block_count + if args.world_activation_checkpoint_blocks < 0 + else args.world_activation_checkpoint_blocks + ) + if not 0 <= world_checkpoint_blocks <= world_block_count: + raise ValueError( + f"--world-activation-checkpoint-blocks must be -1 or [0,{world_block_count}]" + ) + action_block_count = len(trainable.action.action_flow.blocks) + if not 0 <= args.action_activation_checkpoint_blocks <= action_block_count: + raise ValueError( + f"--action-activation-checkpoint-blocks must be [0,{action_block_count}]" + ) + for index, block in enumerate(trainable.world.world_model.blocks[:world_checkpoint_blocks]): + trainable.world.world_model.blocks[index] = checkpoint_wrapper( + block, checkpoint_impl=CheckpointImpl.NO_REENTRANT, preserve_rng_state=True + ) + partial_components = tuple( + item.strip() for item in args.world_partial_checkpoint_components.split(",") if item.strip() + ) + allowed_partial_components = { + "hub", + "hub.attention", + "temporal_attention", + "condition", + "condition.attention", + "condition.attention.gate_proj", + "condition.attention.out_proj", + "mlp", + } + unknown_partial_components = set(partial_components) - allowed_partial_components + if unknown_partial_components: + raise ValueError( + "Unknown --world-partial-checkpoint-components: " + + ",".join(sorted(unknown_partial_components)) + ) + if partial_components: + if not world_checkpoint_blocks <= args.world_partial_checkpoint_block < world_block_count: + raise ValueError( + "--world-partial-checkpoint-block must select a World block that is not already " + "fully checkpointed" + ) + partial_block = trainable.world.world_model.blocks[args.world_partial_checkpoint_block] + for component_name in partial_components: + parent: torch.nn.Module = partial_block + path_parts = component_name.split(".") + for path_part in path_parts[:-1]: + parent = getattr(parent, path_part) + attribute_name = path_parts[-1] + component = getattr(parent, attribute_name) + if component is None: + raise ValueError( + f"World block {args.world_partial_checkpoint_block} has no {component_name}" + ) + setattr( + parent, + attribute_name, + checkpoint_wrapper( + component, + checkpoint_impl=CheckpointImpl.NO_REENTRANT, + preserve_rng_state=True, + ), + ) + elif args.world_partial_checkpoint_block != -1: + raise ValueError( + "--world-partial-checkpoint-block requires --world-partial-checkpoint-components" + ) + for index in range(args.action_activation_checkpoint_blocks): + trainable.action.action_flow.blocks[index] = checkpoint_wrapper( + trainable.action.action_flow.blocks[index], + checkpoint_impl=CheckpointImpl.NO_REENTRANT, + preserve_rng_state=True, + ) + if world_size > 1: + if args.shard_group_size < 0 or (args.shard_group_size and world_size % args.shard_group_size): + raise ValueError("--shard-group-size must divide the distributed world size") + shard_mesh = ( + init_device_mesh( + "cuda", (world_size // args.shard_group_size, args.shard_group_size), + mesh_dim_names=("replicate", "shard"), + ) + if args.shard_group_size and args.shard_group_size < world_size + else None + ) + policy = MixedPrecisionPolicy( + param_dtype=torch.bfloat16, + reduce_dtype=torch.float32, + output_dtype=torch.bfloat16, + ) + for block in trainable.world.world_model.blocks: + fully_shard(block, mesh=shard_mesh, mp_policy=policy, reshard_after_forward=True) + for layer in trainable.action.transition_conditioner.qformer.layers: + fully_shard(layer, mesh=shard_mesh, mp_policy=policy, reshard_after_forward=True) + fully_shard( + trainable.action.transition_conditioner.hub, + mesh=shard_mesh, + mp_policy=policy, + reshard_after_forward=True, + ) + for block in trainable.action.action_flow.blocks: + fully_shard(block, mesh=shard_mesh, mp_policy=policy, reshard_after_forward=True) + fully_shard(trainable, mesh=shard_mesh, mp_policy=policy, reshard_after_forward=True) + + world_parameters, action_parameters = [], [] + for name, parameter in trainable.named_parameters(): + if not parameter.requires_grad: + continue + (action_parameters if ".action." in f".{name}." else world_parameters).append(parameter) + optimizer = torch.optim.AdamW( + [ + {"params": world_parameters, "lr": args.lr_world, "initial_lr": args.lr_world}, + {"params": action_parameters, "lr": args.lr_action, "initial_lr": args.lr_action}, + ], + betas=(0.9, 0.95), + eps=1.0e-8, + weight_decay=0.01, + ) + + def lr_scale(step: int) -> float: + return scheduled_lr_scale(step, warmup_steps=args.warmup_steps, total_steps=args.steps, + min_ratio=args.min_lr_ratio) + + scheduler = torch.optim.lr_scheduler.LambdaLR( + optimizer, [lr_scale for _ in optimizer.param_groups] + ) + + # Codec encoder and Qwen execute under no_grad. Decoder weights also stay frozen, but its + # forward is differentiable with respect to predicted latents for RGB supervision. + codec = VideoCodec.load_from_checkpoint(paths["codec"], device=device) + codec.requires_grad_(False).eval() + codec.decoder.config.activation_checkpointing = True + codec.decoder.train(True) + qwen_identity = _prepare_qwen_identity(output, paths["qwen"], rank, contract) + qwen = FrozenQwenCurrentLanes(paths["qwen"], qwen_identity, device=device).eval() + qwen.assert_frozen() + if any(parameter.requires_grad for parameter in codec.parameters()): + raise RuntimeError("Codec must remain frozen during joint full fine-tuning") + frozen_joint = [name for name, parameter in trainable.named_parameters() if not parameter.requires_grad] + if frozen_joint: + raise RuntimeError( + "Only Qwen3 and codec may be frozen; joint model still has frozen parameters: " + + ", ".join(frozen_joint[:20]) + ) + optimizer_parameter_ids = { + id(parameter) for group in optimizer.param_groups for parameter in group["params"] + } + trainable_parameter_ids = {id(parameter) for parameter in trainable.parameters()} + if optimizer_parameter_ids != trainable_parameter_ids: + raise RuntimeError("Optimizer parameters do not exactly match the full joint trainable set") + parameter_summary = { + "joint_total": sum(parameter.numel() for parameter in trainable.parameters()), + "joint_trainable": sum( + parameter.numel() for parameter in trainable.parameters() if parameter.requires_grad + ), + "world_trainable": sum( + parameter.numel() for parameter in trainable.world.parameters() if parameter.requires_grad + ), + "action_trainable": sum( + parameter.numel() for parameter in trainable.action.parameters() if parameter.requires_grad + ), + "codec_frozen": sum(parameter.numel() for parameter in codec.parameters()), + "qwen3_frozen": sum(parameter.numel() for parameter in qwen.model.parameters()), + "optimizer_parameters": sum( + parameter.numel() for group in optimizer.param_groups for parameter in group["params"] + ), + } + if rank == 0: + LOGGER.info("trainability=%s", json.dumps(parameter_summary, sort_keys=True)) + + stats = json.loads(paths["stats"].read_text(encoding="utf-8")) + state_mean = torch.tensor(stats["mean"], device=device).reshape(1, 1, 2, 7) + state_std = torch.tensor(stats["std"], device=device).clamp_min( + float(stats.get("normalization_std_floor", 1.0e-2)) + ).reshape(1, 1, 2, 7) + state_clip = float(stats.get("normalization_clip", 5.0)) + + instruction_mix = parse_instruction_mix(args.instruction_mix) + validation_mix = "seen=1,full_goal=0" + dataset = JointOnlineRoboTwinDataset( + dataset_root=dataset_root, manifest=paths["manifest"], instruction_mix=args.instruction_mix + ) + validation_dataset = JointOnlineRoboTwinDataset( + dataset_root=dataset_root, manifest=paths["validation_manifest"], instruction_mix=validation_mix + ) + if {row["episode_sha256"] for row in dataset.source_rows} & { + row["episode_sha256"] for row in validation_dataset.source_rows + }: + raise ValueError("Episode leakage between training and validation manifests") + validation_indices = [] + proposals = JointEvalAlignedSampler(validation_dataset, seed=args.seed + 800_001) + validation_per_rank = args.validation_batches * args.per_device_batch + validation_total = validation_per_rank * world_size + for index, proposal in enumerate(itertools.islice(iter(proposals), validation_total)): + if index // validation_per_rank != rank: + continue + episode, _ = validation_dataset._locate(proposal) + last = validation_dataset.base_counts[episode] - 1 + anchor = (0, min(8, last), min(16, last), last // 2, last)[index % 5] + validation_indices.append(validation_dataset.anchor_index(episode, anchor)) + validation_loader = DataLoader( + validation_dataset, batch_size=args.per_device_batch, + sampler=validation_indices, + num_workers=0, collate_fn=collate_joint_online, + ) + task_weights, task_weights_sha256 = ( + load_task_weights(args.task_weights, dataset.tasks) if args.task_weights else (None, None) + ) + sampling = {"task_weights": task_weights, "task_weights_sha256": task_weights_sha256, + "clean_probability": args.clean_probability} + sampler = JointEvalAlignedSampler( + dataset, seed=args.seed, rank=rank, world_size=world_size, + emit_draw_index=True, clean_probability=args.clean_probability, task_weights=task_weights, + ) + loader = DataLoader( + dataset, + batch_size=args.per_device_batch, + sampler=sampler, + num_workers=args.num_workers, + prefetch_factor=2 if args.num_workers else None, + persistent_workers=args.num_workers > 0, + pin_memory=True, + collate_fn=collate_joint_online, + ) + runtime_seed = args.seed + rank + random.seed(runtime_seed) + np.random.seed(runtime_seed) + torch.manual_seed(runtime_seed) + torch.cuda.manual_seed(runtime_seed) + identity = _identity(args, paths, world_meta, action_meta, contract, sampling, action_loss) + config = {**vars(args), "resolved_paths": {key: str(value) for key, value in paths.items()}, + "image_contract": contract, "sampling": sampling, + "world_model": world_config.model_dump(mode="json"), + "action_loss": action_loss, + "action_inference": action_meta["resolved_config"]["action"], + "state_stats": stats, "action_stats": action_stats, + "parameter_summary": parameter_summary, + "frozen_boundary": { + "frozen": ["qwen3_vl", "lingbot_codec"], + "trainable": ["world_all", "current_resampler", "state_encoder", "action_all"], + }, + "activation_checkpointing": { + "world_blocks": world_checkpoint_blocks, + "world_blocks_total": world_block_count, + "world_partial_block": args.world_partial_checkpoint_block, + "world_partial_components": partial_components, + "action_blocks": args.action_activation_checkpoint_blocks, + "action_blocks_total": action_block_count, + }, + "distributed_sharding": { + "mode": "hybrid_2d" if world_size > args.shard_group_size > 0 else "full_1d", + "shard_group_size": args.shard_group_size or world_size, + "replica_groups": world_size // args.shard_group_size if args.shard_group_size else 1, + }} + if rank == 0: + (output / "resolved_config.json").write_text( + json.dumps(config, indent=2, default=str) + "\n", encoding="utf-8" + ) + tracker = SwanLabTracker.disabled() + if rank == 0: + tracker = SwanLabTracker.initialize( + { + "mode": args.swanlab_mode, + "project": args.swanlab_project, + "experiment_name": args.swanlab_experiment_name, + "token_file": args.swanlab_token_file, + "job_type": "joint-world-action-training", + "tags": ["RoboTwin2.0", "joint", "anchor-v2", f"{world_size}gpu"], + "resume": "allow", + "capture_console": "stderr", + "upload_hardware": True, + "upload_runtime": True, + "upload_requirements": False, + "upload_git": False, + "system_monitor": True, + "public": False, + }, + output_dir=output, + run_config=config, + ) + _barrier() + ema = ParameterEMA(trainable, args.ema_decay) if args.ema_decay > 0 else None + start = 0 + if args.resume_from_joint_checkpoint and args.init_from_joint_checkpoint: + raise ValueError("Choose either full continuation or weight-only initialization") + if args.init_from_joint_checkpoint: + if _complete_checkpoints(output): + raise ValueError("Weight initialization requires an empty output checkpoint set") + _init_joint_weights(Path(args.init_from_joint_checkpoint).expanduser().resolve(), model=trainable) + if ema is not None: + ema.copy_from_model() + elif args.resume_from_joint_checkpoint: + if _complete_checkpoints(output): + raise ValueError("Explicit checkpoint continuation requires an empty output checkpoint set") + start = _resume( + Path(args.resume_from_joint_checkpoint).expanduser().resolve(), + model=trainable, optimizer=optimizer, scheduler=scheduler, + sampler=sampler, identity=identity, ema=ema, + ) + elif not args.no_auto_resume: + checkpoints = _complete_checkpoints(output) + if checkpoints: + start = _resume( + checkpoints[-1][1], + model=trainable, + optimizer=optimizer, + scheduler=scheduler, + sampler=sampler, + identity=identity, + ema=ema, + ) + total = min(args.steps, args.max_steps) if args.max_steps is not None else args.steps + iterator = iter(loader) + if start >= total: + raise RuntimeError(f"output already completed {start} steps; requested {total}") + if args.max_runtime_seconds < 0: + raise ValueError("--max-runtime-seconds must be non-negative") + run_started = torch.tensor(int(time.time()), dtype=torch.long, device=device) + if dist.is_initialized(): + dist.broadcast(run_started, src=0) + runtime_deadline = int(run_started.item()) + args.max_runtime_seconds if args.max_runtime_seconds else None + stop_requested = False + + def request_stop(_signum: int, _frame: Any) -> None: + nonlocal stop_requested + stop_requested = True + + signal.signal(signal.SIGINT, request_stop) + signal.signal(signal.SIGTERM, request_stop) + metrics_path = output / "metrics.jsonl" + trainable.train() + torch.cuda.reset_peak_memory_stats(device) + torch.cuda.synchronize(device) + interval_started = time.perf_counter() + interval_steps = 0 + last_metrics: dict[str, float] = {} + for step in range(start, total): + interval_steps += 1 + optimizer.zero_grad(set_to_none=True) + totals: dict[str, torch.Tensor] = {} + history_counts = {value: 0 for value in range(1, 11)} + instruction_counts = {name: 0 for name in ("seen", "full_goal")} + for micro in range(args.gradient_accumulation): + batch, metadata = next(iterator) + for item in metadata: + history_counts[int(item["history_length"])] += 1 + instruction_counts[str(item["instruction_source"])] += 1 + # Preserve raw uint8 for Qwen; codec performs its own aspect-preserving preprocessing. + current_rgb = torch.stack( + [preprocess_qwen_rgb(sample[:, 19]) for sample in batch.video] + ) + flat_video = batch.video.flatten(0, 1).to(device, non_blocking=True) + # Split contract: reversed channels for the codec branch only; Qwen keeps RGB above. + codec_batch = _empty_codec_batch(flat_video.flip(2) if codec_flip else flat_video) + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16): + codec.preprocess_batch(codec_batch) + normalized_video, encoded = codec.encode(codec_batch.video, trim_video=False) + qwen_hidden, qwen_mask = qwen( + current_rgb, + [str(item["instruction"]) for item in metadata], + ) + batch_size = batch.video.shape[0] + latent = encoded.z.reshape(batch_size, 3, 20, 32, 9, 12) + z_context, z_future = latent[:, :, :10], latent[:, :, 10:] + gt_future_rgb = normalized_video.reshape( + batch_size, 3, 40, 3, 288, 384 + )[:, :, 20:] + state_raw = batch.state_history_raw.to(device, non_blocking=True) + state = ((state_raw - state_mean) / state_std).clamp(-state_clip, state_clip) + action_gt = batch.action_gt.to(device, non_blocking=True) + history_valid = batch.history_valid.to(device, non_blocking=True) + if args.state_noise_std > 0: + noise = torch.randn_like(state) * args.state_noise_std + state = (state + noise * history_valid[:, :, None, None]).clamp(-state_clip, state_clip) + context_valid = batch.context_valid.to(device, non_blocking=True) + action_valid = batch.action_valid.to(device, non_blocking=True) + rollout_noise = torch.randn_like(z_future, dtype=torch.float32) + action_noise = torch.randn_like(action_gt, dtype=torch.float32) + + last_backward = micro == args.gradient_accumulation - 1 + if world_size > 1: + trainable.set_requires_gradient_sync(last_backward) + trainable.set_is_last_backward(last_backward) + with torch.autocast("cuda", dtype=torch.bfloat16): + result = trainable( + z_context_raw=z_context, + z_future_raw=z_future, + state_history=state, + history_valid=history_valid, + context_valid=context_valid, + action_gt=action_gt, + action_valid=action_valid, + future_valid=batch.future_valid.to(device), + qwen_hidden=qwen_hidden, + qwen_mask=qwen_mask, + rollout_noise=rollout_noise, + action_noise=action_noise, + rollout_steps=args.world_rollout_steps, + rollout_grad_steps=args.rollout_grad_steps or None, + ) + # The codec decoder is temporally causal. Decode context + prediction together, + # exactly like deployment visualization, then supervise only the future frames. + loss_pixel = result["loss_action"].new_zeros(()) + if args.weight_pixel > 0: + predicted_rgb = codec.decoder( + torch.cat([z_context, result["predicted_future_raw"]], dim=2).flatten(0, 1) + ).reshape(batch_size, 3, 40, 3, 288, 384)[:, :, 20:] + pixel_error = torch.sqrt((predicted_rgb.float() - gt_future_rgb.float()).square() + 1.0e-6) + pixel_mask = batch.future_rgb_valid.to(device)[:, None, :, None, None, None].expand_as(pixel_error) + loss_pixel = (pixel_error * pixel_mask).sum() / pixel_mask.sum().clamp_min(1) + loss = ( + args.weight_world_flow * result["loss_world_flow"] + + args.weight_latent * result["loss_world_latent"] + + args.weight_pixel * loss_pixel + + args.weight_action * result["loss_action"] + ) / args.gradient_accumulation + if not bool(torch.isfinite(loss)): + raise FloatingPointError("joint objective became non-finite") + loss.backward() + values = { + "loss_total": loss.detach() * args.gradient_accumulation, + "loss_world_flow": result["loss_world_flow"].detach(), + "loss_world_latent": result["loss_world_latent"].detach(), + "loss_pixel": loss_pixel.detach(), + "loss_action": result["loss_action"].detach(), + "world_recovered_clean_mse": result["world_recovered_clean_mse"].detach(), + } + for name, value in values.items(): + totals[name] = totals.get(name, torch.zeros_like(value)) + value / args.gradient_accumulation + sampler.mark_consumed(args.per_device_batch) + + grad_norm = torch.nn.utils.clip_grad_norm_(trainable.parameters(), 1.0, error_if_nonfinite=True) + optimizer.step() + scheduler.step() + completed = step + 1 + ema_decay = ema.update(completed) if ema is not None else None + stop_tensor = torch.tensor( + int(stop_requested or (runtime_deadline is not None and time.time() >= runtime_deadline)), + device=device, + ) + if dist.is_initialized(): + dist.all_reduce(stop_tensor, op=dist.ReduceOp.MAX) + stop_requested = bool(stop_tensor.item()) + if completed - start <= 5 or completed % args.log_every == 0 or completed == total or stop_requested: + torch.cuda.synchronize(device) + interval_seconds = max(time.perf_counter() - interval_started, 1.0e-6) + step_seconds = interval_seconds / interval_steps + last_metrics = {name: _mean(value) for name, value in totals.items()} + last_metrics.update( + { + "grad_norm": _mean(torch.as_tensor(grad_norm, device=device)), + "lr_world": optimizer.param_groups[0]["lr"], + "lr_action": optimizer.param_groups[1]["lr"], + **({"ema_decay": ema_decay} if ema_decay is not None else {}), + "step_seconds": step_seconds, + "global_samples_per_second": ( + world_size + * args.per_device_batch + * args.gradient_accumulation + * interval_steps + / interval_seconds + ), + "peak_memory_gib_max_rank": _max(torch.tensor(torch.cuda.max_memory_allocated(device) / 2**30, device=device)), + "peak_reserved_gib_max_rank": _max(torch.tensor(torch.cuda.max_memory_reserved(device) / 2**30, device=device)), + **{f"history_h{key}": _mean(torch.tensor(value, device=device)) * world_size for key, value in history_counts.items()}, + **{f"instruction_{key}_samples": _mean(torch.tensor(value, device=device)) * world_size for key, value in instruction_counts.items()}, + } + ) + if rank == 0: + row = {"step": completed, **last_metrics} + with metrics_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(row, sort_keys=True) + "\n") + LOGGER.info("%s", json.dumps(row, sort_keys=True)) + try: + tracker.log(last_metrics, step=completed) + except Exception: # Cloud telemetry must never invalidate a training step. + LOGGER.warning("SwanLab scalar upload failed; local JSONL remains authoritative", exc_info=True) + interval_started = time.perf_counter() + interval_steps = 0 + is_best = False + if not args.probe_only and (completed % args.validate_every == 0 or completed == total): + validation = _validation(trainable, codec, qwen, validation_loader, + args=args, device=device, state_mean=state_mean, state_std=state_std, state_clip=state_clip, + codec_flip=codec_flip) + if not all(math.isfinite(value) for value in validation.values()): + raise FloatingPointError("Validation is non-finite") + best_path = output / "best_validation.json" + if rank == 0: + previous = json.loads(best_path.read_text()) if best_path.exists() else None + is_best = previous is None or validation["loss_action"] < previous["metrics"]["loss_action"] + best_decision = torch.tensor(int(is_best), device=device) + if dist.is_initialized(): + dist.broadcast(best_decision, src=0) + is_best = bool(best_decision.item()) + last_metrics.update({f"val/{key}": value for key, value in validation.items()}) + if rank == 0: + with (output / "validation.jsonl").open("a") as handle: + handle.write(json.dumps({"step": completed, **validation}) + "\n") + LOGGER.info("validation step=%s %s", completed, validation) + try: + tracker.log({f"val/{key}": value for key, value in validation.items()}, step=completed) + except Exception: + LOGGER.warning("SwanLab validation upload failed; local JSONL remains authoritative", exc_info=True) + _barrier() + should_save = (not args.probe_only) and ( + is_best or completed % args.save_every == 0 or completed == total or stop_requested + ) + if should_save: + _save_checkpoint( + output, + completed=completed, + model=trainable, + optimizer=optimizer, + scheduler=scheduler, + sampler=sampler, + identity=identity, + config=config, + metrics=last_metrics, + ema=ema, + ) + if is_best and rank == 0: + temporary = best_path.with_suffix(".tmp") + temporary.write_text(json.dumps({"step": completed, "criterion": "fixed_seed_action_FM_not_closed_loop", "metrics": validation}, indent=2) + "\n") + temporary.replace(best_path) + _barrier() + if stop_requested: + break + qwen.assert_frozen() + if any(parameter.grad is not None for parameter in codec.parameters()): + raise RuntimeError("frozen codec accumulated parameter gradients") + if rank == 0: + if args.probe_only: + (output / "probe_summary.json").write_text( + json.dumps( + { + "status": "passed", + "completed_steps": total, + "parameter_summary": parameter_summary, + "last_metrics": last_metrics, + "checkpoint_written": False, + }, + indent=2, + sort_keys=True, + ) + + "\n", + encoding="utf-8", + ) + try: + tracker.finish() + except Exception: + LOGGER.warning("SwanLab finish failed after training completed", exc_info=True) + if dist.is_initialized(): + dist.destroy_process_group() + + +def main() -> None: + args = _parser().parse_args() + train(args) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/scripts/train_robotwin_codec.sh b/release-20261107/source/workspace_joint/mira/scripts/train_robotwin_codec.sh new file mode 100644 index 0000000000000000000000000000000000000000..b52fa9eb0d39ba1713fdf162c53b41c146bb1b89 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/train_robotwin_codec.sh @@ -0,0 +1,242 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Give the shell a narrow, recognizable name while it validates data or waits for GPUs. The +# distributed launcher replaces this with syncnet_codec_launch, and workers use syncnet_codec. +if [[ -w "/proc/$$/comm" ]]; then + printf '%s' "syncnet_wait" > "/proc/$$/comm" +fi + +MIRA_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +WORKSPACE_ROOT="$(cd "${MIRA_ROOT}/.." && pwd)" + +CONDA_ROOT="${CONDA_ROOT:-/private/software/conda}" +CONDA_ENV_NAME="${CONDA_ENV_NAME:-mira}" +DATASET_ROOT="${ROBOTWIN_DATASET_ROOT:-${WORKSPACE_ROOT}/datasets/RoboTwin2.0}" +MANIFEST_DIR="${ROBOTWIN_MANIFEST_DIR:-${DATASET_ROOT}/mira_manifests}" +COMPAT_MANIFEST_DIR="${ROBOTWIN_COMPAT_MANIFEST_DIR:-${MANIFEST_DIR}/codec_40f_30to20}" +LINGBOT_MODEL_DIR="${LINGBOT_VISION_MODEL_DIR:-${WORKSPACE_ROOT}/models/lingbot-vision-vit-large}" +OUTPUT_DIR="${OUTPUT_DIR:-${WORKSPACE_ROOT}/outputs/mira_robotwin_codec}" + +STEPS="${STEPS:-250001}" +BATCH_SIZE="${BATCH_SIZE:-1}" +NUM_WORKERS="${NUM_WORKERS:-4}" +ARCHIVE_MIX_SIZE="${ARCHIVE_MIX_SIZE:-32}" +VAL_SAMPLES="${VAL_SAMPLES:-96}" +VIS_EVERY="${VIS_EVERY:-1%}" +CHECKPOINT_EVERY="${CHECKPOINT_EVERY:-5%}" +LOG_EVERY="${LOG_EVERY:-100}" +RUN_COMPILE="${RUN_COMPILE:-false}" +WANDB_MODE="${WANDB_MODE:-disabled}" +SWANLAB_MODE="${SWANLAB_MODE:-online}" +SWANLAB_PROJECT="${SWANLAB_PROJECT:-Multi_WAM}" +SWANLAB_TOKEN_FILE="${SWANLAB_TOKEN_FILE:-${WORKSPACE_ROOT}/z_oranger/token.txt}" +RUN_NAME="${RUN_NAME:-lingbot-robotwin-codec}" +DRY_RUN="${DRY_RUN:-0}" +REBUILD_MANIFEST="${REBUILD_MANIFEST:-0}" +REBUILD_COMPAT_MANIFEST="${REBUILD_COMPAT_MANIFEST:-0}" +CLIP_AUDIT_WORKERS="${CLIP_AUDIT_WORKERS:-8}" +CLIP_AUDIT_PROBES="${CLIP_AUDIT_PROBES:-3}" +REQUIRE_IDLE_GPUS="${REQUIRE_IDLE_GPUS:-1}" +WAIT_FOR_IDLE_GPUS="${WAIT_FOR_IDLE_GPUS:-0}" +GPU_IDLE_MAX_MEMORY_MIB="${GPU_IDLE_MAX_MEMORY_MIB:-4096}" +GPU_IDLE_MAX_UTILIZATION="${GPU_IDLE_MAX_UTILIZATION:-10}" +GPU_IDLE_STABLE_CHECKS="${GPU_IDLE_STABLE_CHECKS:-1}" +GPU_IDLE_POLL_SECONDS="${GPU_IDLE_POLL_SECONDS:-30}" + +if [[ ! -f "${CONDA_ROOT}/etc/profile.d/conda.sh" ]]; then + echo "Conda initialization script not found: ${CONDA_ROOT}/etc/profile.d/conda.sh" >&2 + exit 1 +fi +# shellcheck disable=SC1091 +source "${CONDA_ROOT}/etc/profile.d/conda.sh" +conda activate "${CONDA_ENV_NAME}" + +# All dependency/model/data access is local. Prevent accidental proxy or Hub fallback. +unset HTTP_PROXY HTTPS_PROXY ALL_PROXY http_proxy https_proxy all_proxy +export HF_HUB_OFFLINE=1 +export TRANSFORMERS_OFFLINE=1 +export PYTHONUNBUFFERED=1 +export TORCH_NCCL_ASYNC_ERROR_HANDLING=1 +export OMP_NUM_THREADS="${OMP_NUM_THREADS:-4}" +export ROBOTWIN_DATASET_ROOT="${DATASET_ROOT}" +export LINGBOT_VISION_MODEL_DIR="${LINGBOT_MODEL_DIR}" +export MIRA_PROCESS_NAME=syncnet_codec +export MIRA_HYDRA_RUN_DIR="${OUTPUT_DIR}" +export SWANLAB_TOKEN_FILE + +cd "${MIRA_ROOT}" + +if [[ ! -d "${DATASET_ROOT}/dataset" ]]; then + echo "RoboTwin dataset directory not found: ${DATASET_ROOT}/dataset" >&2 + exit 1 +fi +if [[ ! -f "${LINGBOT_MODEL_DIR}/model.pt" ]]; then + echo "LingBot model not found: ${LINGBOT_MODEL_DIR}/model.pt" >&2 + exit 1 +fi +if [[ "${SWANLAB_MODE}" == "online" && ! -s "${SWANLAB_TOKEN_FILE}" ]]; then + echo "SwanLab token file is missing or empty: ${SWANLAB_TOKEN_FILE}" >&2 + exit 1 +fi + +if [[ "${REBUILD_MANIFEST}" == "1" || ! -s "${MANIFEST_DIR}/train.jsonl" || ! -s "${MANIFEST_DIR}/val.jsonl" ]]; then + echo "Building RoboTwin manifests in ${MANIFEST_DIR}" + python scripts/build_robotwin_manifest.py \ + --dataset-root "${DATASET_ROOT}" \ + --output-dir "${MANIFEST_DIR}" \ + --val-fraction 0.02 \ + --seed 2026 +fi + +FILTER_ARGS=( + --dataset-root "${DATASET_ROOT}" + --train-manifest "${MANIFEST_DIR}/train.jsonl" + --val-manifest "${MANIFEST_DIR}/val.jsonl" + --output-dir "${COMPAT_MANIFEST_DIR}" + --clip-len 40 + --source-fps 30 + --target-fps 20 + --probes-per-archive "${CLIP_AUDIT_PROBES}" + --workers "${CLIP_AUDIT_WORKERS}" +) +if [[ "${REBUILD_COMPAT_MANIFEST}" == "1" ]]; then + FILTER_ARGS+=(--force) +fi +echo "Checking clip-compatible RoboTwin manifests in ${COMPAT_MANIFEST_DIR}" +python scripts/filter_robotwin_manifests.py "${FILTER_ARGS[@]}" + +if [[ -n "${CUDA_VISIBLE_DEVICES:-}" ]]; then + IFS=',' read -r -a _visible_devices <<< "${CUDA_VISIBLE_DEVICES}" + DEFAULT_NPROC="${#_visible_devices[@]}" +else + if command -v nvidia-smi >/dev/null 2>&1; then + DEFAULT_NPROC="$(nvidia-smi -L 2>/dev/null | wc -l || true)" + else + DEFAULT_NPROC=0 + fi +fi +NPROC_PER_NODE="${NPROC_PER_NODE:-${DEFAULT_NPROC}}" +if [[ "${NPROC_PER_NODE}" -lt 1 ]]; then + if [[ "${DRY_RUN}" == "1" ]]; then + NPROC_PER_NODE=1 + else + echo "No visible GPU found. Set CUDA_VISIBLE_DEVICES/NPROC_PER_NODE when a GPU is available." >&2 + exit 1 + fi +fi + +HYDRA_ARGS=( + "dataset=robotwin2" + "dataset.root=${DATASET_ROOT}" + "dataset.manifest_dir=${MANIFEST_DIR}" + "dataset.train_manifest=${COMPAT_MANIFEST_DIR}/train.jsonl" + "dataset.val_manifest=${COMPAT_MANIFEST_DIR}/val.jsonl" + "model.architecture.config.encoder.backbone_weights_path=${LINGBOT_MODEL_DIR}" + "run.output_dir=${OUTPUT_DIR}" + "run.steps=${STEPS}" + "run.batch_size=${BATCH_SIZE}" + "run.compile=${RUN_COMPILE}" + "run.checkpoint_every=${CHECKPOINT_EVERY}" + "run.log_every=${LOG_EVERY}" + "dataloader.num_workers=${NUM_WORKERS}" + "dataloader.archive_mix_size=${ARCHIVE_MIX_SIZE}" + "validation.val_n_samples=${VAL_SAMPLES}" + "visualization.every=${VIS_EVERY}" + "wandb.mode=${WANDB_MODE}" + "wandb.name=${RUN_NAME}" + "swanlab.mode=${SWANLAB_MODE}" + "swanlab.project=${SWANLAB_PROJECT}" + "swanlab.experiment_name=${RUN_NAME}" + "swanlab.token_file=${SWANLAB_TOKEN_FILE}" +) +HYDRA_ARGS+=("$@") + +if [[ "${NPROC_PER_NODE}" -eq 1 ]]; then + COMMAND=(python scripts/train_codec.py "${HYDRA_ARGS[@]}") +else + COMMAND=( + python + scripts/syncnet_torchrun.py + --standalone + --nproc_per_node="${NPROC_PER_NODE}" + scripts/train_codec.py + "${HYDRA_ARGS[@]}" + ) +fi + +echo "RoboTwin root : ${DATASET_ROOT}" +echo "Manifest dir : ${MANIFEST_DIR}" +echo "Clip manifests: ${COMPAT_MANIFEST_DIR}" +echo "LingBot model : ${LINGBOT_MODEL_DIR}" +echo "Output dir : ${OUTPUT_DIR}" +echo "GPU workers : ${NPROC_PER_NODE}" +echo "SwanLab : ${SWANLAB_MODE} / ${SWANLAB_PROJECT} / ${RUN_NAME}" +printf "Launch command:" +printf " %q" "${COMMAND[@]}" +printf "\n" + +if [[ "${DRY_RUN}" == "1" ]]; then + exit 0 +fi + +if [[ "${REQUIRE_IDLE_GPUS}" == "1" ]]; then + if [[ -n "${CUDA_VISIBLE_DEVICES:-}" ]]; then + IFS=',' read -r -a _launch_gpu_ids <<< "${CUDA_VISIBLE_DEVICES}" + else + mapfile -t _launch_gpu_ids < <(seq 0 $((NPROC_PER_NODE - 1))) + fi + if [[ "${#_launch_gpu_ids[@]}" -ne "${NPROC_PER_NODE}" ]]; then + echo "Expected ${NPROC_PER_NODE} launch GPU IDs, got ${#_launch_gpu_ids[@]}" >&2 + exit 1 + fi + + _idle_streak=0 + while true; do + _busy_report="" + for _gpu_id in "${_launch_gpu_ids[@]}"; do + _gpu_stats="$( + nvidia-smi \ + --id="${_gpu_id}" \ + --query-gpu=memory.used,utilization.gpu \ + --format=csv,noheader,nounits + )" + IFS=',' read -r _memory_mib _utilization <<< "${_gpu_stats}" + _memory_mib="${_memory_mib//[[:space:]]/}" + _utilization="${_utilization//[[:space:]]/}" + if (( + _memory_mib > GPU_IDLE_MAX_MEMORY_MIB + || _utilization > GPU_IDLE_MAX_UTILIZATION + )); then + _busy_report+=" GPU${_gpu_id}=${_memory_mib}MiB/${_utilization}%" + fi + done + + if [[ -z "${_busy_report}" ]]; then + _idle_streak=$((_idle_streak + 1)) + if (( _idle_streak >= GPU_IDLE_STABLE_CHECKS )); then + echo "GPU idle gate passed for ${NPROC_PER_NODE} GPU(s)." + break + fi + echo "GPU idle check ${_idle_streak}/${GPU_IDLE_STABLE_CHECKS} passed; confirming stability." + else + _idle_streak=0 + if [[ "${WAIT_FOR_IDLE_GPUS}" != "1" ]]; then + echo "Refusing to co-schedule on busy GPU(s):${_busy_report}" >&2 + echo "Set WAIT_FOR_IDLE_GPUS=1 to queue, or REQUIRE_IDLE_GPUS=0 to override explicitly." >&2 + exit 1 + fi + echo "Waiting for idle GPU(s):${_busy_report}" + fi + sleep "${GPU_IDLE_POLL_SECONDS}" + done +fi + +if [[ "${NPROC_PER_NODE}" -eq 1 ]]; then + exec "${COMMAND[@]}" +else + export MIRA_LAUNCHER_PROCESS_NAME=syncnet_codec_launch + # Do not use `exec -a` here: Python derives sys.executable from argv[0], and torchrun needs the + # real interpreter path to spawn workers. syncnet_torchrun.py sets both comm and full title. + exec "${COMMAND[@]}" +fi diff --git a/release-20261107/source/workspace_joint/mira/scripts/train_world_model.py b/release-20261107/source/workspace_joint/mira/scripts/train_world_model.py new file mode 100644 index 0000000000000000000000000000000000000000..58689de48397a0c59c6af22010b82826bedae22e --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/train_world_model.py @@ -0,0 +1,465 @@ +"""Train the latent world model (frozen codec + action-conditioned diffusion transformer). + +A single-GPU-safe trainer: flow-matching diffusion loss on codec latents, periodic validation loss, +and an optional world-model metrics eval (DINO/latent drift + Frechet curves) with rollout +visualizations logged to W&B. Video-only. Data is read +through :func:`mira.data.training_loader.create_loader`; the codec is loaded frozen from +its checkpoint by the model itself. Launch with Hydra:: + + python scripts/train_world_model.py \\ + model.architecture.config.codec_checkpoint=/path/to/codec_ckpt \\ + dataset.train_index=/path/to/train dataset.test_index=/path/to/test + +Multi-GPU runs go through ``torchrun`` (the distributed setup no-ops for a single process). +``run.compile`` is opt-in (default off) for reproducibility; when enabled it compiles the codec +encoder, the inner diffusion transformer, and the codec decoder *separately* — the model forward has +data-dependent control flow, so compiling the whole module would graph-break every step. +""" + +from __future__ import annotations + +import contextlib +import logging +import random +import time +from collections import defaultdict +from collections.abc import Iterator +from datetime import datetime +from pathlib import Path + +import hydra +import torch +import torch.distributed as dist +import tqdm +from hydra.utils import instantiate +from omegaconf import DictConfig, OmegaConf +from rich.logging import RichHandler +from torch.nn.parallel import DistributedDataParallel + +from mira.data.training_loader import ClipMeta, create_loader +from mira.training.checkpoint_manager import CheckpointManager +from mira.training.distributed import get_distributed_settings, set_up_distributed +from mira.training.lr_schedule import WarmupConstantCosineDecayLR +from mira.training.metrics.distributed_metric import DistributedMetric +from mira.training.metrics.world_model_metrics import ( + WorldModelMetrics, + WorldModelMetricsConfig, + build_frechet_curve_plots, +) +from mira.training.tracker import TrainingTracker, display_execution_time, periodic_event +from mira.training.visualization import ( + VideoForWandb, + draw_text_on_first_frame, + videos_for_wandb, +) +from mira.world_model.latent_world_model import InferenceOutputs, LatentWorldModel + +logging.basicConfig(format="%(message)s", datefmt="[%X]", handlers=[RichHandler()]) + +logger = logging.getLogger(__name__) + + +def _autocast(device: int | str | torch.device): + """bfloat16 autocast on CUDA, a no-op elsewhere (so the trainer runs on CPU too).""" + if torch.cuda.is_available(): + return torch.autocast(device_type="cuda", dtype=torch.bfloat16) + return contextlib.nullcontext() + + +def _frame_size(cfg: DictConfig) -> tuple[int, int] | None: + fs = cfg.dataset.get("frame_size") + return tuple(fs) if fs is not None else None # type: ignore[return-value] + + +@hydra.main(version_base=None, config_path="../configs", config_name="train_world_model") +def train(cfg: DictConfig) -> None: + distributed_settings = set_up_distributed() + is_main_process = distributed_settings.is_main_process + device = distributed_settings.device + + torch.manual_seed(cfg.run.seed + distributed_settings.rank) + logging.getLogger().setLevel(logging.INFO if is_main_process else logging.ERROR) + + logger.info("[magenta]" + "=" * 60 + "[/magenta]") + logger.info("[magenta]Training configuration:[/magenta]") + logger.info(OmegaConf.to_yaml(cfg)) + + if is_main_process: + _init_wandb(cfg) + + raw_model: LatentWorldModel = instantiate(cfg.model.architecture) + raw_model.train().to(device) + is_distributed = dist.is_available() and dist.is_initialized() + model = DistributedDataParallel(raw_model, device_ids=[device]) if is_distributed else raw_model + + if cfg.run.get("compile"): + # Compile the codec encoder, the inner diffusion transformer, and the codec decoder + # separately. The model forward has data-dependent control flow, so compiling the whole + # module would graph-break every step. + raw_model.codec.encode = torch.compile(raw_model.codec.encode) + raw_model.world_model.compile() + raw_model.decode_to_video = torch.compile(raw_model.decode_to_video) + + if is_main_process: + n_codec_params = sum(p.numel() for p in raw_model.codec.parameters()) + n_total_params = sum(p.numel() for p in raw_model.parameters()) + logger.info( + f"Initialized latent world model with {(n_total_params - n_codec_params) / 1e6:.2f}M " + f"parameters (+{n_codec_params / 1e6:.2f}M in the frozen codec)." + ) + + wm_metrics_config: WorldModelMetricsConfig = instantiate(cfg.world_model_metrics) + train_loader, val_loader, metrics_loader = _create_dataloaders(cfg, wm_metrics_config, raw_model) + + optimizer = torch.optim.AdamW( + model.parameters(), + # `lr` needs to be a tensor to compile the backward pass. + **{**cfg.optim.optimizer, "lr": torch.tensor(cfg.optim.optimizer.lr)}, + ) + lr_scheduler = WarmupConstantCosineDecayLR(optimizer, **cfg.optim.scheduler) + + @torch.compile(disable=not cfg.run.get("compile")) + def optimizer_step() -> None: + optimizer.step() + lr_scheduler.step() + + iter_train_loader = iter(train_loader) + with display_execution_time("Warming up dataloader", print_output=is_main_process): + # First batch takes longer; warm it up before the timed loop. + next(iter_train_loader) + + training_tracker = TrainingTracker( + world_size=distributed_settings.world_size, device=device, total_steps=int(cfg.run.steps) + ) + checkpoint_manager = CheckpointManager( + raw_model, + checkpoint_dir=cfg.run.output_dir, + save_every=cfg.run.checkpoint_every, + keep_recent=cfg.run.checkpoint_keep_recent, + keep_permanent_every=cfg.run.checkpoint_keep_permanent_every, + total_steps=int(cfg.run.steps), + model_ema_decay=cfg.optim.model_ema_decay, + ) + checkpoint_manager.register({"optimizer": optimizer, "lr_scheduler": lr_scheduler}) + + start_step = _resume(cfg, checkpoint_manager) + + # Built lazily on the first metrics eval: constructing it loads the DINO/Inception backbones and + # pytorch_fid. If those are unavailable, downstream metrics are skipped for the rest of training. + wm_metrics: WorldModelMetrics | None = None + wm_metrics_disabled = False + + losses: dict[str, torch.Tensor] = {} + iter_num = start_step - 1 # well-defined for the final save below if the loop never runs + for iter_num in range(start_step, int(cfg.run.steps)): + step_start_time = time.monotonic() + + batch, _ = next(iter_train_loader) + batch = batch.to(device) + + optimizer.zero_grad(set_to_none=True) + with _autocast(device): + losses = model(batch) + + losses["loss_total"].backward() + optimizer_step() + checkpoint_manager.model_ema.step() + + training_tracker.on_batch_processed(batch, losses) + + early_logging_steps = 10 + if periodic_event(iter_num, cfg.run.log_every, cfg.run.steps) or iter_num < early_logging_steps: + # All ranks must call get_stats() so the inner all_reduce completes. + stats = training_tracker.get_stats(step=iter_num) + stats["train/learning_rate"] = optimizer.param_groups[0]["lr"] + if is_main_process: + stats["System/step_ms"] = (time.monotonic() - step_start_time) * 1000 + logger.info(f"Step {iter_num}: total loss {stats['train/loss_total']:.4f}") + _wandb_log(stats, step=iter_num) + + if periodic_event( + iter_num, cfg.validation.val_every, cfg.run.steps, include_0=cfg.validation.val_first + ): + with checkpoint_manager.model_ema.average_parameters(): + # Fresh iterator each eval so the same fixed subsample is scored every time. + run_validation(cfg, device, raw_model, iter(val_loader), iter_num) + + if periodic_event(iter_num, cfg.run.checkpoint_every, cfg.run.steps, include_0=False): + if is_main_process: + checkpoint_manager.maybe_save_checkpoint(iter_num, extra_data=_extra_data(iter_num, losses)) + if is_distributed: + dist.barrier() + + if not wm_metrics_disabled and periodic_event( + iter_num, cfg.validation.downstream_val_every, cfg.run.steps, include_0=False + ): + if wm_metrics is None: + try: + wm_metrics = WorldModelMetrics(wm_metrics_config, iter(metrics_loader), device) + except Exception as exc: # noqa: BLE001 -- any dep/weight failure disables the eval + logger.warning( + "World-model metrics unavailable (%s: %s); skipping the downstream eval for " + "the rest of training. Install `mira[eval]` and make the DINO/" + "Inception weights reachable to enable it.", + type(exc).__name__, + exc, + ) + wm_metrics_disabled = True + if wm_metrics is not None: + with checkpoint_manager.model_ema.average_parameters(): + run_world_model_metrics(cfg, wm_metrics, metrics_loader, raw_model, iter_num) + + if is_distributed: + dist.barrier() + + if is_main_process and iter_num >= start_step: # skip when resuming an already-finished run + checkpoint_manager.maybe_save_checkpoint( + iter_num, extra_data=_extra_data(iter_num, losses), final=True + ) + logger.info("Done training") + if is_distributed: + dist.destroy_process_group() + + +def run_validation( + cfg: DictConfig, + device: torch.device | int | str, + model: LatentWorldModel, + iter_val_loader: Iterator[tuple], + iter_num: int, +) -> None: + """Average the world-model forward loss over a fixed validation subsample. Runs on all ranks.""" + t1 = time.time() + distributed_settings = get_distributed_settings() + is_distributed = dist.is_available() and dist.is_initialized() + model.eval() + world_size = distributed_settings.world_size + val_batch_size = cfg.validation.batch_size or cfg.run.batch_size + n_batches = cfg.validation.val_n_samples // (val_batch_size * world_size) + + metric_trackers: dict[str, DistributedMetric] = defaultdict(lambda: DistributedMetric(device=device)) + for _ in tqdm.trange( + max(1, n_batches), disable=not distributed_settings.is_main_process, desc="Running validation" + ): + batch, _ = next(iter_val_loader) + batch = batch.to(device) + with torch.no_grad(), _autocast(device): + for k, v in model(batch).items(): + metric_trackers[k].update(v) + + metrics = {k: tracker.compute_and_reset().item() for k, tracker in metric_trackers.items()} + if distributed_settings.is_main_process: + logger.info(f"Validation took {time.time() - t1:.2f}s") + logger.info( + f"Validation at step {iter_num}: " + ", ".join(f"{k}={v:.4f}" for k, v in metrics.items()) + ) + _wandb_log({f"test/{k}": v for k, v in metrics.items()}, step=iter_num) + + model.train() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + if is_distributed: + dist.barrier() + + +def run_world_model_metrics( + cfg: DictConfig, + wm_metrics: WorldModelMetrics, + metrics_loader, + model: LatentWorldModel, + iter_num: int, +) -> None: + """Unroll the world model on a held-out subsample, log metrics + rollout viz. Runs on all ranks.""" + distributed_settings = get_distributed_settings() + is_main_process = distributed_settings.is_main_process + is_distributed = dist.is_available() and dist.is_initialized() + config = wm_metrics.config + + if torch.cuda.is_available(): + torch.cuda.empty_cache() + model.eval() + + num_eval_batches = max( + 1, config.num_samples // (config.per_device_batch_size * distributed_settings.world_size) + ) + logger.info(f"Running world model metrics at step {iter_num} for {num_eval_batches} batches") + + # Fresh iterator each eval so the same fixed subsample is scored every time. + wm_metrics.iter_dataloader = iter(metrics_loader) + + # Visualize a random subset of the eval samples, reusing the videos generated for metrics (no + # extra inference). Re-sampled each eval so the logged clips vary; rank 0 only (it does logging). + viz_batch_indices: set[int] = set() + if is_main_process: + viz_batch_indices = set( + random.sample(range(num_eval_batches), min(config.num_viz_samples, num_eval_batches)) + ) + viz_samples: list[dict] = [] + + t_start = time.time() + for batch_idx in tqdm.trange( + num_eval_batches, disable=not is_main_process, desc="Evaluating world model metrics" + ): + inference_outputs, metadata = wm_metrics.process_batch(model) + if batch_idx in viz_batch_indices: + viz_samples.append(_render_viz_sample(model, inference_outputs, metadata)) + if is_distributed: + dist.barrier() + + if is_main_process and viz_samples: + _log_viz_videos(viz_samples, fps=model.config.video.fps, iter_num=iter_num) + + metric_values, frechet_curves = wm_metrics.compute() + + if is_main_process: + for k, v in metric_values.items(): + logger.info(f" {k}: {float(v):.4f}") + viz_plots = build_frechet_curve_plots(frechet_curves, config.fdd_slice_frames) + _wandb_log( + {f"metrics/{k}": float(v) for k, v in metric_values.items()} + | viz_plots + | {"metrics/time_min": (time.time() - t_start) / 60}, + step=iter_num, + ) + + model.train() + if is_distributed: + dist.barrier() + + +def _render_viz_sample( + model: LatentWorldModel, inference_outputs: InferenceOutputs, metadata: list[ClipMeta] +) -> dict: + """Render one already-generated rollout into a CPU viz tensor (rank 0, metrics loop).""" + n_players = getattr(model, "n_players", 1) + captions = [f"{m.match_id}:{m.perspective}" for m in metadata] + grouped = [" + ".join(captions[i : i + n_players]) for i in range(0, len(captions), n_players)] + + viz_video = model.visualize(inference_outputs)["viz_video"] + viz_video = draw_text_on_first_frame(viz_video, grouped) + return {"viz_video": viz_video.cpu(), "captions": captions} + + +def _log_viz_videos(viz_samples: list[dict], fps: float, iter_num: int) -> None: + """Concatenate per-sample rollout viz tensors and log them to W&B. Rank 0 only.""" + caption = ", ".join(cid for s in viz_samples for cid in s["captions"]) + video = torch.cat([s["viz_video"] for s in viz_samples], dim=0) + with videos_for_wandb( + {"videos/viz_video": VideoForWandb(video=video, caption=caption)}, fps=fps + ) as wandb_videos: + _wandb_log(dict(wandb_videos), step=iter_num) + + +def _create_dataloaders(cfg: DictConfig, wm_metrics_config: WorldModelMetricsConfig, model: LatentWorldModel): + """Build the (train, val, metrics) dataloaders. The val/metrics loaders use fixed seeds so the + same held-out subsample is scored every eval.""" + n_players = getattr(model, "n_players", 1) + dataset_n_players = cfg.dataset.get("n_players", 1) + if dataset_n_players != n_players: + raise ValueError( + f"dataset n_players ({dataset_n_players}) != model n_players ({n_players}); the " + "match-grouped dataset must provide exactly as many perspectives as the model expects." + ) + + # Apply the eval's context override before deriving the metrics clip length, so the loader, the + # rollout, and the metric indexing all agree on n_context_frames (see set_inference_context). + if wm_metrics_config.n_context_frames is not None: + model.set_inference_context(wm_metrics_config.n_context_frames) + + common = dict( + target_fps=model.config.video.fps, + # Actions are sampled at their own rate, decoupled from the frame rate. The released default + # has both at 20fps (one action per video frame), so this is a no-op; setting actions.target_fps + # above video.fps turns on the knob (e.g. 20fps frames + 40fps actions => 2 actions/frame). + action_fps=model.config.actions.target_fps, + n_players=n_players, + num_workers=cfg.dataloader.num_workers, + shuffle_buffer_size=cfg.dataloader.shuffle_buffer_size, + frame_size=_frame_size(cfg), + valid_keys=list(model.config.actions.valid_keys), + infinite=True, + ) + stride = wm_metrics_config.eval_temporal_downsampling or model.temporal_downsampling + + train_loader = create_loader( + index_path=cfg.dataset.train_index, + clip_len=model.config.video.timesteps, + batch_size=cfg.run.batch_size, + seed=cfg.run.seed, + exclude_replays=cfg.dataset.exclude_replays, + **common, + ) + val_loader = create_loader( + index_path=cfg.dataset.test_index, + clip_len=model.config.video.timesteps, + batch_size=cfg.validation.batch_size or cfg.run.batch_size, + seed=37, + exclude_replays=True, + **common, + ) + metrics_loader = create_loader( + index_path=cfg.dataset.test_index, + clip_len=model.config.n_context_frames + wm_metrics_config.num_unrolled_frames * stride, + batch_size=wm_metrics_config.per_device_batch_size, + seed=38, + exclude_replays=True, + **common, + ) + return train_loader, val_loader, metrics_loader + + +def _extra_data(iter_num: int, losses: dict[str, torch.Tensor]) -> dict: + extra_data = {k: v.item() for k, v in losses.items() if v.numel() == 1} + extra_data["iter_num"] = iter_num + return extra_data + + +def _init_wandb(cfg: DictConfig) -> None: + import wandb # noqa: PLC0415 -- optional dep, used only on the main process + + timestamp = datetime.now().strftime("%y%m%d-%H%M") + cfg.wandb.name = f"{cfg.wandb.name}-{timestamp}" + if cfg.wandb.group is not None: + cfg.wandb.group = f"{cfg.wandb.group}-{timestamp}" + + Path(cfg.run.output_dir).mkdir(parents=True, exist_ok=True) + wandb.init( + entity=cfg.wandb.entity, + project=cfg.wandb.project, + name=cfg.wandb.name, + group=cfg.wandb.group, + config=OmegaConf.to_container(cfg, resolve=True), + dir=cfg.run.output_dir, + mode=cfg.wandb.mode, + ) + # The checkpoint loader reads world_model_config.yaml from a parent dir of the checkpoint. + OmegaConf.save(cfg, Path(cfg.run.output_dir) / LatentWorldModel.CONFIG_FILENAME, resolve=True) + + +def _wandb_log(stats: dict, step: int) -> None: + import wandb # noqa: PLC0415 -- optional dep, used only on the main process + + if wandb.run is not None: + wandb.log(stats, step=step) + + +def _resume(cfg: DictConfig, checkpoint_manager: CheckpointManager) -> int: + """Resume from continue_from / finetune_from / an auto-discovered checkpoint, else start at 0.""" + continue_from = cfg.run.get("continue_from") + finetune_from = cfg.run.get("finetune_from") + if continue_from and finetune_from: + raise ValueError("Set at most one of run.continue_from and run.finetune_from") + + if continue_from: + return checkpoint_manager.continue_from(continue_from) + if finetune_from: + checkpoint_manager.finetune_from(finetune_from) + return 0 + if checkpoint_manager.latest_checkpoint is not None: + logger.info(f"Auto-resuming from existing checkpoint in {cfg.run.output_dir}") + return checkpoint_manager.continue_from(checkpoint_manager.latest_checkpoint) + return 0 + + +if __name__ == "__main__": + train() diff --git a/release-20261107/source/workspace_joint/mira/scripts/validate_joint_inference.py b/release-20261107/source/workspace_joint/mira/scripts/validate_joint_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..778e1d19e246473cc5fb94681105791c8375d402 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/scripts/validate_joint_inference.py @@ -0,0 +1,297 @@ +#!/usr/bin/env python3 +"""Real-checkpoint GPU validation only: no optimizer, backward, or checkpoint writes.""" +from __future__ import annotations + +import argparse +import gc +import json +import os +from pathlib import Path +import time +import traceback + +import numpy as np +import torch + +from mira.codec.codec_model import VideoCodec +from mira.data.joint_online import JointOnlineRoboTwinDataset +from mira.data.world_v6 import preprocess_qwen_rgb +from mira.inference.robotwin_v6_runtime import _empty_codec_batch +from mira.inference.robotwin_v12_runtime import BiHubWAMV12ResearchRuntime +from mira.joint.model import JointWorldActionModel +from mira.training.visualization import write_video_ffmpeg + + +def emit(path: Path, row: dict) -> None: + with path.open('a') as stream: + stream.write(json.dumps(row, allow_nan=False) + '\n') + print(json.dumps(row, allow_nan=False), flush=True) + + +def memory() -> dict: + free, total = torch.cuda.mem_get_info() + return dict(allocated_gib=torch.cuda.memory_allocated() / 2**30, + reserved_gib=torch.cuda.memory_reserved() / 2**30, + peak_allocated_gib=torch.cuda.max_memory_allocated() / 2**30, + peak_reserved_gib=torch.cuda.max_memory_reserved() / 2**30, + device_free_gib=free / 2**30, device_total_gib=total / 2**30) + + +def selected_cases(dataset, limit, offset=0, *, all_task_domains=False, + num_shards=1, shard_index=0): + episodes = [] + targets = ( + sorted({(str(row['task']), str(row['domain'])) for row in dataset.source_rows}) + if all_task_domains + else [(task, domain) for task in ('adjust_bottle', 'lift_pot') + for domain in ('clean', 'randomized')] + ) + for task, domain in targets: + match = next((i for i, row in enumerate(dataset.source_rows) + if row['task'] == task and row['domain'] == domain), None) + if match is not None: + episodes.append(match) + if not episodes: + episodes = [0] + # Iterate anchor strata before episodes: even a short test sees multiple tasks/domains. + candidates = [] + for stratum in ('cold', 'h5', 'h9', 'full', 'tail'): + for episode in episodes: + last = dataset.base_counts[episode] - 1 + anchor = {'cold': 0, 'h5': min(8, last), 'h9': min(16, last), + 'full': min(24, last), 'tail': last}[stratum] + candidates.append((episode, anchor, stratum)) + if limit > 0 and limit < len(candidates) and offset == 0: + # Include both initial and final strata in bounded tests. + positions = np.linspace(0, len(candidates) - 1, limit, dtype=int) + candidates = [candidates[i] for i in positions] + elif limit > 0 and candidates: + # A deterministic window lets multiple GPUs cover disjoint case shards. + candidates = [candidates[(offset + i) % len(candidates)] + for i in range(min(limit, len(candidates)))] + if not 0 <= shard_index < num_shards: + raise ValueError('shard_index must be in [0,num_shards)') + return candidates[shard_index::num_shards] + + +def encode(codec, video, device, *, full_precision=False): + batch = _empty_codec_batch(video.to(device)) + codec.preprocess_batch(batch) + with torch.autocast('cuda', dtype=torch.bfloat16, enabled=not full_precision): + normalized, encoded = codec.encode(batch.video, trim_video=False) + return normalized, encoded.z + + +def action_metrics(runtime, predicted, sample): + prediction = torch.as_tensor(predicted, dtype=torch.float32) + target = sample['action_gt'].reshape(20, 14) + valid = sample['action_valid'] + scale = runtime.action.action_std.float().cpu().reshape(14) + error = ((prediction - target) / scale).square().mean(dim=-1) + prefix = valid.clone() + prefix[8:] = False + return {'normalized_action_mse': float(error[valid].mean()), + 'execute8_normalized_mse': float(error[prefix].mean()), + 'valid_action_steps': int(valid.sum())} + + +def video_grid(path, truth, predicted): + # Views are columns L/G/R, truth and prediction are rows. + top = torch.cat(list(truth.unbind(0)), dim=-1) + bottom = torch.cat(list(predicted.unbind(0)), dim=-1) + grid = torch.cat([top, bottom], dim=-2) + write_video_ffmpeg(path, (grid.float().cpu() * .5 + .5).clamp(0, 1), fps=20) + + +@torch.inference_mode() +def run(args, report): + device = torch.device('cuda:0') + torch.cuda.set_device(device) + torch.cuda.set_per_process_memory_fraction(args.memory_cap_gib * 2**30 / torch.cuda.get_device_properties(device).total_memory) + torch.cuda.reset_peak_memory_stats() + torch.set_num_threads(2) + torch.manual_seed(20260920) + torch.cuda.manual_seed(20260920) + dataset = JointOnlineRoboTwinDataset(dataset_root=args.workspace / 'datasets/RoboTwin2.0', + manifest=args.workspace / 'datasets/RoboTwin2.0/mira_wam_aloha/val.jsonl') + cases = selected_cases( + dataset, args.cases, args.case_offset, + all_task_domains=args.all_task_domains, + num_shards=args.num_shards, shard_index=args.shard_index, + ) + emit(report, dict(event='start', mode=args.mode, action_step=args.action_step, + physical_gpu=os.environ.get('CUDA_VISIBLE_DEVICES'), pid=os.getpid(), + case_offset=args.case_offset, all_task_domains=args.all_task_domains, + num_shards=args.num_shards, shard_index=args.shard_index, + memory_cap_gib=args.memory_cap_gib, training=False, **memory())) + runtime = None + started = time.perf_counter() + if args.mode == 'codec': + codec = VideoCodec.load_from_checkpoint( + args.workspace / 'outputs/mira_robotwin_codec/checkpoint-125000/checkpoint.pth', + device='cpu').to(device).eval().requires_grad_(False) + else: + runtime = BiHubWAMV12ResearchRuntime(action_checkpoint=args.workspace / + f'outputs/robotwin_bihub_wam_v13_action_eval_aligned_continue4epoch/action-checkpoint-{args.action_step}', + device=str(device)) + codec = runtime.codec + torch.cuda.synchronize() + emit(report, dict(event='loaded', seconds=time.perf_counter()-started, **memory())) + joint = None + if args.mode == 'joint': + joint = JointWorldActionModel(runtime.world, runtime.action).eval().requires_grad_(False) + case_rows = [] + for case_number, (episode, anchor, stratum) in enumerate(cases): + torch.cuda.empty_cache() + free, _ = torch.cuda.mem_get_info() + if free < 8 * 2**30: + raise RuntimeError('Co-run safety stop: free memory fell below 8 GiB') + sample = dataset[dataset.anchor_index(episode, anchor)] + metadata = sample['metadata'] + started = time.perf_counter() + result = dict(event='case', case=case_number, stratum=stratum, **metadata) + if args.mode == 'baseline': + rgb = sample['video'][:, :20].permute(0, 1, 3, 4, 2).numpy() + predicted, diagnostics = runtime.plan(rgb_history=rgb, + state_history=sample['state_history_raw'].reshape(20, 14).numpy(), + state_valid=sample['history_valid'].numpy(), instruction=metadata['instruction'], + task=metadata['task'], domain=metadata['domain'], environment_seed=20260920, + replan_index=anchor, capture_world=(case_number == 0)) + context = diagnostics.pop('_world_context_raw', None) + future = diagnostics.pop('_world_prediction_raw', None) + result.update(diagnostics) + result.update(action_metrics(runtime, predicted, sample)) + assert np.isfinite(predicted).all() and predicted.shape == (20, 14) + if case_number == 0: + repeated, _ = runtime.plan(rgb_history=rgb, + state_history=sample['state_history_raw'].reshape(20, 14).numpy(), + state_valid=sample['history_valid'].numpy(), instruction=metadata['instruction'], + task=metadata['task'], domain=metadata['domain'], environment_seed=20260920, + replan_index=anchor) + difference = float(np.max(np.abs(predicted - repeated))) + result['repeat_max_abs_action_error'] = difference + if difference > 1e-5: + raise AssertionError(f'Repeated inference is not stable: {difference}') + # Decode one view at a time to bound scratch memory; view paths are independent. + decoded = [] + with torch.autocast('cuda', dtype=torch.bfloat16): + for view in range(3): + latent = torch.cat([context[view], future[view]], dim=0)[None].to(device) + decoded.append(codec.decode(latent)[0, 20:].float().cpu()) + normalized, _ = encode(codec, sample['video'][:, 20:], device) + video_grid(args.output / 'world_prediction.mp4', normalized.cpu(), torch.stack(decoded)) + np.savez(args.output / f'action_{case_number:03d}.npz', predicted=predicted, + target=sample['action_gt'].reshape(20, 14).numpy(), valid=sample['action_valid'].numpy()) + else: + normalized, latents = encode(codec, sample['video'], device) + _, context_only = encode(codec, sample['video'][:, :20], device) + difference = float((latents[:, :10].float() - context_only.float()).abs().max()) + result['codec_context_prefix_max_abs_error'] = difference + result['codec_context_prefix_rmse'] = float((latents[:, :10].float() - context_only.float()).square().mean().sqrt()) + # Test causality at identical shapes, not with an arbitrary BF16 closeness threshold. + # Different batch sizes can select different reduced-precision GEMM kernels. + if case_number == 0: + perturbed_video = sample['video'].clone() + perturbed_video[:, 20:] = 255 - perturbed_video[:, 20:] + _, changed = encode(codec, perturbed_video, device) + result['same_shape_future_perturbation_prefix_error'] = float((latents[:, :10] - changed[:, :10]).abs().max()) + torch.testing.assert_close(latents[:, :10], changed[:, :10], atol=0, rtol=0) + del changed, perturbed_video + if args.mode == 'codec': + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + _, fp32_full = encode(codec, sample['video'], device, full_precision=True) + _, fp32_context = encode(codec, sample['video'][:, :20], device, full_precision=True) + result['fp32_context_prefix_max_abs_error'] = float((fp32_full[:, :10] - fp32_context).abs().max()) + torch.testing.assert_close(fp32_full[:, :10], fp32_context, atol=1e-4, rtol=1e-4) + del fp32_full, fp32_context + if args.mode == 'codec': + decoded = [] + with torch.autocast('cuda', dtype=torch.bfloat16): + for view in range(3): + decoded.append(codec.decode(latents[view:view+1]).float().cpu()) + reconstructed = torch.cat(decoded) + result['reconstruction_mse'] = float((normalized.float().cpu() - reconstructed).square().mean()) + if case_number == 0: + video_grid(args.output / 'codec_reconstruction.mp4', normalized.cpu(), reconstructed) + else: + current = preprocess_qwen_rgb(sample['video'][:, 19])[None] + with torch.autocast('cuda', dtype=torch.bfloat16): + hidden, mask = runtime.qwen(current, [metadata['instruction']]) + state = runtime._normalize_state(sample['state_history_raw'].reshape(20, 14).to(device)).reshape(1, 20, 2, 7) + kwargs = dict(z_context_raw=latents[None, :, :10], z_future_raw=latents[None, :, 10:], + state_history=state, history_valid=sample['history_valid'][None].to(device), + context_valid=sample['context_valid'][None].to(device), + action_gt=sample['action_gt'][None].to(device), action_valid=sample['action_valid'][None].to(device), + future_valid=sample['future_valid'][None].to(device), qwen_hidden=hidden, qwen_mask=mask, + rollout_noise=torch.randn_like(latents[None, :, 10:], dtype=torch.float32), + action_noise=torch.randn(1, 20, 2, 7, device=device), rollout_steps=10) + values = joint(**kwargs) + for name in ('loss_world_flow', 'loss_world_latent', 'loss_action', 'world_recovered_clean_mse'): + assert torch.isfinite(values[name]).all(), name + result[name] = float(values[name]) + if not bool(sample['future_valid'].any()): + assert result['loss_world_flow'] == 0 and result['loss_world_latent'] == 0 + result['future_valid_count'] = int(sample['future_valid'].sum()) + assert all(p.grad is None and not p.requires_grad for p in joint.parameters()) + del values, kwargs, hidden, mask + del normalized, latents, context_only + torch.cuda.synchronize() + result['seconds'] = time.perf_counter() - started + result.update(memory()) + emit(report, result) + case_rows.append(result) + gc.collect() + assert all(p.grad is None and not p.requires_grad for p in codec.parameters()) + if runtime is not None: + runtime.qwen.assert_frozen() + for module in (runtime.world, runtime.action): + assert all(p.grad is None and not p.requires_grad for p in module.parameters()) + summary = dict(status='passed', mode=args.mode, action_step=args.action_step, cases=len(cases), + all_task_domains=args.all_task_domains, num_shards=args.num_shards, + shard_index=args.shard_index, + task_count=len({row['task'] for row in case_rows}), + domains=sorted({row['domain'] for row in case_rows}), + strata=sorted({row['stratum'] for row in case_rows}), + training=False, backward_calls=0, optimizer_steps=0, checkpoint_writes=0, **memory()) + if runtime is not None: + summary['runtime_provenance'] = runtime.provenance_dict() + if args.mode == 'baseline': + for key in ('normalized_action_mse', 'execute8_normalized_mse', 'latency_s', 'seconds'): + values = np.asarray([row[key] for row in case_rows], dtype=np.float64) + summary[f'{key}_mean'] = float(values.mean()) + summary[f'{key}_p50'] = float(np.quantile(values, 0.50)) + summary[f'{key}_p95'] = float(np.quantile(values, 0.95)) + (args.output / 'summary.json').write_text(json.dumps(summary, indent=2) + '\n') + emit(report, dict(event='done', **summary)) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mode', choices=['baseline', 'joint', 'codec'], required=True) + parser.add_argument('--action-step', type=int, choices=[11508, 23016], default=23016) + parser.add_argument('--cases', type=int, default=8) + parser.add_argument('--case-offset', type=int, default=0) + parser.add_argument('--all-task-domains', action='store_true') + parser.add_argument('--num-shards', type=int, default=1) + parser.add_argument('--shard-index', type=int, default=0) + parser.add_argument('--memory-cap-gib', type=float, default=32) + parser.add_argument('--workspace', type=Path, default=Path(__file__).resolve().parents[2]) + parser.add_argument('--output', type=Path, required=True) + args = parser.parse_args() + import setproctitle + setproctitle.setproctitle(f'syncnet_eval_{os.environ.get("CUDA_VISIBLE_DEVICES", "x")}') + args.output.mkdir(parents=True, exist_ok=False) + report = args.output / 'metrics.jsonl' + try: + run(args, report) + except Exception as exc: + failure = dict(status='failed', error=repr(exc), traceback=traceback.format_exc(), training=False) + if torch.cuda.is_initialized(): + failure.update(memory()) + (args.output / 'summary.json').write_text(json.dumps(failure, indent=2) + '\n') + raise + + +if __name__ == '__main__': + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/__init__.py b/release-20261107/source/workspace_joint/mira/src/mira/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4d2a005b3717a53735b8f5938e9667955d147882 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/__init__.py @@ -0,0 +1,5 @@ +"""mira: a multiplayer world model for Rocket League. + +The :mod:`mira.data` submodule loads the 4-player dataset — time-aligned video frames, +keyboard actions, game events, and per-frame physics across all 4 co-temporal player perspectives. +""" diff --git a/release-20261107/source/workspace_joint/mira/src/mira/action/__init__.py b/release-20261107/source/workspace_joint/mira/src/mira/action/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..724437aae78b7d3909dd4fd72a8c8c69f2e7ce34 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/action/__init__.py @@ -0,0 +1,6 @@ +"""Joint bimanual action-flow stage built on frozen BiHub world predictions.""" + +from .config import ActionHeadConfig +from .joint_action_flow import JointBimanualActionFlow + +__all__ = ["ActionHeadConfig", "JointBimanualActionFlow"] diff --git a/release-20261107/source/workspace_joint/mira/src/mira/action/checkpoint.py b/release-20261107/source/workspace_joint/mira/src/mira/action/checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..d8ba994c5f6f2c34fd87363b4ffd8dda58bbccd1 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/action/checkpoint.py @@ -0,0 +1,166 @@ +"""Atomic DCP checkpoints for the Action Head stage.""" + +from __future__ import annotations + +import json +import os +import random +import shutil +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import torch.distributed as dist +import torch.distributed.checkpoint as dcp +from torch.distributed.checkpoint.state_dict import get_state_dict, set_state_dict + +from mira.training.ema import ModelEMA + + +def _barrier() -> None: + if dist.is_available() and dist.is_initialized(): + dist.barrier() + + +def latest_action_checkpoint(output_dir: str | Path) -> Path | None: + candidates = [] + for path in Path(output_dir).glob("checkpoint-*"): + if not path.is_dir() or not (path / "trainer_state.json").is_file(): + continue + suffix = path.name.split("-", 1)[1] + if suffix.isdigit(): + candidates.append((int(suffix), path)) + return max(candidates, default=(None, None))[1] + + +def save_action_checkpoint( + output_dir: str | Path, + *, + completed_steps: int, + model: torch.nn.Module, + optimizer: torch.optim.Optimizer, + scheduler: Any, + ema: ModelEMA, + sampler: Any, + resolved_config: dict[str, Any], + artifact_identity: dict[str, Any], + metrics: dict[str, Any], + keep_recent: int = 2, + permanent_name: str | None = None, +) -> Path: + rank = dist.get_rank() if dist.is_initialized() else 0 + root = Path(output_dir) + final = root / (permanent_name or f"checkpoint-{completed_steps}") + temporary = root / f".{final.name}.tmp" + if rank == 0: + root.mkdir(parents=True, exist_ok=True) + if temporary.exists(): + shutil.rmtree(temporary) + temporary.mkdir(parents=True) + _barrier() + model_state, optimizer_state = get_state_dict(model, optimizer) + dcp.save( + {"model": model_state, "optimizer": optimizer_state, "ema": ema.state_dict()}, + checkpoint_id=temporary / "distributed", + ) + rank_state = { + "scheduler": scheduler.state_dict(), + "sampler": sampler.state_dict(), + "python_rng": random.getstate(), + "numpy_rng": np.random.get_state(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state() if torch.cuda.is_available() else None, + } + torch.save(rank_state, temporary / f"rank-{rank:05d}.pth") + _barrier() + if rank == 0: + curriculum = resolved_config["training"]["future_curriculum"] + gt_only_until = int(curriculum["gt_only_until"]) + transition_end = int(curriculum["transition_end"]) + phase = ( + "gt_only" + if completed_steps <= gt_only_until + else "transition" + if completed_steps <= transition_end + else "predicted_only" + ) + state = { + "format_version": 1, + "completed_steps": completed_steps, + "next_step": completed_steps, + "phase": phase, + "resolved_config": resolved_config, + "artifact_identity": artifact_identity, + "metrics": metrics, + } + (temporary / "trainer_state.json").write_text( + json.dumps(state, indent=2, default=str) + "\n", + encoding="utf-8", + ) + if final.exists(): + shutil.rmtree(final) + os.replace(temporary, final) + if permanent_name is None: + regular = sorted( + ( + (int(path.name.split("-", 1)[1]), path) + for path in root.glob("checkpoint-*") + if path.is_dir() and path.name.split("-", 1)[1].isdigit() + ), + key=lambda item: item[0], + ) + protected = {80_000, 90_000, 100_000} + if not bool(resolved_config["run"]["debug_smoke"]): + protected.update({gt_only_until, transition_end}) + removable = [(step, path) for step, path in regular if step not in protected] + for _, old in removable[:-keep_recent]: + shutil.rmtree(old) + _barrier() + return final + + +def load_action_checkpoint( + checkpoint: str | Path, + *, + model: torch.nn.Module, + optimizer: torch.optim.Optimizer, + scheduler: Any, + ema: ModelEMA, + sampler: Any, + expected_artifact_identity: dict[str, Any], +) -> int: + rank = dist.get_rank() if dist.is_initialized() else 0 + checkpoint = Path(checkpoint) + metadata = json.loads((checkpoint / "trainer_state.json").read_text(encoding="utf-8")) + if metadata["artifact_identity"] != expected_artifact_identity: + raise ValueError( + "Action checkpoint artifact identity mismatch; refusing unsafe resume:\n" + f"expected={json.dumps(expected_artifact_identity, sort_keys=True)}\n" + f"actual={json.dumps(metadata['artifact_identity'], sort_keys=True)}" + ) + model_state, optimizer_state = get_state_dict(model, optimizer) + state = {"model": model_state, "optimizer": optimizer_state, "ema": ema.state_dict()} + dcp.load(state, checkpoint_id=checkpoint / "distributed") + set_state_dict( + model, + optimizer, + model_state_dict=state["model"], + optim_state_dict=state["optimizer"], + ) + ema.load_state_dict(state["ema"]) + rank_path = checkpoint / f"rank-{rank:05d}.pth" + if not rank_path.is_file(): + raise ValueError( + f"Exact Action resume requires the same world size; missing rank state {rank_path}" + ) + rank_state = torch.load(rank_path, map_location="cpu", weights_only=False) + scheduler.load_state_dict(rank_state["scheduler"]) + sampler.load_state_dict(rank_state["sampler"]) + random.setstate(rank_state["python_rng"]) + np.random.set_state(rank_state["numpy_rng"]) + torch.set_rng_state(rank_state["torch_rng"]) + if torch.cuda.is_available() and rank_state["cuda_rng"] is not None: + torch.cuda.set_rng_state(rank_state["cuda_rng"]) + _barrier() + return int(metadata["next_step"]) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/action/config.py b/release-20261107/source/workspace_joint/mira/src/mira/action/config.py new file mode 100644 index 0000000000000000000000000000000000000000..cfaba1d725b62e138a8d27a98038d9b63b7b046b --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/action/config.py @@ -0,0 +1,54 @@ +"""Strict configuration for the frozen-world Action Head stage.""" + +from __future__ import annotations + +from pydantic import BaseModel, ConfigDict, model_validator + + +class ActionHeadConfig(BaseModel): + model_config = ConfigDict(extra="forbid") + + latent_dim: int = 32 + text_dim: int = 4096 + state_dim: int = 512 + hidden_dim: int = 1024 + layers: int = 16 + heads: int = 16 + kv_heads: int = 16 + ffn_dim: int = 4096 + action_dim: int = 14 + horizon: int = 20 + current_height: int = 9 + current_width: int = 12 + future_steps: int = 10 + future_height: int = 3 + future_width: int = 4 + future_drop_prob: float = 0.10 + activation_checkpointing: bool = True + noise_repeats: int = 2 + inference_steps: int = 10 + flow_beta_alpha: float = 1.5 + flow_beta_beta: float = 1.0 + flow_time_scale: float = 0.999 + + @model_validator(mode="after") + def validate_contract(self) -> "ActionHeadConfig": + if self.hidden_dim % self.heads: + raise ValueError("Action hidden_dim must be divisible by heads") + if self.heads % self.kv_heads: + raise ValueError("Action heads must be divisible by kv_heads") + if self.action_dim != 14 or self.horizon != 20: + raise ValueError("RoboTwin Action Head is locked to a joint 20x14 action chunk") + if (self.current_height, self.current_width) != (9, 12): + raise ValueError("Current latent memory is locked to the full 9x12 grid") + if (self.future_steps, self.future_height, self.future_width) != (10, 3, 4): + raise ValueError("Predicted-future memory is locked to 10x3x4 per view") + if not 0 <= self.future_drop_prob < 1: + raise ValueError("future_drop_prob must be in [0,1)") + if self.noise_repeats != 2: + raise ValueError("The formal Action objective requires exactly two noise repeats") + if self.flow_beta_beta != 1.0: + raise ValueError("The exact inverse-CDF sampler currently requires Beta(alpha, 1)") + if self.flow_time_scale <= 0 or self.flow_time_scale > 1: + raise ValueError("flow_time_scale must be in (0,1]") + return self diff --git a/release-20261107/source/workspace_joint/mira/src/mira/action/curriculum.py b/release-20261107/source/workspace_joint/mira/src/mira/action/curriculum.py new file mode 100644 index 0000000000000000000000000000000000000000..9bf329129c3c51ae45d816b4d27f365182138173 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/action/curriculum.py @@ -0,0 +1,40 @@ +"""Deterministic GT-to-predicted future curriculum.""" + +from __future__ import annotations + +import torch +from torch import Tensor + + +def gt_probability(step: int, *, gt_only_until: int = 5_000, transition_end: int = 20_000) -> float: + if step < 0: + raise ValueError("step must be non-negative") + if step < gt_only_until: + return 1.0 + if step >= transition_end: + return 0.0 + return 1.0 - (step - gt_only_until) / (transition_end - gt_only_until) + + +def choose_gt_future( + step: int, + global_sample_indices: Tensor, + *, + gt_only_until: int = 5_000, + transition_end: int = 20_000, +) -> Tensor: + """Choose whole-sample future sources without depending on rank partitioning.""" + probability = gt_probability( + step, + gt_only_until=gt_only_until, + transition_end=transition_end, + ) + if probability == 1.0: + return torch.ones_like(global_sample_indices, dtype=torch.bool) + if probability == 0.0: + return torch.zeros_like(global_sample_indices, dtype=torch.bool) + # Integer mixing is stable across Python versions and distributed layouts. + value = global_sample_indices.to(torch.int64) + value = (value * 6_364_136_223_846_793_005 + 1_442_695_040_888_963_407) & 0x7FFF_FFFF_FFFF_FFFF + threshold = int(probability * 1_000_000) + return value.remainder(1_000_000) < threshold diff --git a/release-20261107/source/workspace_joint/mira/src/mira/action/data.py b/release-20261107/source/workspace_joint/mira/src/mira/action/data.py new file mode 100644 index 0000000000000000000000000000000000000000..aca6f1c009ab99eb949602830dc9306e3a321c70 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/action/data.py @@ -0,0 +1,354 @@ +"""Action-window dataset joined to pooled predicted-future memmaps.""" + +from __future__ import annotations + +import json +import random +from collections import OrderedDict +from dataclasses import dataclass, fields +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import torch.nn.functional as F +from safetensors.torch import load_file +from torch import Tensor +from torch.utils.data import Dataset, Sampler + +from mira.data.robotwin_wam_schema import read_jsonl, sha256_file + + +@dataclass +class RoboTwinActionBatch: + current_latent: Tensor + future_gt_pooled: Tensor + future_pred_pooled: Tensor + joint_target_history: Tensor + action_history: Tensor + history_valid: Tensor + text_hidden: Tensor + text_mask: Tensor + action_target: Tensor + action_valid: Tensor + repeat_last_baseline: Tensor + per_task_mean_baseline: Tensor + + def to(self, *args: Any, **kwargs: Any) -> "RoboTwinActionBatch": + return RoboTwinActionBatch( + **{field.name: getattr(self, field.name).to(*args, **kwargs) for field in fields(self)} + ) + + +class PredictedFutureMemmap: + def __init__( + self, + root: str | Path, + *, + manifest: str | Path, + allow_incomplete: bool = False, + ) -> None: + self.root = Path(root).expanduser().resolve() + complete = self.root / "COMPLETE" + self.complete = complete.is_file() + if not self.complete and not allow_incomplete: + raise ValueError(f"Predicted-future cache is incomplete: missing {complete}") + if not self.complete: + self.metadata = {} + self._maps = {} + return + self.metadata = json.loads((self.root / "metadata.json").read_text(encoding="utf-8")) + expected_manifest = str(self.metadata["action_manifest_sha256"]) + actual_manifest = sha256_file(manifest) + if actual_manifest != expected_manifest: + raise ValueError( + "Predicted-future cache manifest identity mismatch: " + f"expected={expected_manifest} actual={actual_manifest}" + ) + expected = { + "dtype": "float16", + "view_order": ["left", "global", "right"], + "shape_per_row": [3, 10, 32, 3, 4], + "pooling": "adaptive_avg_pool2d_3x4", + "latent_space": "world_standardized", + } + for key, value in expected.items(): + if self.metadata.get(key) != value: + raise ValueError( + f"Predicted-future cache contract mismatch for {key}: " + f"expected={value!r} actual={self.metadata.get(key)!r}" + ) + self._maps: dict[int, np.memmap] = {} + + def _open(self, shard: int) -> np.memmap: + if shard not in self._maps: + shard_root = self.root / f"shard-{shard:05d}" + if not (shard_root / "COMPLETE").is_file(): + raise ValueError(f"Predicted-future shard {shard} is incomplete") + metadata = json.loads((shard_root / "metadata.json").read_text(encoding="utf-8")) + rows = int(metadata["rows"]) + self._maps[shard] = np.memmap( + shard_root / "future_pred10.f16", + mode="r", + dtype=np.float16, + shape=(rows, 3, 10, 32, 3, 4), + ) + return self._maps[shard] + + def get(self, shard: int, row: int) -> Tensor: + value = self._open(shard) + if not 0 <= row < value.shape[0]: + raise IndexError(f"Future cache row out of range: shard={shard} row={row}") + # Copy detaches the tensor from a read-only memmap and makes DataLoader collation safe. + return torch.from_numpy(np.array(value[row], copy=True)) + + +class RoboTwinActionDataset(Dataset[dict[str, Any]]): + def __init__( + self, + manifest: str | Path, + *, + state_stats: str | Path, + action_stats: str | Path, + future_cache: str | Path, + latent_mean: float, + latent_std: float, + require_real_text: bool = True, + episode_cache_size: int = 2, + allow_incomplete_future: bool = False, + ) -> None: + self.manifest_path = Path(manifest).expanduser().resolve() + self.rows = read_jsonl(self.manifest_path) + if not self.rows: + raise ValueError(f"Empty Action manifest: {manifest}") + if require_real_text and any(bool(row.get("text_cache_debug_only")) for row in self.rows): + raise ValueError("Formal Action training refuses deterministic debug text embeddings") + if any(row.get("state_semantics") != "simulator_drive_target_not_measured_qpos" for row in self.rows): + raise ValueError("Ambiguous state semantics in Action manifest") + + state = json.loads(Path(state_stats).read_text(encoding="utf-8")) + action = json.loads(Path(action_stats).read_text(encoding="utf-8")) + self.state_mean = torch.tensor(state["mean"], dtype=torch.float32) + self.state_std = torch.tensor(state["std"], dtype=torch.float32).clamp_min( + float(state.get("normalization_std_floor", 1.0e-2)) + ) + self.state_clip = float(state.get("normalization_clip", 5.0)) + self.action_mean = torch.tensor(action["mean"], dtype=torch.float32) + self.action_std = torch.tensor(action["std"], dtype=torch.float32) + self.action_clip = float(action["normalization_clip"]) + self.per_task_mean_chunk = { + str(task): torch.tensor(value, dtype=torch.float32) + for task, value in action["per_task_mean_chunk"].items() + } + self.global_mean_chunk = torch.tensor(action["global_mean_chunk"], dtype=torch.float32) + if min(self.action_std) <= 1.0e-6: + raise ValueError("Action statistics contain a degenerate dimension") + if self.state_mean.shape != (14,) or self.action_mean.shape != (14,): + raise ValueError("State and Action statistics must both use the frozen 14D order") + if self.global_mean_chunk.shape != (20, 14) or any( + value.shape != (20, 14) for value in self.per_task_mean_chunk.values() + ): + raise ValueError("Each per-task Action baseline must have shape [20,14]") + self.latent_mean = float(latent_mean) + self.latent_std = float(latent_std) + self.future_cache = PredictedFutureMemmap( + future_cache, + manifest=self.manifest_path, + allow_incomplete=allow_incomplete_future, + ) + self.episode_cache_size = max(1, int(episode_cache_size)) + self._episode_cache: OrderedDict[str, dict[str, Tensor]] = OrderedDict() + self._text_cache: OrderedDict[str, dict[str, Tensor]] = OrderedDict() + self.task_domain_rows: dict[str, dict[str, list[int]]] = {} + for index, row in enumerate(self.rows): + task = str(row["task"]) + domain = str(row["domain"]) + self.task_domain_rows.setdefault(task, {}).setdefault(domain, []).append(index) + self.tasks = sorted(self.task_domain_rows) + + def __len__(self) -> int: + return len(self.rows) + + @staticmethod + def _lru_load( + path: str, + cache: OrderedDict[str, dict[str, Tensor]], + limit: int, + ) -> dict[str, Tensor]: + if path in cache: + value = cache.pop(path) + cache[path] = value + return value + value = load_file(path, device="cpu") + cache[path] = value + while len(cache) > limit: + cache.popitem(last=False) + return value + + def _normalize_state(self, value: Tensor) -> Tensor: + return ((value.float() - self.state_mean) / self.state_std).clamp( + -self.state_clip, self.state_clip + ) + + def _normalize_action(self, value: Tensor) -> Tensor: + return ((value.float() - self.action_mean) / self.action_std).clamp( + -self.action_clip, self.action_clip + ) + + def _normalize_latent(self, value: Tensor) -> Tensor: + return (value.float() - self.latent_mean) / self.latent_std + + def __getitem__(self, index: int) -> dict[str, Any]: + row = self.rows[index] + episode = self._lru_load(str(row["cache_path"]), self._episode_cache, self.episode_cache_size) + text = self._lru_load(str(row["text_cache_path"]), self._text_cache, 64) + latent_start = int(row["latent_start"]) + state_start = 2 * latent_start + latent = episode["world_latent_raw_bf16"] + current = self._normalize_latent(latent[:, latent_start + 9]) + gt_future = self._normalize_latent(latent[:, latent_start + 10 : latent_start + 20]) + if current.shape != (3, 32, 9, 12) or gt_future.shape != (3, 10, 32, 9, 12): + raise RuntimeError(f"Truncated latent window for {row['window_id']}") + gt_pooled = F.adaptive_avg_pool2d( + gt_future.reshape(3 * 10, 32, 9, 12), + (3, 4), + ).reshape(3, 10, 32, 3, 4) + + state = episode["joint_target_state20_f32"] + history_raw = state[state_start : state_start + 20] + action_raw = state[state_start + 20 : state_start + 40] + if history_raw.shape != (20, 14) or action_raw.shape != (20, 14): + raise RuntimeError(f"Truncated state/action window for {row['window_id']}") + history_valid = torch.ones(20, dtype=torch.bool) + cached_next_action = episode["action20_f32"] + if state_start == 0: + previous = torch.zeros(20, 14, dtype=torch.float32) + previous[1:] = cached_next_action[:19] + history_valid[0] = False + else: + previous = cached_next_action[state_start - 1 : state_start + 19] + + context_indices = row["context_source_idx"] + action_indices = row["action_source_idx"] + if len(context_indices) != 20 or len(action_indices) != 20: + raise RuntimeError("Action manifest source-index arrays must each contain 20 entries") + if min(action_indices) <= max(context_indices): + raise RuntimeError(f"Action target overlaps factual history for {row['window_id']}") + if action_indices != row["future_video_source_idx"]: + raise RuntimeError(f"Action/future source-index mismatch for {row['window_id']}") + + predicted = ( + self.future_cache.get( + int(row["future_cache_shard"]), + int(row["future_cache_row"]), + ) + if self.future_cache.complete + else torch.zeros(3, 10, 32, 3, 4, dtype=torch.float16) + ) + if not torch.isfinite(predicted).all(): + raise RuntimeError(f"Non-finite predicted future for {row['window_id']}") + return { + "current_latent": current, + "future_gt_pooled": gt_pooled, + "future_pred_pooled": predicted, + "joint_target_history": self._normalize_state(history_raw).reshape(20, 2, 7), + "action_history": self._normalize_state(previous).reshape(20, 2, 7), + "history_valid": history_valid, + "text_hidden": text["text_hidden_bf16"], + "text_mask": text["text_mask_bool"], + "action_target": self._normalize_action(action_raw), + "action_valid": torch.ones(20, 14, dtype=torch.bool), + "repeat_last_baseline": self._normalize_action(history_raw[-1]).expand(20, -1), + "per_task_mean_baseline": self._normalize_action( + self.per_task_mean_chunk.get( + str(row["task"]), + self.global_mean_chunk, + ) + ), + "metadata": { + "dataset_index": index, + "window_id": row["window_id"], + "task": row["task"], + "domain": row["domain"], + "action_source_idx": action_indices, + "context_source_idx": context_indices, + }, + } + + +def collate_robotwin_action( + samples: list[dict[str, Any]], +) -> tuple[RoboTwinActionBatch, list[dict[str, Any]]]: + max_text = max(sample["text_hidden"].shape[0] for sample in samples) + text = torch.zeros(len(samples), max_text, 4096, dtype=torch.bfloat16) + mask = torch.zeros(len(samples), max_text, dtype=torch.bool) + for index, sample in enumerate(samples): + length = sample["text_hidden"].shape[0] + text[index, :length] = sample["text_hidden"] + mask[index, :length] = sample["text_mask"] + batch = RoboTwinActionBatch( + current_latent=torch.stack([sample["current_latent"] for sample in samples]), + future_gt_pooled=torch.stack([sample["future_gt_pooled"] for sample in samples]), + future_pred_pooled=torch.stack([sample["future_pred_pooled"] for sample in samples]), + joint_target_history=torch.stack([sample["joint_target_history"] for sample in samples]), + action_history=torch.stack([sample["action_history"] for sample in samples]), + history_valid=torch.stack([sample["history_valid"] for sample in samples]), + text_hidden=text, + text_mask=mask, + action_target=torch.stack([sample["action_target"] for sample in samples]), + action_valid=torch.stack([sample["action_valid"] for sample in samples]), + repeat_last_baseline=torch.stack( + [sample["repeat_last_baseline"] for sample in samples] + ), + per_task_mean_baseline=torch.stack( + [sample["per_task_mean_baseline"] for sample in samples] + ), + ) + return batch, [sample["metadata"] for sample in samples] + + +class DeterministicActionSampler(Sampler[int]): + """Infinite resumable task/domain-balanced Action sampler.""" + + def __init__( + self, + dataset: RoboTwinActionDataset, + *, + seed: int, + rank: int = 0, + world_size: int = 1, + clean_probability: float = 0.5, + start_index: int = 0, + ) -> None: + self.dataset = dataset + self.seed = int(seed) + self.rank = int(rank) + self.world_size = int(world_size) + self.clean_probability = float(clean_probability) + self.consumed = int(start_index) + + def __len__(self) -> int: + return 2**31 + + def __iter__(self): + local_position = self.consumed + while True: + global_position = local_position * self.world_size + self.rank + rng = random.Random(self.seed + global_position * 1_000_003) + task = self.dataset.tasks[rng.randrange(len(self.dataset.tasks))] + domains = self.dataset.task_domain_rows[task] + desired = "clean" if rng.random() < self.clean_probability else "randomized" + if desired not in domains: + desired = sorted(domains)[rng.randrange(len(domains))] + rows = domains[desired] + yield rows[rng.randrange(len(rows))] + local_position += 1 + + def mark_consumed(self, samples: int) -> None: + self.consumed += int(samples) + + def state_dict(self) -> dict[str, int]: + return {"consumed": self.consumed} + + def load_state_dict(self, state: dict[str, int]) -> None: + self.consumed = int(state["consumed"]) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/action/flow_matching.py b/release-20261107/source/workspace_joint/mira/src/mira/action/flow_matching.py new file mode 100644 index 0000000000000000000000000000000000000000..c47ed4448b8fa2fbaa64050349a2eb82089f90ca --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/action/flow_matching.py @@ -0,0 +1,129 @@ +"""Action flow-matching path, losses, and deterministic Euler sampler.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import torch +from torch import Tensor, nn + + +@dataclass(frozen=True) +class ActionFlowBatch: + noisy_action: Tensor + target_velocity: Tensor + flow_time: Tensor + noise: Tensor + + +def sample_flow_batch( + clean_action: Tensor, + *, + alpha: float = 1.5, + scale: float = 0.999, + generator: torch.Generator | None = None, +) -> ActionFlowBatch: + """Sample ``t=(1-Beta(alpha,1))*scale`` once per trajectory. + + Beta(alpha, 1) has the exact inverse CDF ``u ** (1/alpha)``. Using it avoids a + distribution implementation that cannot consume a caller-owned generator. + """ + if clean_action.ndim != 3: + raise ValueError(f"Expected clean action [B,H,D], got {tuple(clean_action.shape)}") + uniform = torch.rand( + clean_action.shape[0], + 1, + 1, + device=clean_action.device, + dtype=torch.float32, + generator=generator, + ) + beta = uniform.pow(1.0 / alpha) + flow_time = (1.0 - beta) * scale + noise = torch.randn( + clean_action.shape, + device=clean_action.device, + dtype=torch.float32, + generator=generator, + ) + clean = clean_action.float() + noisy = (1.0 - flow_time) * noise + flow_time * clean + return ActionFlowBatch( + noisy_action=noisy, + target_velocity=clean - noise, + flow_time=flow_time, + noise=noise, + ) + + +def masked_action_flow_loss( + prediction: Tensor, + target: Tensor, + valid: Tensor, +) -> tuple[Tensor, dict[str, Tensor]]: + if prediction.shape != target.shape or prediction.shape != valid.shape: + raise ValueError( + f"Action loss shape mismatch: {prediction.shape=}, {target.shape=}, {valid.shape=}" + ) + squared = (prediction.float() - target.float()).square() + mask = valid.to(dtype=squared.dtype) + denominator = mask.sum().clamp_min(1) + total = (squared * mask).sum() / denominator + groups = { + "left_arm": slice(0, 6), + "left_gripper": slice(6, 7), + "right_arm": slice(7, 13), + "right_gripper": slice(13, 14), + } + metrics: dict[str, Tensor] = {} + for name, group in groups.items(): + group_mask = mask[..., group] + metrics[name] = ( + (squared[..., group] * group_mask).sum() / group_mask.sum().clamp_min(1) + ).detach() + return total, metrics + + +@torch.inference_mode() +def sample_action_euler( + model: nn.Module, + *, + conditions: dict[str, Tensor], + batch_size: int, + horizon: int = 20, + action_dim: int = 14, + steps: int = 10, + generator: torch.Generator | None = None, + return_attention: bool = False, +) -> tuple[Tensor, dict[str, Tensor]]: + if steps <= 0: + raise ValueError("Euler steps must be positive") + device = conditions["current_latent"].device + action = torch.randn( + batch_size, + horizon, + action_dim, + device=device, + dtype=torch.float32, + generator=generator, + ) + diagnostics: dict[str, Tensor] = {} + for index in range(steps): + start = index / steps + end = (index + 1) / steps + flow_time = torch.full((batch_size, 1, 1), start, device=device, dtype=torch.float32) + output = model( + action, + flow_time, + return_attention=return_attention and index == steps - 1, + **conditions, + ) + velocity = output["velocity"].float() + action = action + (end - start) * velocity + if return_attention and index == steps - 1: + diagnostics = { + key: value + for key, value in output.items() + if key.startswith("attention/") + } + return action, diagnostics diff --git a/release-20261107/source/workspace_joint/mira/src/mira/action/joint_action_flow.py b/release-20261107/source/workspace_joint/mira/src/mira/action/joint_action_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..23f4e83711d7cdc52240e4e9f22c9b17adcafc5a --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/action/joint_action_flow.py @@ -0,0 +1,458 @@ +"""Joint 20x14 bimanual action-flow Transformer.""" + +from __future__ import annotations + +import math +from typing import Any + +import torch +import torch.nn.functional as F +import torch.utils.checkpoint +from torch import Tensor, nn + +from mira.ml.attention import QKLayerNorm, SelfAttention, SelfAttentionConfig +from mira.world_model.layers.arm_state_encoder import ArmStateEncoder +from mira.world_model.layers.timestep_encoder import get_timestep_embedding + +from .config import ActionHeadConfig + + +class ActionCrossAttention(nn.Module): + """QK-normalized cross-attention with optional attention-mass diagnostics.""" + + def __init__(self, dim: int, heads: int, kv_heads: int) -> None: + super().__init__() + if dim % heads or heads % kv_heads: + raise ValueError("Invalid action cross-attention dimensions") + self.dim = dim + self.heads = heads + self.kv_heads = kv_heads + self.head_dim = dim // heads + kv_dim = kv_heads * self.head_dim + self.q_proj = nn.Linear(dim, dim, bias=False) + self.k_proj = nn.Linear(dim, kv_dim, bias=False) + self.v_proj = nn.Linear(dim, kv_dim, bias=False) + self.out_proj = nn.Linear(dim, dim, bias=False) + self.q_norm = QKLayerNorm((heads, self.head_dim)) + self.k_norm = QKLayerNorm((kv_heads, self.head_dim)) + + def forward( + self, + query: Tensor, + context: Tensor, + context_mask: Tensor, + *, + diagnostic_split: int | None = None, + ) -> tuple[Tensor, dict[str, Tensor]]: + batch, query_length, _ = query.shape + context_length = context.shape[1] + q = self.q_norm(self.q_proj(query).view(batch, query_length, self.heads, self.head_dim)) + k = self.k_norm(self.k_proj(context).view(batch, context_length, self.kv_heads, self.head_dim)) + v = self.v_proj(context).view(batch, context_length, self.kv_heads, self.head_dim) + q, k, v = (value.transpose(1, 2) for value in (q, k, v)) + mask = context_mask[:, None, None].to(torch.bool) + result = F.scaled_dot_product_attention( + q, + k, + v, + attn_mask=mask, + enable_gqa=self.heads != self.kv_heads, + ) + result = result.transpose(1, 2).contiguous().view(batch, query_length, self.dim) + diagnostics: dict[str, Tensor] = {} + if diagnostic_split is not None: + # Diagnostics are called only in validation. Avoid materialising this matrix in training. + if self.heads != self.kv_heads: + repeats = self.heads // self.kv_heads + k_for_scores = k.repeat_interleave(repeats, dim=1) + else: + k_for_scores = k + scores = torch.matmul(q.float(), k_for_scores.float().transpose(-2, -1)) + scores = scores / math.sqrt(self.head_dim) + scores = scores.masked_fill(~mask, -torch.inf) + attention = scores.softmax(dim=-1) + diagnostics["current"] = attention[..., :diagnostic_split].sum(dim=-1).mean().detach() + diagnostics["future"] = attention[..., diagnostic_split:].sum(dim=-1).mean().detach() + return self.out_proj(result), diagnostics + + +class ActionSwiGLU(nn.Module): + def __init__(self, dim: int, hidden_dim: int) -> None: + super().__init__() + self.value = nn.Linear(dim, hidden_dim, bias=False) + self.gate = nn.Linear(dim, hidden_dim, bias=False) + self.output = nn.Linear(hidden_dim, dim, bias=False) + + def forward(self, value: Tensor) -> Tensor: + return self.output(F.silu(self.value(value)) * self.gate(value)) + + +class ActionBlock(nn.Module): + def __init__(self, config: ActionHeadConfig) -> None: + super().__init__() + dim = config.hidden_dim + attention_config = SelfAttentionConfig( + embed_dim=dim, + num_heads=config.heads, + num_kv_heads=config.kv_heads, + gating=False, + qk_norm="layernorm", + ) + self.norms = nn.ModuleList( + [nn.LayerNorm(dim, elementwise_affine=False) for _ in range(4)] + ) + self.self_attention = SelfAttention(attention_config, causal=False) + self.world_attention = ActionCrossAttention(dim, config.heads, config.kv_heads) + self.task_attention = ActionCrossAttention(dim, config.heads, config.kv_heads) + self.ffn = ActionSwiGLU(dim, config.ffn_dim) + self.modulation = nn.Sequential(nn.SiLU(), nn.Linear(dim, 12 * dim)) + linear = self.modulation[-1] + assert isinstance(linear, nn.Linear) + nn.init.zeros_(linear.weight) + nn.init.zeros_(linear.bias) + gate_bias = math.atanh(0.1) + with torch.no_grad(): + for gate_index in (2, 5, 8, 11): + linear.bias[gate_index * dim : (gate_index + 1) * dim].fill_(gate_bias) + + @staticmethod + def _adaln(value: Tensor, norm: nn.Module, shift: Tensor, scale: Tensor) -> Tensor: + return (1 + scale[:, None]) * norm(value) + shift[:, None] + + def forward( + self, + action: Tensor, + flow_condition: Tensor, + world_memory: Tensor, + world_mask: Tensor, + task_memory: Tensor, + task_mask: Tensor, + *, + return_attention: bool = False, + current_tokens: int = 324, + ) -> tuple[Tensor, dict[str, Tensor]]: + parameters = self.modulation(flow_condition).chunk(12, dim=-1) + sa_shift, sa_scale, sa_gate = parameters[0:3] + world_shift, world_scale, world_gate = parameters[3:6] + task_shift, task_scale, task_gate = parameters[6:9] + ffn_shift, ffn_scale, ffn_gate = parameters[9:12] + + update = self.self_attention(self._adaln(action, self.norms[0], sa_shift, sa_scale)) + action = action + torch.tanh(sa_gate[:, None]) * update + + update, diagnostics = self.world_attention( + self._adaln(action, self.norms[1], world_shift, world_scale), + world_memory, + world_mask, + diagnostic_split=current_tokens if return_attention else None, + ) + action = action + torch.tanh(world_gate[:, None]) * update + + update, _ = self.task_attention( + self._adaln(action, self.norms[2], task_shift, task_scale), + task_memory, + task_mask, + ) + action = action + torch.tanh(task_gate[:, None]) * update + + update = self.ffn(self._adaln(action, self.norms[3], ffn_shift, ffn_scale)) + action = action + torch.tanh(ffn_gate[:, None]) * update + return action, diagnostics + + +class LatentMemoryAdapter(nn.Module): + def __init__(self, config: ActionHeadConfig) -> None: + super().__init__() + dim = config.hidden_dim + self.config = config + self.projector = nn.Sequential( + nn.LayerNorm(config.latent_dim), + nn.Linear(config.latent_dim, 512), + nn.SiLU(), + nn.Linear(512, dim), + ) + self.source_embedding = nn.Parameter(torch.randn(2, dim) * 0.02) + self.view_embedding = nn.Parameter(torch.randn(3, dim) * 0.02) + self.future_time_embedding = nn.Parameter(torch.randn(config.future_steps, dim) * 0.02) + self.coordinate_projection = nn.Linear(16, dim, bias=False) + self.null_future = nn.Parameter(torch.randn(1, 1, dim) * 0.02) + + @staticmethod + def _coordinates(height: int, width: int, device: torch.device) -> Tensor: + y = torch.linspace(-1, 1, height, device=device) + x = torch.linspace(-1, 1, width, device=device) + yy, xx = torch.meshgrid(y, x, indexing="ij") + features = [] + for frequency in (1.0, 2.0, 4.0, 8.0): + features.extend( + [ + torch.sin(math.pi * frequency * yy), + torch.cos(math.pi * frequency * yy), + torch.sin(math.pi * frequency * xx), + torch.cos(math.pi * frequency * xx), + ] + ) + return torch.stack(features, dim=-1).reshape(height * width, 16) + + def forward( + self, + current: Tensor, + future: Tensor, + *, + future_drop_mask: Tensor, + ) -> tuple[Tensor, Tensor, dict[str, Tensor]]: + config = self.config + expected_current = (3, config.latent_dim, config.current_height, config.current_width) + expected_future = ( + 3, + config.future_steps, + config.latent_dim, + config.future_height, + config.future_width, + ) + if tuple(current.shape[1:]) != expected_current: + raise ValueError(f"Expected current [B,{expected_current}], got {tuple(current.shape)}") + if tuple(future.shape[1:]) != expected_future: + raise ValueError(f"Expected future [B,{expected_future}], got {tuple(future.shape)}") + batch = current.shape[0] + if future_drop_mask.shape != (batch,): + raise ValueError(f"future_drop_mask must be [B], got {tuple(future_drop_mask.shape)}") + + current_tokens = current.permute(0, 1, 3, 4, 2).reshape(batch, 3, -1, config.latent_dim) + current_tokens = self.projector(current_tokens) + current_coord = self.coordinate_projection( + self._coordinates(config.current_height, config.current_width, current.device) + ) + current_tokens = ( + current_tokens + + self.source_embedding[0] + + self.view_embedding[None, :, None] + + current_coord[None, None] + ).reshape(batch, -1, config.hidden_dim) + + future_tokens = future.permute(0, 1, 2, 4, 5, 3).reshape( + batch, 3, config.future_steps, -1, config.latent_dim + ) + future_tokens = self.projector(future_tokens) + future_coord = self.coordinate_projection( + self._coordinates(config.future_height, config.future_width, future.device) + ) + future_tokens = ( + future_tokens + + self.source_embedding[1] + + self.view_embedding[None, :, None, None] + + self.future_time_embedding[None, None, :, None] + + future_coord[None, None, None] + ).reshape(batch, -1, config.hidden_dim) + + current_count = current_tokens.shape[1] + future_count = future_tokens.shape[1] + current_mask = torch.ones(batch, current_count, dtype=torch.bool, device=current.device) + future_mask = torch.ones(batch, future_count, dtype=torch.bool, device=current.device) + if bool(future_drop_mask.any()): + future_tokens = future_tokens.clone() + future_mask = future_mask.clone() + future_tokens[future_drop_mask] = self.null_future.to(future_tokens.dtype).expand( + int(future_drop_mask.sum()), future_count, -1 + ) + future_mask[future_drop_mask] = False + future_mask[future_drop_mask, 0] = True + memory = torch.cat([current_tokens, future_tokens], dim=1) + mask = torch.cat([current_mask, future_mask], dim=1) + return memory, mask, { + "current_tokens": torch.tensor(current_count, device=current.device), + "future_tokens": torch.tensor(future_count, device=current.device), + "null_future_count": future_drop_mask.sum(), + } + + +class JointBimanualActionFlow(nn.Module): + def __init__(self, config: ActionHeadConfig) -> None: + super().__init__() + self.config = config + dim = config.hidden_dim + self.latent_memory = LatentMemoryAdapter(config) + self.state_encoder = ArmStateEncoder( + hidden_dim=config.state_dim, + layers=2, + heads=8, + text_dim=config.text_dim, + text_kv_heads=4, + use_action_history=False, + ) + # The locked World branch does not condition this encoder on action history, so its + # compatibility-only BOS tensor is structurally unreachable. Keep the exact copied value + # in Action checkpoints, but do not put a dead parameter in AdamW/EMA: lazy optimizer state + # for such a tensor makes otherwise strict distributed resume ambiguous. + self.state_encoder.bos_action.requires_grad_(False) + self.state_projection = nn.Linear(config.state_dim, dim) + self.state_role_embedding = nn.Parameter(torch.randn(3, dim) * 0.02) + self.text_adapter = nn.Sequential( + nn.LayerNorm(config.text_dim), + nn.Linear(config.text_dim, dim), + ) + self.action_input = nn.Linear(config.action_dim, dim) + self.action_type_embedding = nn.Parameter(torch.randn(1, 1, dim) * 0.02) + self.position_mlp = nn.Sequential( + nn.Linear(256, dim), + nn.SiLU(), + nn.Linear(dim, dim), + ) + self.flow_mlp = nn.Sequential( + nn.Linear(256, dim), + nn.SiLU(), + nn.Linear(dim, dim), + ) + self.blocks = nn.ModuleList([ActionBlock(config) for _ in range(config.layers)]) + self.output_norm = nn.LayerNorm(dim) + self.velocity_head = nn.Linear(dim, config.action_dim) + self.external_activation_checkpointing = False + nn.init.zeros_(self.velocity_head.weight) + nn.init.zeros_(self.velocity_head.bias) + + def load_state_encoder_copy(self, state_dict: dict[str, Tensor]) -> None: + self.state_encoder.load_state_dict(state_dict, strict=True) + + def _state_memory( + self, + joint_target_history: Tensor, + action_history: Tensor, + history_valid: Tensor, + text_hidden: Tensor, + text_mask: Tensor, + ) -> tuple[Tensor, Tensor]: + state = self.state_encoder( + joint_target_history, + action_history, + history_valid, + text_hidden, + text_mask, + ) + left = self.state_projection(state["left_tokens"]) + self.state_role_embedding[0] + right = self.state_projection(state["right_tokens"]) + self.state_role_embedding[2] + global_state = self.state_projection(state["global"][:, None]) + self.state_role_embedding[1] + memory = torch.cat([left, right, global_state], dim=1) + mask = torch.cat( + [history_valid, history_valid, torch.ones_like(history_valid[:, :1])], + dim=1, + ) + return memory, mask + + def forward( + self, + noisy_action: Tensor, + flow_time: Tensor, + *, + current_latent: Tensor, + future_latent: Tensor, + joint_target_history: Tensor, + action_history: Tensor, + history_valid: Tensor, + text_hidden: Tensor, + text_mask: Tensor, + future_drop_mask: Tensor | None = None, + return_attention: bool = False, + ) -> dict[str, Tensor]: + config = self.config + batch = noisy_action.shape[0] + if noisy_action.shape[1:] != (config.horizon, config.action_dim): + raise ValueError(f"Expected noisy action [B,20,14], got {tuple(noisy_action.shape)}") + if flow_time.shape != (batch, 1, 1): + raise ValueError(f"Expected one flow time per trajectory [B,1,1], got {flow_time.shape}") + if future_drop_mask is None: + future_drop_mask = ( + torch.rand(batch, device=noisy_action.device) < config.future_drop_prob + if self.training + else torch.zeros(batch, dtype=torch.bool, device=noisy_action.device) + ) + world_memory, world_mask, memory_diagnostics = self.latent_memory( + current_latent, + future_latent, + future_drop_mask=future_drop_mask, + ) + state_memory, state_mask = self._state_memory( + joint_target_history, + action_history, + history_valid, + text_hidden, + text_mask, + ) + text_memory = self.text_adapter(text_hidden.to(self.text_adapter[1].weight.dtype)) + task_memory = torch.cat([state_memory, text_memory], dim=1) + task_mask = torch.cat([state_mask, text_mask], dim=1) + + position = torch.arange( + 1, config.horizon + 1, device=noisy_action.device, dtype=torch.float32 + ) / config.horizon + position = self.position_mlp(get_timestep_embedding(position * 1000, 256)) + action = ( + self.action_input(noisy_action.to(self.action_input.weight.dtype)) + + position[None] + + self.action_type_embedding + ) + flow_condition = self.flow_mlp( + get_timestep_embedding(flow_time[:, 0, 0] * 1000, 256) + ) + attention_current = torch.zeros((), device=noisy_action.device) + attention_future = torch.zeros((), device=noisy_action.device) + for block in self.blocks: + if ( + self.training + and config.activation_checkpointing + and not self.external_activation_checkpointing + and not return_attention + ): + def run(value: Tensor, block: ActionBlock = block) -> Tensor: + return block( + value, + flow_condition, + world_memory, + world_mask, + task_memory, + task_mask, + )[0] + + action = torch.utils.checkpoint.checkpoint(run, action, use_reentrant=False) + else: + action, diagnostics = block( + action, + flow_condition, + world_memory, + world_mask, + task_memory, + task_mask, + return_attention=return_attention, + current_tokens=3 * config.current_height * config.current_width, + ) + if diagnostics: + attention_current += diagnostics["current"] + attention_future += diagnostics["future"] + output: dict[str, Tensor] = { + "velocity": self.velocity_head(self.output_norm(action)), + "future_drop_count": memory_diagnostics["null_future_count"], + } + if return_attention: + output["attention/current_mass"] = attention_current / len(self.blocks) + output["attention/future_mass"] = attention_future / len(self.blocks) + return output + + def parameter_report(self) -> dict[str, Any]: + modules = { + "latent_memory": self.latent_memory, + "state_encoder_copy": self.state_encoder, + "state_projection": self.state_projection, + "text_adapter": self.text_adapter, + "action_transformer": self.blocks, + "action_io": nn.ModuleList( + [self.action_input, self.position_mlp, self.flow_mlp, self.output_norm, self.velocity_head] + ), + } + report = { + name: sum(parameter.numel() for parameter in module.parameters()) + for name, module in modules.items() + } + report["trainable"] = sum( + parameter.numel() for parameter in self.parameters() if parameter.requires_grad + ) + report["total"] = sum(parameter.numel() for parameter in self.parameters()) + return report diff --git a/release-20261107/source/workspace_joint/mira/src/mira/action/visualization.py b/release-20261107/source/workspace_joint/mira/src/mira/action/visualization.py new file mode 100644 index 0000000000000000000000000000000000000000..83fcdcff0d85dc4b37a5452ca1cc286f88bd2a87 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/action/visualization.py @@ -0,0 +1,98 @@ +"""Durable local trajectory cases for Action-stage validation.""" + +from __future__ import annotations + +import json +import os +import re +from pathlib import Path +from typing import Any + +import matplotlib +import numpy as np +from torch import Tensor + +matplotlib.use("Agg") +from matplotlib import pyplot as plt # noqa: E402 + + +def _safe_name(value: str) -> str: + return re.sub(r"[^a-zA-Z0-9_.-]+", "-", value)[:80].strip("-") or "case" + + +def save_action_trajectory_case( + output_dir: str | Path, + *, + case_index: int, + prediction: Tensor, + target: Tensor, + action_mean: Tensor, + action_std: Tensor, + metadata: dict[str, Any], + attention: dict[str, Tensor], + condition: str = "predicted_future_10", +) -> None: + """Save denormalized 20x14 data and a compact fixed-case PNG, atomically.""" + root = Path(output_dir) + root.mkdir(parents=True, exist_ok=True) + stem = ( + f"case-{case_index:02d}-{_safe_name(str(metadata['task']))}-" + f"{_safe_name(condition)}" + ) + prediction_raw = ( + prediction.detach().float().cpu() * action_std.detach().float().cpu() + + action_mean.detach().float().cpu() + ).numpy() + target_raw = ( + target.detach().float().cpu() * action_std.detach().float().cpu() + + action_mean.detach().float().cpu() + ).numpy() + npz_path = root / f"{stem}.npz" + npz_tmp = root / f".{stem}.npz.tmp" + with npz_tmp.open("wb") as handle: + np.savez_compressed( + handle, + prediction=prediction_raw, + target=target_raw, + action_source_idx=np.asarray(metadata["action_source_idx"], dtype=np.int32), + ) + os.replace(npz_tmp, npz_path) + + record = { + "window_id": metadata["window_id"], + "task": metadata["task"], + "domain": metadata["domain"], + "condition": condition, + "sampler": "euler", + "attention": {key: float(value.detach().float().cpu()) for key, value in attention.items()}, + } + json_path = root / f"{stem}.json" + json_tmp = root / f".{stem}.json.tmp" + json_tmp.write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8") + os.replace(json_tmp, json_path) + + figure, axes = plt.subplots(2, 2, figsize=(13, 7), sharex=True) + time = np.arange(20) + groups = ( + ("Left arm", slice(0, 6)), + ("Left gripper", slice(6, 7)), + ("Right arm", slice(7, 13)), + ("Right gripper", slice(13, 14)), + ) + for axis, (title, dimensions) in zip(axes.flat, groups, strict=True): + for dimension in range(dimensions.start, dimensions.stop): + axis.plot(time, target_raw[:, dimension], "-", alpha=0.8) + axis.plot(time, prediction_raw[:, dimension], "--", alpha=0.8) + axis.set_title(title) + axis.grid(alpha=0.2) + axes[1, 0].set_xlabel("20 Hz action step") + axes[1, 1].set_xlabel("20 Hz action step") + figure.suptitle( + f"{metadata['task']} / {metadata['domain']} — solid target, dashed prediction" + ) + figure.tight_layout() + png_path = root / f"{stem}.png" + png_tmp = root / f".{stem}.png.tmp" + figure.savefig(png_tmp, format="png", dpi=130) + plt.close(figure) + os.replace(png_tmp, png_path) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/action/world_checkpoint.py b/release-20261107/source/workspace_joint/mira/src/mira/action/world_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..18c82197670ddb3d584e29041a491c22cb753f7c --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/action/world_checkpoint.py @@ -0,0 +1,106 @@ +"""Strict standalone loading of online/EMA branches from a World DCP checkpoint.""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path +from typing import Any + +import torch +import torch.distributed.checkpoint as dcp +from torch import Tensor + +from mira.training.ema import ModelEMA +from mira.world_model.bihub_config import BiHubWorldModelConfig +from mira.world_model.bihub_latent_world_model import BiHubLatentWorldModel + + +def hash_tensor_state(state: dict[str, Tensor]) -> str: + digest = hashlib.sha256() + for name, value in sorted(state.items()): + tensor = value.detach().cpu().contiguous() + digest.update(name.encode()) + digest.update(str(tuple(tensor.shape)).encode()) + digest.update(str(tensor.dtype).encode()) + digest.update(tensor.view(torch.uint8).numpy()) + return digest.hexdigest() + + +def checkpoint_model_config(checkpoint: str | Path) -> tuple[BiHubWorldModelConfig, dict[str, Any]]: + checkpoint = Path(checkpoint).expanduser().resolve() + metadata = json.loads((checkpoint / "trainer_state.json").read_text(encoding="utf-8")) + config = BiHubWorldModelConfig.model_validate(metadata["resolved_config"]["model"]) + return config, metadata + + +def load_world_online_and_ema( + checkpoint: str | Path, +) -> tuple[BiHubLatentWorldModel, ModelEMA, dict[str, Any]]: + """Load canonical model and EMA states onto CPU without optimizer/training state.""" + checkpoint = Path(checkpoint).expanduser().resolve() + config, metadata = checkpoint_model_config(checkpoint) + model = BiHubLatentWorldModel(config) + ema = ModelEMA(model, decay=0.999, unbias=False) + # The World trainer creates EMA after wrapping each block with activation checkpointing. + # DCP canonicalizes the online model keys, while the plain EMA dictionary retains the wrapper + # component in its names. Recreate that exact storage schema, then strip it after loading. + wrapped_ema_state: dict[str, Tensor] = {} + for name, value in ema.state.items(): + parts = name.split(".") + if len(parts) >= 4 and parts[:2] == ["world_model", "blocks"]: + name = ".".join(parts[:3] + ["_checkpoint_wrapped_module"] + parts[3:]) + wrapped_ema_state[name] = value + state = { + "model": model.state_dict(), + "ema": {"state": wrapped_ema_state, "count": ema.count}, + } + dcp.load(state, checkpoint_id=checkpoint / "distributed") + model.load_state_dict(state["model"], strict=True) + canonical_ema_state = {} + for name, value in state["ema"]["state"].items(): + name = name.replace("._checkpoint_wrapped_module.", ".") + canonical_ema_state[name] = value + ema.load_state_dict({"state": canonical_ema_state, "count": state["ema"]["count"]}) + report = model.parameter_report() + if int(report["total"]) != 1_397_471_023: + raise ValueError(f"Unexpected World parameter count: {report}") + return model, ema, metadata + + +def apply_ema_to_model(model: BiHubLatentWorldModel, ema: ModelEMA) -> None: + with torch.no_grad(): + named = dict(model.named_parameters()) + if set(ema.state) != { + name for name, parameter in named.items() if parameter.requires_grad and parameter.is_floating_point() + }: + raise ValueError("World EMA parameter keys do not exactly match the online model") + for name, value in ema.state.items(): + named[name].copy_(value.to(device=named[name].device, dtype=named[name].dtype)) + + +def selected_state_encoder( + model: BiHubLatentWorldModel, + ema: ModelEMA, + branch: str, +) -> dict[str, Tensor]: + if branch == "online": + return { + name: value.detach().cpu().clone() + for name, value in model.state_encoder.state_dict().items() + } + if branch != "ema": + raise ValueError(f"Unknown World branch: {branch}") + prefix = "state_encoder." + output = { + name[len(prefix) :]: value.detach().cpu().clone() + for name, value in ema.state.items() + if name.startswith(prefix) + } + expected = set(model.state_encoder.state_dict()) + if set(output) != expected: + raise ValueError( + f"EMA state-encoder keys mismatch: missing={sorted(expected-set(output))[:5]} " + f"extra={sorted(set(output)-expected)[:5]}" + ) + return output diff --git a/release-20261107/source/workspace_joint/mira/src/mira/action_v6/__init__.py b/release-20261107/source/workspace_joint/mira/src/mira/action_v6/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..45bd9b4e8042bec16bfa434c92d6249fe0b1b9cd --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/action_v6/__init__.py @@ -0,0 +1,17 @@ +"""BiHub-WAM v6 transition-conditioned bimanual action policy.""" + +from .model import ( + ActionV6Batch, + BiHubActionFlow, + BiHubWAMActionStage, + TransitionConditioner, + monotonic_transition_bias, +) + +__all__ = [ + "ActionV6Batch", + "BiHubActionFlow", + "BiHubWAMActionStage", + "TransitionConditioner", + "monotonic_transition_bias", +] diff --git a/release-20261107/source/workspace_joint/mira/src/mira/action_v6/layers.py b/release-20261107/source/workspace_joint/mira/src/mira/action_v6/layers.py new file mode 100644 index 0000000000000000000000000000000000000000..5f4406f52be20704fcbe2d757b13b0ed6a5d6ff0 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/action_v6/layers.py @@ -0,0 +1,127 @@ +"""Small attention primitives with explicit Q/K normalization and routing.""" + +from __future__ import annotations + +import math + +import torch +from torch import Tensor, nn +from torch.nn import functional as F + + +class RMSNorm(nn.Module): + def __init__(self, width: int, eps: float = 1.0e-6) -> None: + super().__init__() + self.weight = nn.Parameter(torch.ones(width)) + self.eps = eps + + def forward(self, value: Tensor) -> Tensor: + dtype = value.dtype + normalized = value.float() * torch.rsqrt(value.float().square().mean(-1, keepdim=True) + self.eps) + return (normalized * self.weight.float()).to(dtype) + + +class QKNormAttention(nn.Module): + """MHA/cross-attention whose graph is explicit enough to audit.""" + + def __init__(self, width: int, heads: int, *, output_bias: bool = False) -> None: + super().__init__() + if width % heads: + raise ValueError("attention width must be divisible by heads") + self.width = width + self.heads = heads + self.head_dim = width // heads + self.q_proj = nn.Linear(width, width, bias=False) + self.k_proj = nn.Linear(width, width, bias=False) + self.v_proj = nn.Linear(width, width, bias=False) + self.out_proj = nn.Linear(width, width, bias=output_bias) + self.q_scale = nn.Parameter(torch.ones(heads, self.head_dim)) + self.k_scale = nn.Parameter(torch.ones(heads, self.head_dim)) + + @staticmethod + def _rms(value: Tensor, scale: Tensor) -> Tensor: + dtype = value.dtype + value = value.float() * torch.rsqrt(value.float().square().mean(-1, keepdim=True) + 1.0e-6) + return (value * scale.float()).to(dtype) + + def forward(self, query: Tensor, memory: Tensor | None = None, bias: Tensor | None = None) -> Tensor: + memory = query if memory is None else memory + batch, q_length, _ = query.shape + k_length = memory.shape[1] + q = self.q_proj(query).reshape(batch, q_length, self.heads, self.head_dim) + k = self.k_proj(memory).reshape(batch, k_length, self.heads, self.head_dim) + v = self.v_proj(memory).reshape(batch, k_length, self.heads, self.head_dim) + q = self._rms(q, self.q_scale).transpose(1, 2) + k = self._rms(k, self.k_scale).transpose(1, 2) + v = v.transpose(1, 2) + attention_bias = None + if bias is not None: + if bias.ndim == 2: + attention_bias = bias[None, None] + elif bias.ndim == 3: + attention_bias = bias[:, None] + elif bias.ndim == 4: + attention_bias = bias + else: + raise ValueError("attention bias must have rank 2, 3, or 4") + if attention_bias.shape[-2:] != (q_length, k_length): + raise ValueError("attention bias shape does not match query/memory") + attention_bias = attention_bias.to(dtype=q.dtype, device=q.device) + value = F.scaled_dot_product_attention(q, k, v, attn_mask=attention_bias, dropout_p=0.0) + return self.out_proj(value.transpose(1, 2).contiguous().reshape(batch, q_length, self.width)) + + +class SwiGLU(nn.Module): + def __init__(self, width: int, hidden: int) -> None: + super().__init__() + self.in_proj = nn.Linear(width, 2 * hidden, bias=False) + self.out_proj = nn.Linear(hidden, width, bias=False) + + def forward(self, value: Tensor) -> Tensor: + gate, content = self.in_proj(value).chunk(2, dim=-1) + return self.out_proj(F.silu(gate) * content) + + +class ResidualAttentionFFN(nn.Module): + def __init__(self, width: int, heads: int, hidden: int, *, gate_init: float = 1.0) -> None: + super().__init__() + self.query_norm = RMSNorm(width) + self.memory_norm = RMSNorm(width) + self.attention = QKNormAttention(width, heads) + self.ffn_norm = RMSNorm(width) + self.ffn = SwiGLU(width, hidden) + # FSDP2 does not support scalar parameters; a one-element tensor has + # identical broadcasting semantics and is shardable/checkpointable. + self.attention_gate = nn.Parameter(torch.tensor([float(gate_init)])) + self.ffn_gate = nn.Parameter(torch.tensor([float(gate_init)])) + + def forward(self, query: Tensor, memory: Tensor, bias: Tensor | None = None) -> Tensor: + query = query + self.attention_gate * self.attention( + self.query_norm(query), self.memory_norm(memory), bias + ) + return query + self.ffn_gate * self.ffn(self.ffn_norm(query)) + + +class ResidualCrossAttention(nn.Module): + """A plain pre-norm residual attention used by the fixed Action-block graph.""" + + def __init__(self, width: int, heads: int) -> None: + super().__init__() + self.query_norm = RMSNorm(width) + self.memory_norm = RMSNorm(width) + self.attention = QKNormAttention(width, heads) + + def forward(self, query: Tensor, memory: Tensor, bias: Tensor | None = None) -> Tensor: + return query + self.attention(self.query_norm(query), self.memory_norm(memory), bias) + + +def fourier_time(value: Tensor, width: int) -> Tensor: + """Deterministic physical/flow time features before a learned projection.""" + if width % 2: + raise ValueError("Fourier width must be even") + frequencies = torch.exp( + torch.arange(width // 2, device=value.device, dtype=torch.float32) + * (-math.log(10_000.0) / max(width // 2 - 1, 1)) + ) + phase = value.float()[..., None] * frequencies * (2.0 * math.pi) + return torch.cat([phase.sin(), phase.cos()], dim=-1) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/action_v6/model.py b/release-20261107/source/workspace_joint/mira/src/mira/action_v6/model.py new file mode 100644 index 0000000000000000000000000000000000000000..6998b3d48eac79c39f78c70b288d03357b6a3e3b --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/action_v6/model.py @@ -0,0 +1,570 @@ +"""Exact v6 Action Head topology from the frozen experiment design.""" + +from __future__ import annotations + +from dataclasses import dataclass, fields +from typing import Any + +import torch +from torch import Tensor, nn + +from .layers import ( + QKNormAttention, + RMSNorm, + ResidualAttentionFFN, + ResidualCrossAttention, + SwiGLU, + fourier_time, +) + +VIEW_ORDER = ("left", "global", "right") +ARM_ORDER = ("left", "right") + + +@dataclass +class ActionV6Batch: + z_current: Tensor + z_future_cond: Tensor + state_history: Tensor + state_valid_mask: Tensor + action_gt: Tensor + action_valid_mask: Tensor + future_source: Tensor | None = None + + def to(self, *args: Any, **kwargs: Any) -> "ActionV6Batch": + values: dict[str, Any] = {} + for field in fields(self): + value = getattr(self, field.name) + values[field.name] = value.to(*args, **kwargs) if isinstance(value, Tensor) else value + return ActionV6Batch(**values) + + +class DirectionalPairBuilder(nn.Module): + """Build source/target/signed-delta memories for all 30 directed transitions.""" + + def __init__(self, width: int, delta_scale: Tensor) -> None: + super().__init__() + if tuple(delta_scale.shape) != (3, 10, 32): + raise ValueError("delta_scale must be [3,10,32]") + if not torch.isfinite(delta_scale).all() or bool((delta_scale < 1.0e-4).any()): + raise ValueError("delta_scale must be finite and clamped to >=1e-4") + self.width = width + self.register_buffer("delta_scale", delta_scale.float().clone(), persistent=True) + self.src_norm = RMSNorm(32) + self.tgt_norm = RMSNorm(32) + self.src_proj = nn.Linear(32, width, bias=False) + self.tgt_proj = nn.Linear(32, width, bias=False) + self.delta_proj = nn.Linear(32, width, bias=False) + self.type_embedding = nn.Parameter(torch.randn(3, width) * 0.02) + self.view_embedding = nn.Parameter(torch.randn(3, width) * 0.02) + self.interval_embedding = nn.Parameter(torch.randn(10, width) * 0.02) + self.row_embedding = nn.Parameter(torch.randn(9, width) * 0.02) + self.column_embedding = nn.Parameter(torch.randn(12, width) * 0.02) + self.time_projection = nn.Linear(64, width, bias=False) + + @staticmethod + def _flatten(value: Tensor) -> Tensor: + return value.permute(0, 1, 2, 4, 5, 3).reshape(value.shape[0], 3, 10, 108, 32) + + def forward_pairs(self, source: Tensor, target: Tensor) -> Tensor: + expected = (3, 10, 32, 9, 12) + if source.ndim != 6 or tuple(source.shape[1:]) != expected: + raise ValueError("transition source must be [B,3,10,32,9,12]") + if target.shape != source.shape: + raise ValueError("transition source/target shapes differ") + source = self._flatten(source) + target = self._flatten(target) + scale = self.delta_scale[None, :, :, None].to(source.device) + delta = (target.float() - source.float()) / scale + source_tokens = self.src_proj(self.src_norm(source)) + self.type_embedding[0] + target_tokens = self.tgt_proj(self.tgt_norm(target)) + self.type_embedding[1] + delta_tokens = self.delta_proj(delta.to(self.delta_proj.weight.dtype)) + self.type_embedding[2] + tokens = torch.cat([source_tokens, target_tokens, delta_tokens], dim=3) + + rows = self.row_embedding[:, None].expand(9, 12, -1).reshape(108, self.width) + columns = self.column_embedding[None].expand(9, 12, -1).reshape(108, self.width) + coordinates = (rows + columns).repeat(3, 1) + physical = (torch.arange(10, device=tokens.device, dtype=torch.float32) + 0.5) / 10.0 + time = self.time_projection(fourier_time(physical, 64)) + tokens = tokens + coordinates[None, None, None] + tokens = tokens + self.view_embedding[None, :, None, None] + tokens = tokens + self.interval_embedding[None, None, :, None] + tokens = tokens + time[None, None, :, None] + return tokens + + def forward(self, z_current: Tensor, z_future: Tensor) -> Tensor: + if z_current.ndim != 6 or tuple(z_current.shape[1:]) != (3, 1, 32, 9, 12): + raise ValueError(f"z_current must be [B,3,1,32,9,12], got {tuple(z_current.shape)}") + if z_future.ndim != 6 or tuple(z_future.shape[1:]) != (3, 10, 32, 9, 12): + raise ValueError(f"z_future must be [B,3,10,32,9,12], got {tuple(z_future.shape)}") + if z_current.shape[0] != z_future.shape[0]: + raise ValueError("current/future batch sizes differ") + sequence = torch.cat([z_current, z_future], dim=2) + return self.forward_pairs(sequence[:, :, :-1], sequence[:, :, 1:]) + + +class QFormerLayer(nn.Module): + def __init__(self, width: int, heads: int, hidden: int) -> None: + super().__init__() + self.self_norm = RMSNorm(width) + self.self_attention = QKNormAttention(width, heads) + self.cross_norm = RMSNorm(width) + self.memory_norm = RMSNorm(width) + self.cross_attention = QKNormAttention(width, heads) + self.ffn_norm = RMSNorm(width) + self.ffn = SwiGLU(width, hidden) + + def forward(self, query: Tensor, memory: Tensor) -> Tensor: + query = query + self.self_attention(self.self_norm(query)) + query = query + self.cross_attention(self.cross_norm(query), self.memory_norm(memory)) + return query + self.ffn(self.ffn_norm(query)) + + +class ContinuousTransitionQFormer(nn.Module): + def __init__(self, width: int, queries: int, layers: int, heads: int, hidden: int) -> None: + super().__init__() + self.width = width + self.queries = queries + self.base_queries = nn.Parameter(torch.randn(queries, width) * 0.02) + self.view_embedding = nn.Parameter(torch.randn(3, width) * 0.02) + self.interval_embedding = nn.Parameter(torch.randn(10, width) * 0.02) + self.time_projection = nn.Linear(64, width, bias=False) + self.layers = nn.ModuleList([QFormerLayer(width, heads, hidden) for _ in range(layers)]) + self.final_norm = RMSNorm(width) + + def forward(self, pair_memory: Tensor) -> Tensor: + if pair_memory.ndim != 5 or tuple(pair_memory.shape[1:4]) != (3, 10, 324): + raise ValueError("pair memory must be [B,3,10,324,width]") + batch = pair_memory.shape[0] + physical = (torch.arange(10, device=pair_memory.device, dtype=torch.float32) + 0.5) / 10.0 + time = self.time_projection(fourier_time(physical, 64)) + query = self.base_queries[None, None, None] + query = query + self.view_embedding[None, :, None, None] + query = query + self.interval_embedding[None, None, :, None] + query = query + time[None, None, :, None] + query = query.expand(batch, -1, -1, -1, -1) + query = query.reshape(batch * 30, self.queries, self.width) + memory = pair_memory.reshape(batch * 30, 324, self.width) + for layer in self.layers: + query = layer(query, memory) + return self.final_norm(query).reshape(batch, 3, 10, self.queries, self.width) + + +class TransitionHub(nn.Module): + """Sequential global gather followed by shared local broadcasts.""" + + def __init__(self, width: int, heads: int, hidden: int, gate_init: float = 0.1) -> None: + super().__init__() + self.global_gather = ResidualAttentionFFN(width, heads, hidden, gate_init=gate_init) + self.local_broadcast = ResidualAttentionFFN(width, heads, hidden, gate_init=gate_init) + + def forward(self, transition: Tensor) -> Tensor: + if transition.ndim != 5 or transition.shape[1:4] != (3, 10, 4): + raise ValueError("transition must be [B,3,10,4,width]") + batch, _, intervals, queries, width = transition.shape + left, global_value, right = [ + value.reshape(batch * intervals, queries, width) + for value in transition.unbind(dim=1) + ] + global_value = self.global_gather(global_value, torch.cat([left, global_value, right], dim=1)) + local_query = torch.cat([left, right], dim=0) + local_memory = torch.cat( + [torch.cat([left, global_value], dim=1), torch.cat([global_value, right], dim=1)], dim=0 + ) + left, right = self.local_broadcast(local_query, local_memory).chunk(2, dim=0) + return torch.stack( + [ + left.reshape(batch, intervals, queries, width), + global_value.reshape(batch, intervals, queries, width), + right.reshape(batch, intervals, queries, width), + ], + dim=1, + ) + + +class TransitionConditioner(nn.Module): + def __init__( + self, + delta_scale: Tensor, + *, + width: int = 1024, + queries: int = 4, + qformer_layers: int = 2, + heads: int = 16, + hidden: int = 4096, + residual_gate_init: float = 0.1, + ) -> None: + super().__init__() + self.pair_builder = DirectionalPairBuilder(width, delta_scale) + self.qformer = ContinuousTransitionQFormer(width, queries, qformer_layers, heads, hidden) + self.hub = TransitionHub(width, heads, hidden, residual_gate_init) + + def forward(self, z_current: Tensor, z_future: Tensor) -> Tensor: + return self.hub(self.qformer(self.pair_builder(z_current, z_future))) + + def forward_pairs(self, source: Tensor, target: Tensor) -> Tensor: + return self.hub(self.qformer(self.pair_builder.forward_pairs(source, target))) + + +def monotonic_transition_bias( + *, horizon: int = 20, intervals: int = 10, queries: int = 4, sigma: float = 0.10 +) -> Tensor: + if (horizon, intervals, queries, sigma) != (20, 10, 4, 0.10): + raise ValueError("first formal Action v6 run locks H=20, K=10, Q=4, sigma=0.10") + action_time = (torch.arange(horizon, dtype=torch.float32) + 0.5) / horizon + transition_time = (torch.arange(intervals, dtype=torch.float32) + 0.5) / intervals + bias = -(action_time[:, None] - transition_time[None]) ** 2 / (2.0 * sigma**2) + return bias.repeat_interleave(queries, dim=1) + + +class FlowConditionedFFN(nn.Module): + def __init__(self, width: int, hidden: int) -> None: + super().__init__() + self.norm = RMSNorm(width) + self.condition = nn.Linear(width, 3 * width) + self.ffn = SwiGLU(width, hidden) + nn.init.zeros_(self.condition.weight) + nn.init.zeros_(self.condition.bias) + with torch.no_grad(): + self.condition.bias[2 * width :].fill_(-2.0) + + def forward(self, value: Tensor, flow: Tensor) -> Tensor: + shift, scale, gate = self.condition(flow).chunk(3, dim=-1) + normalized = self.norm(value) + conditioned = normalized * (1.0 + scale[:, None]) + shift[:, None] + return value + torch.sigmoid(gate[:, None]) * self.ffn(conditioned) + + +class ActionBlock(nn.Module): + """One audited action block; cross-arm paths exist only through global registers.""" + + def __init__( + self, width: int, heads: int, hidden: int, *, observable_global_flow_output: bool = True + ) -> None: + super().__init__() + self.local_self_norm = RMSNorm(width) + self.local_self_attention = QKNormAttention(width, heads) + self.global_self_norm = RMSNorm(width) + self.global_self_attention = QKNormAttention(width, heads) + self.local_transition = ResidualCrossAttention(width, heads) + self.global_transition = ResidualCrossAttention(width, heads) + self.action_gather = ResidualCrossAttention(width, heads) + self.action_broadcast = ResidualCrossAttention(width, heads) + self.local_flow_ffn = FlowConditionedFFN(width, hidden) + # The last block has no downstream consumer for post-broadcast Global + # tokens and the model intentionally has no Global output head. Keeping + # that final Global FFN would create permanently zero-gradient Action + # parameters. Earlier blocks retain it because their Global output is + # consumed by the next block. + self.global_flow_ffn = ( + FlowConditionedFFN(width, hidden) if observable_global_flow_output else None + ) + + def forward( + self, + left: Tensor, + global_value: Tensor, + right: Tensor, + transition: Tensor, + flow: Tensor, + monotonic_bias: Tensor, + ) -> tuple[Tensor, Tensor, Tensor]: + batch = left.shape[0] + local = torch.cat([left, right], dim=0) + local = local + self.local_self_attention(self.local_self_norm(local)) + left, right = local.chunk(2, dim=0) + global_value = global_value + self.global_self_attention(self.global_self_norm(global_value)) + + transition_left, transition_global, transition_right = transition.unbind(dim=1) + local_action = torch.cat([left[:, 1:], right[:, 1:]], dim=0) + local_memory = torch.cat( + [transition_left.flatten(1, 2), transition_right.flatten(1, 2)], dim=0 + ) + local_bias = monotonic_bias.to(device=left.device, dtype=left.dtype) + local_action = self.local_transition( + local_action, local_memory, local_bias[None].expand(2 * batch, -1, -1) + ) + left_action, right_action = local_action.chunk(2, dim=0) + global_action = self.global_transition( + global_value[:, 1:], transition_global.flatten(1, 2), local_bias + ) + + global_action = self.action_gather( + global_action, torch.cat([left_action, global_action, right_action], dim=1) + ) + local_action = torch.cat([left_action, right_action], dim=0) + local_memory = torch.cat( + [ + torch.cat([left_action, global_action], dim=1), + torch.cat([global_action, right_action], dim=1), + ], + dim=0, + ) + left_action, right_action = self.action_broadcast(local_action, local_memory).chunk(2, dim=0) + left = torch.cat([left[:, :1], left_action], dim=1) + global_value = torch.cat([global_value[:, :1], global_action], dim=1) + right = torch.cat([right[:, :1], right_action], dim=1) + + local = self.local_flow_ffn(torch.cat([left, right], dim=0), torch.cat([flow, flow], dim=0)) + left, right = local.chunk(2, dim=0) + if self.global_flow_ffn is not None: + global_value = self.global_flow_ffn(global_value, flow) + return left, global_value, right + + +class BiHubActionFlow(nn.Module): + def __init__( + self, + *, + width: int = 1024, + layers: int = 8, + heads: int = 16, + hidden: int = 4096, + horizon: int = 20, + ) -> None: + super().__init__() + if horizon != 20: + raise ValueError("Action v6 horizon is locked to 20") + self.width = width + self.horizon = horizon + self.state_local = nn.Linear(512, width, bias=False) + self.state_global = nn.Linear(512, width, bias=False) + self.action_input = nn.Linear(7, width, bias=False) + self.state_type = nn.Parameter(torch.randn(width) * 0.02) + self.action_type = nn.Parameter(torch.randn(width) * 0.02) + self.arm_embedding = nn.Parameter(torch.randn(2, width) * 0.02) + self.global_embedding = nn.Parameter(torch.randn(width) * 0.02) + self.action_position = nn.Parameter(torch.randn(horizon, width) * 0.02) + self.global_registers = nn.Parameter(torch.randn(horizon, width) * 0.02) + self.flow_projection = nn.Sequential( + nn.Linear(128, width), nn.SiLU(), nn.Linear(width, width) + ) + self.blocks = nn.ModuleList( + [ + ActionBlock( + width, + heads, + hidden, + observable_global_flow_output=index < layers - 1, + ) + for index in range(layers) + ] + ) + self.final_norm = RMSNorm(width) + self.output_left = nn.Linear(width, 7) + self.output_right = nn.Linear(width, 7) + nn.init.normal_(self.output_left.weight, std=1.0e-3) + nn.init.normal_(self.output_right.weight, std=1.0e-3) + nn.init.zeros_(self.output_left.bias) + nn.init.zeros_(self.output_right.bias) + self.register_buffer("monotonic_bias", monotonic_transition_bias(), persistent=True) + + def velocity( + self, + action_tau: Tensor, + tau: Tensor, + state_lgr: Tensor, + transitions: Tensor, + action_valid_mask: Tensor | None = None, + ) -> Tensor: + if action_tau.ndim != 4 or tuple(action_tau.shape[1:]) != (20, 2, 7): + raise ValueError("action_tau must be [B,20,2,7]") + batch = action_tau.shape[0] + if tau.shape not in {(batch,), (batch, 1), (batch, 1, 1, 1)}: + raise ValueError("tau must provide one shared scalar per sample") + if state_lgr.shape != (batch, 3, 512): + raise ValueError("state_lgr must be [B,3,512] in [left,global,right] order") + if transitions.shape != (batch, 3, 10, 4, self.width): + raise ValueError("transitions must be [B,3,10,4,1024]") + if action_valid_mask is not None and action_valid_mask.shape != (batch, 20): + raise ValueError("action_valid_mask must be [B,20]") + action_tau = action_tau.float() + left_action, right_action = action_tau.unbind(dim=2) + left_action = self.action_input(left_action) + self.action_type + self.arm_embedding[0] + right_action = self.action_input(right_action) + self.action_type + self.arm_embedding[1] + left_action = left_action + self.action_position + right_action = right_action + self.action_position + global_action = self.global_registers[None].expand(batch, -1, -1) + global_action = global_action + self.action_type + self.global_embedding + self.action_position + left_state = self.state_local(state_lgr[:, 0]) + self.state_type + self.arm_embedding[0] + global_state = self.state_global(state_lgr[:, 1]) + self.state_type + self.global_embedding + right_state = self.state_local(state_lgr[:, 2]) + self.state_type + self.arm_embedding[1] + left = torch.cat([left_state[:, None], left_action], dim=1) + global_value = torch.cat([global_state[:, None], global_action], dim=1) + right = torch.cat([right_state[:, None], right_action], dim=1) + flow = self.flow_projection(fourier_time(tau.reshape(batch), 128)) + for block in self.blocks: + left, global_value, right = block( + left, global_value, right, transitions, flow, self.monotonic_bias + ) + left_velocity = self.output_left(self.final_norm(left[:, 1:])) + right_velocity = self.output_right(self.final_norm(right[:, 1:])) + return torch.stack([left_velocity, right_velocity], dim=2).float() + + @torch.inference_mode() + def sample( + self, + noise: Tensor, + state_lgr: Tensor, + transitions: Tensor, + *, + steps: int = 10, + action_valid_mask: Tensor | None = None, + ) -> Tensor: + if steps != 10: + raise ValueError("formal Action v6 inference locks 10 Euler steps") + value = noise.float().clone() + batch = value.shape[0] + for index in range(steps): + tau = torch.full((batch,), index / steps, dtype=torch.float32, device=value.device) + velocity = self.velocity(value, tau, state_lgr, transitions, action_valid_mask) + if not torch.isfinite(velocity).all(): + raise FloatingPointError("non-finite action velocity") + value.add_(velocity, alpha=1.0 / steps) + if not torch.isfinite(value).all(): + raise FloatingPointError("non-finite sampled normalized action") + return value + + +class BiHubWAMActionStage(nn.Module): + """Training wrapper with an immutable World-v6 State Encoder.""" + + def __init__( + self, + *, + state_encoder: nn.Module, + delta_scale: Tensor, + action_mean: Tensor, + action_std: Tensor, + loss_mode: str = "masked_action_flow_mse_only", + transition_kwargs: dict[str, Any] | None = None, + action_kwargs: dict[str, Any] | None = None, + ) -> None: + super().__init__() + if tuple(action_mean.shape) != (14,) or tuple(action_std.shape) != (14,): + raise ValueError("action statistics must be 14D") + if not torch.isfinite(action_mean).all() or not torch.isfinite(action_std).all(): + raise ValueError("action statistics must be finite") + if bool((action_std < 1.0e-4).any()): + raise ValueError("action standard deviation must be clamped to >=1e-4") + if loss_mode not in { + "masked_action_flow_mse_only", + "masked_action_flow_mse_execute8_gripper_weighted", + }: + raise ValueError(f"unsupported Action loss mode: {loss_mode}") + self.loss_mode = loss_mode + self.state_encoder = state_encoder.eval() + self.state_encoder.requires_grad_(False) + self.transition_conditioner = TransitionConditioner(delta_scale, **(transition_kwargs or {})) + self.action_flow = BiHubActionFlow(**(action_kwargs or {})) + self.register_buffer("action_mean", action_mean.float().reshape(2, 7), persistent=True) + self.register_buffer("action_std", action_std.float().reshape(2, 7), persistent=True) + + def train(self, mode: bool = True) -> "BiHubWAMActionStage": + super().train(mode) + self.state_encoder.eval() + return self + + def normalize_action(self, value: Tensor) -> Tensor: + return (value.float() - self.action_mean) / self.action_std + + def denormalize_action(self, value: Tensor) -> Tensor: + return value.float() * self.action_std + self.action_mean + + def state_conditions(self, history: Tensor, mask: Tensor) -> Tensor: + with torch.no_grad(): + encoded = self.state_encoder(history.float(), mask.bool()) + return torch.stack([encoded["left"], encoded["global"], encoded["right"]], dim=1) + + def forward( + self, + batch: ActionV6Batch, + *, + noise: Tensor | None = None, + tau: Tensor | None = None, + action_tau: Tensor | None = None, + transitions: Tensor | None = None, + state_lgr: Tensor | None = None, + transition_source: Tensor | None = None, + transition_target: Tensor | None = None, + ) -> dict[str, Tensor]: + action = self.normalize_action(batch.action_gt) + if noise is None: + noise = torch.randn_like(action) + else: + noise = noise.float() + if tau is None: + tau = torch.sigmoid(torch.randn(action.shape[0], device=action.device, dtype=torch.float32)) + else: + tau = tau.reshape(action.shape[0]).float().clamp(1.0e-5, 1.0 - 1.0e-5) + if action_tau is None: + action_tau = (1.0 - tau[:, None, None, None]) * noise + tau[:, None, None, None] * action + elif action_tau.shape != action.shape: + raise ValueError("action_tau override must be [B,20,2,7]") + else: + action_tau = action_tau.float() + velocity_target = action - noise + if transitions is None: + if (transition_source is None) != (transition_target is None): + raise ValueError("explicit transition source/target must be provided together") + transitions = ( + self.transition_conditioner(batch.z_current, batch.z_future_cond) + if transition_source is None + else self.transition_conditioner.forward_pairs( + transition_source, transition_target # type: ignore[arg-type] + ) + ) + elif transition_source is not None or transition_target is not None: + raise ValueError("cannot combine precomputed and explicit transition conditions") + if state_lgr is None: + state_lgr = self.state_conditions(batch.state_history, batch.state_valid_mask) + velocity = self.action_flow.velocity( + action_tau, tau, state_lgr, transitions, batch.action_valid_mask + ) + mask = batch.action_valid_mask.bool()[:, :, None, None].expand_as(velocity) + squared = (velocity.float() - velocity_target.float()).square() + per_sample_denominator = mask.flatten(1).sum(1).clamp_min(1) + uniform_per_sample = (squared * mask).flatten(1).sum(1) / per_sample_denominator + uniform_loss = uniform_per_sample.mean() + deploy_loss = uniform_loss + deploy_per_sample = uniform_per_sample + if self.loss_mode == "masked_action_flow_mse_execute8_gripper_weighted": + # The deployed controller executes only the first eight targets before + # replanning. Preserve supervision over all 20 steps while assigning + # 60% of the temporal weight to the actually executed prefix. + time_weight = squared.new_tensor([1.5] * 8 + [2.0 / 3.0] * 12) + weight = mask.to(squared.dtype) * time_weight[None, :, None, None] + # Gripper changes are short and sparse. Reweight only arms whose GT + # chunk really contains an open/close transition; never reward motion + # merely for being large. + gripper = batch.action_gt.float()[:, :, :, 6] + valid_gripper = batch.action_valid_mask[:, :, None].bool() + maximum = gripper.masked_fill(~valid_gripper, -torch.inf).amax(dim=1) + minimum = gripper.masked_fill(~valid_gripper, torch.inf).amin(dim=1) + transition = (maximum - minimum) > 0.5 + dimension_weight = torch.ones( + squared.shape[0], 1, 2, 7, dtype=squared.dtype, device=squared.device + ) + dimension_weight[:, 0, :, 6] = 1.0 + 3.0 * transition.to(squared.dtype) + weight = weight * dimension_weight + deploy_denominator = weight.flatten(1).sum(1).clamp_min(1.0) + deploy_per_sample = (squared * weight).flatten(1).sum(1) / deploy_denominator + deploy_loss = deploy_per_sample.mean() + loss = 0.5 * uniform_loss + 0.5 * deploy_loss + per_sample = 0.5 * uniform_per_sample + 0.5 * deploy_per_sample + else: + loss = uniform_loss + per_sample = uniform_per_sample + if not torch.isfinite(loss): + raise FloatingPointError("non-finite masked action flow loss") + return { + "loss": loss.float(), + "loss_uniform": uniform_loss.detach().float(), + "loss_deploy": deploy_loss.detach().float(), + "velocity_pred": velocity, + "velocity_target": velocity_target.float(), + "tau": tau, + "per_sample_mse": per_sample, + "transitions": transitions, + "state_lgr": state_lgr, + } diff --git a/release-20261107/source/workspace_joint/mira/src/mira/benchmark/__init__.py b/release-20261107/source/workspace_joint/mira/src/mira/benchmark/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c25dfa3045c2cd2771406fd4d65da44ccfeaa01a --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/benchmark/__init__.py @@ -0,0 +1 @@ +"""Benchmark integration packages.""" diff --git a/release-20261107/source/workspace_joint/mira/src/mira/benchmark/robotwin_v6/__init__.py b/release-20261107/source/workspace_joint/mira/src/mira/benchmark/robotwin_v6/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3853ed22791124e35945434fd56551d50dedb727 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/benchmark/robotwin_v6/__init__.py @@ -0,0 +1,5 @@ +"""Pinned RoboTwin-v2 adapter for BiHub-WAM v6 Action.""" + +from .adapter import ActionPostprocessor, CommandHistory, pack_action_dict, unpack_action_chunk + +__all__ = ["ActionPostprocessor", "CommandHistory", "pack_action_dict", "unpack_action_chunk"] diff --git a/release-20261107/source/workspace_joint/mira/src/mira/benchmark/robotwin_v6/adapter.py b/release-20261107/source/workspace_joint/mira/src/mira/benchmark/robotwin_v6/adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..efd1abcfa9062a6af49e60b9567120a95bcc1b70 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/benchmark/robotwin_v6/adapter.py @@ -0,0 +1,173 @@ +"""Strict 14D Action-v6 ↔ XPolicyLab/RoboTwin state and history contracts.""" + +from __future__ import annotations + +from collections import deque +from dataclasses import dataclass, field +import hashlib + +import numpy as np + + +def camera_lgr(observation: dict) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + source = observation.get("observation", observation) + names = ("left_camera", "head_camera", "right_camera") + if any(name not in source or "rgb" not in source[name] for name in names): + raise KeyError("RoboTwin observation must provide left/head/right RGB cameras") + values = tuple(np.asarray(source[name]["rgb"]) for name in names) + if any(value.ndim != 3 or value.shape[-1] != 3 for value in values): + raise ValueError("RoboTwin camera RGB must be HWC with three channels") + return values # type: ignore[return-value] + + +def deterministic_replan_seed( + task: str, domain: str, environment_seed: int, replan_index: int, artifact_sha: str, role: str +) -> int: + payload = f"{task}\0{domain}\0{environment_seed}\0{replan_index}\0{artifact_sha}\0{role}" + return int.from_bytes(hashlib.sha256(payload.encode()).digest()[:8], "big") + + +def validate_result_row(value: dict) -> None: + required = { + "task", "domain", "env_seed", "checkpoint_sha256", "world_sha256", + "inference_config_sha256", "success", "latency_ms", "protocol", + } + missing = sorted(required - set(value)) + if missing: + raise ValueError(f"benchmark result row lacks provenance: {missing}") + if value["protocol"] not in {"smoke", "dev", "final"}: + raise ValueError("invalid benchmark protocol") + + +def unpack_action_chunk(value: np.ndarray) -> list[dict[str, np.ndarray | str]]: + action = np.asarray(value, dtype=np.float32) + if action.ndim == 1: + action = action[None] + if action.ndim != 2 or action.shape[1] != 14 or not np.isfinite(action).all(): + raise ValueError("Action-v6 output must be finite [H,14]") + return [ + { + "left_arm_joint_state": row[:6].copy(), + "left_ee_joint_state": row[6:7].copy(), + "right_arm_joint_state": row[7:13].copy(), + "right_ee_joint_state": row[13:14].copy(), + "action_type": "joint", + } + for row in action + ] + + +def pack_action_dict(value: dict[str, np.ndarray | str]) -> np.ndarray: + required = ( + "left_arm_joint_state", + "left_ee_joint_state", + "right_arm_joint_state", + "right_ee_joint_state", + ) + if any(name not in value for name in required): + raise KeyError("XPolicyLab action dict is missing a bimanual qpos field") + parts = [np.asarray(value[name], dtype=np.float32).reshape(-1) for name in required] + if [part.size for part in parts] != [6, 1, 6, 1]: + raise ValueError("XPolicyLab action field dimensions differ from 6+1+6+1") + packed = np.concatenate(parts) + if not np.isfinite(packed).all(): + raise ValueError("XPolicyLab action contains non-finite values") + return packed + + +class ActionPostprocessor: + def __init__(self, mean, std, physical_min, physical_max, normalized_clip: float = 5.0) -> None: + self.mean = np.asarray(mean, dtype=np.float32).reshape(14) + self.std = np.asarray(std, dtype=np.float32).reshape(14) + self.lower = np.asarray(physical_min, dtype=np.float32).reshape(14) + self.upper = np.asarray(physical_max, dtype=np.float32).reshape(14) + self.normalized_clip = float(normalized_clip) + if np.any(self.std < 1.0e-4) or np.any(self.lower > self.upper): + raise ValueError("invalid Action-v6 postprocessing statistics") + self.normalized_clip_count = 0 + self.physical_clip_count = 0 + self.total = 0 + + def __call__(self, normalized: np.ndarray) -> np.ndarray: + value = np.asarray(normalized, dtype=np.float32) + if value.ndim != 2 or value.shape[1] != 14 or not np.isfinite(value).all(): + raise ValueError("normalized Action-v6 sample must be finite [H,14]") + clipped = np.clip(value, -self.normalized_clip, self.normalized_clip) + self.normalized_clip_count += int(np.count_nonzero(clipped != value)) + raw = clipped * self.std + self.mean + limited = np.clip(raw, self.lower, self.upper) + self.physical_clip_count += int(np.count_nonzero(limited != raw)) + self.total += value.size + return limited + + +@dataclass +class _EnvironmentState: + command_history: deque[np.ndarray] = field(default_factory=lambda: deque(maxlen=20)) + history_valid: deque[bool] = field(default_factory=lambda: deque(maxlen=20)) + pending: deque[np.ndarray] = field(default_factory=deque) + image_count: int = 0 + replan_index: int = 0 + + +class CommandHistory: + """Track actually issued drive targets; measured qpos is used only for reset padding.""" + + def __init__(self) -> None: + self._states: dict[str, _EnvironmentState] = {} + + def reset(self, environment_id: str, measured_qpos: np.ndarray) -> None: + qpos = np.asarray(measured_qpos, dtype=np.float32).reshape(14) + if not np.isfinite(qpos).all(): + raise ValueError("initial measured qpos must be finite 14D") + state = _EnvironmentState() + state.command_history.extend(qpos.copy() for _ in range(20)) + state.history_valid.extend([False] * 19 + [True]) + self._states[environment_id] = state + + def queue_chunk(self, environment_id: str, action: np.ndarray, *, execute_steps: int = 8) -> list[np.ndarray]: + if environment_id not in self._states: + raise KeyError("environment must be reset before planning") + chunk = np.asarray(action, dtype=np.float32) + if chunk.shape != (20, 14) or not np.isfinite(chunk).all(): + raise ValueError("policy chunk must be finite [20,14]") + if execute_steps != 8: + raise ValueError("Action v6 benchmark locks execute_steps=8") + state = self._states[environment_id] + if state.pending: + raise RuntimeError("cannot replan before the issued chunk has been consumed") + state.pending.extend(row.copy() for row in chunk[:execute_steps]) + state.replan_index += 1 + return [row.copy() for row in chunk[:execute_steps]] + + def update_obs(self, environment_id: str) -> None: + if environment_id not in self._states: + raise KeyError(environment_id) + state = self._states[environment_id] + state.image_count += 1 + if state.pending: + state.command_history.append(state.pending.popleft()) + state.history_valid.append(True) + + def history(self, environment_id: str) -> np.ndarray: + state = self._states[environment_id] + if len(state.command_history) != 20: + raise RuntimeError("command history must always have 20 rows") + return np.stack(state.command_history) + + def valid_mask(self, environment_id: str) -> np.ndarray: + state = self._states[environment_id] + if len(state.history_valid) != 20: + raise RuntimeError("command-history validity mask must always have 20 entries") + return np.asarray(state.history_valid, dtype=np.bool_) + + def finish(self, environment_id: str) -> None: + if environment_id in self._states: + self._states[environment_id].pending.clear() + + def remove(self, environment_id: str) -> None: + self._states.pop(environment_id, None) + + @property + def environment_ids(self) -> set[str]: + return set(self._states) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/codec/__init__.py b/release-20261107/source/workspace_joint/mira/src/mira/codec/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d09f2dda5576ffecf22ac362c5a0f9fde09a2993 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/codec/__init__.py @@ -0,0 +1,43 @@ +"""mira.codec: the RAEv2 temporal-downsampling video codec. + +Public API: + VideoCodecConfig, RAEEncoderConfig, ViTDecoderConfig, StridedConvBottleneckConfig — configs + VideoCodec, VideoCodecOutputs — the codec module and its forward outputs + RAEEncoder, RAEEncoderOutputs — frozen feature backbone + strided-conv bottleneck encoder + ViTVideoDecoder — ViT video decoder + DinoModel, DinoPerceptualLoss, DINO_DIM — DINOv3 backbone loading + perceptual loss + LingBotModel, LINGBOT_DIM — local LingBot-Vision backbone loading + CodecLoss, CodecLossWeights — the codec training loss and its configuration +""" + +from .codec_model import VideoCodec, VideoCodecOutputs +from .config import ( + RAEEncoderConfig, + StridedConvBottleneckConfig, + VideoCodecConfig, + ViTDecoderConfig, +) +from .dino import DINO_DIM, DinoModel, DinoPerceptualLoss +from .lingbot import LINGBOT_DIM, LingBotModel +from .loss import CodecLoss, CodecLossWeights +from .rae_encoder import RAEEncoder, RAEEncoderOutputs +from .vit_decoder import ViTVideoDecoder + +__all__ = [ + "VideoCodecConfig", + "RAEEncoderConfig", + "ViTDecoderConfig", + "StridedConvBottleneckConfig", + "VideoCodec", + "VideoCodecOutputs", + "RAEEncoder", + "RAEEncoderOutputs", + "ViTVideoDecoder", + "DinoModel", + "DinoPerceptualLoss", + "DINO_DIM", + "LingBotModel", + "LINGBOT_DIM", + "CodecLoss", + "CodecLossWeights", +] diff --git a/release-20261107/source/workspace_joint/mira/src/mira/codec/codec_model.py b/release-20261107/source/workspace_joint/mira/src/mira/codec/codec_model.py new file mode 100644 index 0000000000000000000000000000000000000000..7b3d51910fcb5c2e7f49e93042b6192fbd05e3f3 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/codec/codec_model.py @@ -0,0 +1,218 @@ +"""The RAEv2 temporal-downsampling video codec: encode/decode plus checkpoint loading. + +:class:`VideoCodec` wraps the frozen-feature :class:`RAEEncoder` and the :class:`ViTVideoDecoder`. +It is video-only (no audio). :meth:`VideoCodec.load_from_checkpoint` restores the backbone weights +from the checkpoint, so deployment does not need a separate pretrained-backbone weight path. +""" + +from __future__ import annotations + +import logging +from dataclasses import dataclass +from pathlib import Path + +import torch +from einops import rearrange +from torch import Tensor, nn + +from mira.codec.config import VideoCodecConfig +from mira.codec.rae_encoder import RAEEncoder, RAEEncoderOutputs +from mira.codec.vit_decoder import ViTVideoDecoder +from mira.data.batch import VideoActionBatch +from mira.ml.config_loading import drop_removed_fields, strip_hydra_targets + +logger = logging.getLogger(__name__) + +# Fields dropped from the codec schema but still written, at their no-op value, by older training +# runs; tolerated and stripped on load so released checkpoints keep validating (see +# `drop_removed_fields`). A non-no-op value raises rather than loading silently wrong. +REMOVED_CONFIG_FIELDS = {"is_audio_model": False} + + +@dataclass # dataclass doesn't cause graph breaks when torch.compile()'ing, unlike Pydantic +class VideoCodecOutputs: + input_video: Tensor + output_video: Tensor + z: Tensor + backbone_features: tuple[Tensor, ...] | None = None + + @property + def dino_features(self) -> tuple[Tensor, ...] | None: + """Backward-compatible alias for pre-LingBot callers.""" + return self.backbone_features + + +class VideoCodec(nn.Module): + def __init__(self, config: VideoCodecConfig, require_dino_weights: bool = True) -> None: + super().__init__() + + self.config = config + + self.encoder = RAEEncoder(config.encoder, require_dino_weights=require_dino_weights) + self.decoder = ViTVideoDecoder(config.decoder) + + self.temporal_downsampling, self.spatial_downsampling = self.encoder.get_downsampling_factors() + decoder_patch_size_t = config.decoder.patch_size_t + if decoder_patch_size_t != self.temporal_downsampling: + raise ValueError( + f"Codec encoder/decoder temporal mismatch: encoder downsamples by " + f"{self.temporal_downsampling}x in time, decoder expands by " + f"{decoder_patch_size_t}x (decoder.patch_size_t). Set them equal." + ) + if config.decoder.latent_dim != config.encoder.latent_dim: + raise ValueError( + f"Codec encoder/decoder latent_dim mismatch: encoder={config.encoder.latent_dim}, " + f"decoder={config.decoder.latent_dim}. Set them equal." + ) + decoder_spatial = config.decoder.bottleneck.stride * config.decoder.patch_size + if decoder_spatial != self.spatial_downsampling: + raise ValueError( + f"Codec encoder/decoder spatial mismatch: encoder downsamples by " + f"{self.spatial_downsampling}x in space, decoder expands by {decoder_spatial}x " + f"(decoder.bottleneck.stride * decoder.patch_size). Set them equal." + ) + self.latent_dim = config.encoder.latent_dim + + # Non-weights checkpoint entries (everything saved alongside ``state_dict``), populated by + # :meth:`load_from_checkpoint`. This is freeform metadata; the world model reads the codec + # latent normalization from its ``latent_mean_std`` key when present. + self.info_from_checkpoint: dict | None = None + + def preprocess_batch(self, batch: VideoActionBatch) -> None: + """Preprocess a batch in-place. + + Watch out: the batch should be on the GPU, because resizing on CPU is so slow that it can + bottleneck world model training. + """ + video = batch.video / 255.0 + + batch_size, n_frames, _, image_h, image_w = video.shape + target_h, target_w = self.config.encoder.video.height, self.config.encoder.video.width + + # Letterbox symmetrically with black to preserve aspect ratio and keep the scene centered. + if image_w * target_h < target_w * image_h: + horizontal_pad = round(target_w / target_h * image_h) - image_w + left_pad = horizontal_pad // 2 + right_pad = horizontal_pad - left_pad + video = torch.nn.functional.pad(video, (left_pad, right_pad)) + elif image_w * target_h > target_w * image_h: + vertical_pad = round(target_h / target_w * image_w) - image_h + top_pad = vertical_pad // 2 + bottom_pad = vertical_pad - top_pad + video = torch.nn.functional.pad(video, (0, 0, top_pad, bottom_pad)) + + if video.shape[-2:] != (target_h, target_w): + video = torch.nn.functional.interpolate( + rearrange(video, "b t c h w -> (b t) c h w"), + size=(target_h, target_w), + mode="bilinear", + antialias=True, + ) + video = rearrange(video, "(b t) c h w -> b t c h w", b=batch_size, t=n_frames) + + batch.video = video + + def normalize_video(self, x: Tensor, trim_video: bool = True) -> Tensor: + if trim_video: + x = x[:, : self.config.encoder.video.timesteps] + + x = (x - 0.5) / 0.5 # [-1, 1] range + + return x + + def forward(self, batch: VideoActionBatch, trim_video: bool = True) -> VideoCodecOutputs: + self.preprocess_batch(batch) + + input_video, encoder_output = self.encode(batch.video, trim_video=trim_video) + output_video = self.decode(encoder_output.z) + + return VideoCodecOutputs( + input_video=input_video, + output_video=output_video, + z=encoder_output.z, + backbone_features=encoder_output.backbone_features, + ) + + def encode(self, video: Tensor, trim_video: bool = True) -> tuple[Tensor, RAEEncoderOutputs]: + input_video = self.normalize_video(video, trim_video=trim_video) + return input_video, self.encoder(input_video) + + def decode(self, z: Tensor) -> Tensor: + return self.decoder(z) + + CONFIG_FILENAME = "codec_config.yaml" + + def save_checkpoint(self, checkpoint_path: str | Path, extra_data: dict | None = None) -> None: + """Save the model checkpoint to a file. + + Doesn't save the config; save it separately alongside the checkpoint. + """ + if _find_codec_config(checkpoint_path) is None: + raise FileNotFoundError( + f"Could not find '{VideoCodec.CONFIG_FILENAME}' in parent directories " + f"of {checkpoint_path}. Make sure to save the config file alongside the checkpoint." + ) + + checkpoint = {"state_dict": self.state_dict()} + + if extra_data is not None: + for key in extra_data.keys(): + if key in checkpoint: + raise ValueError(f"Key {key} already exists in checkpoint, cannot overwrite") + + checkpoint.update(extra_data) + + torch.save(checkpoint, checkpoint_path) + + @classmethod + def load_from_checkpoint( + cls, + checkpoint_path: str | Path, + device: str | torch.device = "cpu", + ) -> VideoCodec: + # `device` defaults to "cpu" rather than None: torch.load(..., map_location=None) + # restores tensors to the device they were saved from (typically cuda:0), which + # causes every DDP rank to materialise the codec on cuda:0 and silently leaks + # several GiB onto rank 0's GPU. Callers that want GPU loading pass device explicitly. + from omegaconf import OmegaConf # noqa: PLC0415 -- optional dep, used only here + + config_path = _find_codec_config(checkpoint_path) + + if config_path is None: + raise FileNotFoundError( + f"Could not find '{VideoCodec.CONFIG_FILENAME}' in parent directories " + f"of {checkpoint_path}. Make sure to save the config file alongside the checkpoint." + ) + + # Load via OmegaConf (already a dependency) so the config's ${..} interpolations resolve. + config_raw = OmegaConf.load(config_path) + + # _target_ keys may exist at any nesting if saved from hydra instantiation; strip them all, + # then drop fields removed from the schema since the checkpoint was written. + raw_dict = strip_hydra_targets( + OmegaConf.to_container(config_raw.model.architecture.config, resolve=True) + ) + raw_dict = drop_removed_fields(raw_dict, REMOVED_CONFIG_FIELDS) + assert isinstance(raw_dict, dict), "expected dict at architecture.config" + config = VideoCodecConfig.model_validate(raw_dict) + + # We don't need external pretrained backbone weights because the codec checkpoint includes + # the complete frozen backbone state. + model = VideoCodec(config, require_dino_weights=False) + model.to(device) + + checkpoint = torch.load(checkpoint_path, map_location=device) + model.load_state_dict(checkpoint["state_dict"]) + + checkpoint.pop("state_dict") + model.info_from_checkpoint = checkpoint + + return model + + +def _find_codec_config(checkpoint_path: str | Path) -> Path | None: + for parent in Path(checkpoint_path).parents: + candidate = parent / VideoCodec.CONFIG_FILENAME + if candidate.exists(): + return candidate + return None diff --git a/release-20261107/source/workspace_joint/mira/src/mira/codec/config.py b/release-20261107/source/workspace_joint/mira/src/mira/codec/config.py new file mode 100644 index 0000000000000000000000000000000000000000..7360dc54f62ec0e3b1248d13ff58d18d902efaf2 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/codec/config.py @@ -0,0 +1,104 @@ +"""Pydantic configs for the RAEv2 temporal-downsampling video codec. + +The codec is a frozen image-feature backbone with a strided-conv bottleneck +(:class:`RAEEncoderConfig`) feeding a ViT video decoder (:class:`ViTDecoderConfig`). +""" + +from __future__ import annotations + +from typing import Literal + +from pydantic import BaseModel, ConfigDict, Field + +from mira.ml import ImageConfig + + +class StridedConvBottleneckConfig(BaseModel): + """kxk strided convolution bottleneck (RAEv2). + + Encoder side: a ``Conv2d`` (``temporal_stride == 1``) or ``Conv3d`` (``temporal_stride > 1``) + with ``kernel_size == stride``; decoder side: a matching ``ConvTranspose2d`` lifting the latent + grid back up. ``noise_tau > 0`` adds train-time Gaussian noise ``sigma ~ U(0, noise_tau)`` per + frame to the latent (the decoder ignores ``noise_tau``). When ``temporal_stride > 1`` the encoder + downsamples in time by that factor; pair it with ``decoder.patch_size_t == temporal_stride``. + """ + + model_config = ConfigDict(extra="forbid") + + stride: int = 2 + temporal_stride: int = 1 + noise_tau: float = 0.0 + + +class RAEEncoderConfig(BaseModel): + """Frozen feature backbone + a strided-conv bottleneck (RAEv2). + + Aggregates intermediate backbone layers (``mean(features at indices) + features[-1]``) when + ``aggregation_layers`` is set, then projects to the latent through the strided-conv bottleneck. + """ + + model_config = ConfigDict(extra="forbid") + + latent_dim: int + backbone_type: Literal["dinov3", "lingbot"] = "dinov3" + # Backbone variant: e.g. ``dinov3_vitl16`` or LingBot's ``large``. + rae_model: str + # LingBot training loads only from this local file/directory. It never falls back to a Hub + # download. Codec checkpoint restoration does not need this path because the backbone weights + # are included in the codec state dict. + backbone_weights_path: str | None = None + video: ImageConfig + + # None = last-layer-only. list = multi-layer-sum: ``mean(features at indices) + features[-1]``. + # RAEv2's k=7 default is (11, 13, 15, 17, 19, 21, 23). + aggregation_layers: list[int] | None = None + + bottleneck: StridedConvBottleneckConfig = Field(default_factory=StridedConvBottleneckConfig) + + # New configs should use this generic flag. ``compile_dino`` remains for compatibility with + # released DINO codec configs and checkpoints. + compile_backbone: bool | None = None + compile_dino: bool = True + + @property + def should_compile_backbone(self) -> bool: + return self.compile_dino if self.compile_backbone is None else self.compile_backbone + + +class ViTDecoderConfig(BaseModel): + """ViT video decoder lifting the RAEv2 latent back to pixels. + + The ``bottleneck`` (a :class:`StridedConvBottleneckConfig`) selects the latent->ViT-input + projection: a kxk ``ConvTranspose2d`` lifting the latent to the wider ViT grid (e.g. a /32 + latent up to a /16 ViT grid with ``stride=2``). + """ + + model_config = ConfigDict(extra="forbid") + + video: ImageConfig + out_channels: int = 3 + latent_dim: int = 32 + patch_size: int = 32 + patch_size_t: int = 1 + is_causal: bool = True + activation_checkpointing: bool = False + eps: float = 1e-6 + + bottleneck: StridedConvBottleneckConfig = Field(default_factory=StridedConvBottleneckConfig) + + vit_width: int = 1024 + vit_depth: int = 24 + vit_num_heads: int = 16 + vit_num_kv_heads: int | None = None + mlp_dim_multiplier: int = 4 + layerscale_init: float = 1e-4 + rope_theta_spatial: float = 100.0 + rope_theta_temporal: float = 64.0 + qk_norm: Literal["rmsnorm", "layernorm"] = "rmsnorm" + + +class VideoCodecConfig(BaseModel): + model_config = ConfigDict(extra="forbid") + + encoder: RAEEncoderConfig + decoder: ViTDecoderConfig diff --git a/release-20261107/source/workspace_joint/mira/src/mira/codec/dino.py b/release-20261107/source/workspace_joint/mira/src/mira/codec/dino.py new file mode 100644 index 0000000000000000000000000000000000000000..61c6d7b230c0219c3aed5f2215046984b1c0490d --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/codec/dino.py @@ -0,0 +1,224 @@ +"""DINOv3 backbone loading for the frozen RAE encoder. + +The encoder's frozen feature extractor is a DINOv3 ViT loaded through ``torch.hub`` from the +``facebookresearch/dinov3`` repo. This requires network access (or a populated hub cache) the first +time it runs. Pretrained weights are loaded from a local cache directory when the +``RS_DINO_WEIGHTS_DIR`` environment variable points at one; when no local weights are available and +``require_pretrained=False`` the backbone is built with random weights and restored from a codec +checkpoint instead (the path :meth:`VideoCodec.load_from_checkpoint` takes). + +The backbone (:class:`DinoModel`) and the DINO-feature perceptual loss +(:class:`DinoPerceptualLoss`, used for the latent-consistency term) both live here; the loss module +in :mod:`mira.codec.loss` composes them. +""" + +from __future__ import annotations + +import logging +import os +from pathlib import Path +from typing import Any, List + +import torch +import torch.nn as nn +from einops import rearrange +from torch import Tensor + +logger = logging.getLogger(__name__) + +IMAGENET_MEAN = (0.485, 0.456, 0.406) +IMAGENET_STD = (0.229, 0.224, 0.225) +PATCH_SIZE = 16 +DINO_DIM = { + "dinov3_vitl16": 1024, + "dinov3_vitb16": 768, +} + +# Pretrained DINOv3 weight filenames, as published at +# https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/ +DINO_WEIGHT_FILENAMES = { + "dinov3_vitl16": "dinov3_vitl16_pretrain_lvd1689m-8aa4cbdd.pth", + "dinov3_vitb16": "dinov3_vitb16_pretrain_lvd1689m-73cec8be.pth", +} + + +def resolve_dino_weights(dino_model: str) -> Path | None: + """Return a local DINOv3 weights file for ``dino_model``, or ``None`` if none is configured. + + Set ``RS_DINO_WEIGHTS_DIR`` to a directory holding the pretrained ``.pth`` files (named as in + :data:`DINO_WEIGHT_FILENAMES`) to load weights from disk; otherwise the backbone is built + without pretrained weights (and restored from a codec checkpoint, for inference). + """ + weights_dir = os.environ.get("RS_DINO_WEIGHTS_DIR") + if not weights_dir: + return None + candidate = Path(weights_dir) / DINO_WEIGHT_FILENAMES[dino_model] + return candidate if candidate.exists() else None + + +DEFAULT_DINO_LAYERS = { + "dinov3_vitl16": (2, 6, 10, 14, 18, 22), + "dinov3_vitb16": (2, 5, 8, 11), +} + + +class DinoModel(nn.Module): + backbone_type = "dinov3" + + # The hub-loaded (or preloaded) backbone; typed loosely as its API is dynamic. + dino_model: Any + mean: Tensor + std: Tensor + + def __init__( + self, + dino_model: str = "dinov3_vitb16", + preloaded_dino_module: torch.nn.Module | None = None, + last_layer_only: bool = True, + layer_indices: tuple[int, ...] | None = None, + compile: bool = True, + require_pretrained: bool = True, + ): + assert dino_model in DINO_DIM, f"Dino model {dino_model} not supported" + if last_layer_only and layer_indices is not None: + raise ValueError("DinoModel: pass either last_layer_only=True OR layer_indices=(...), not both.") + super().__init__() + self.dino_model_name = dino_model + if layer_indices is not None: + self.layers = layer_indices + elif last_layer_only: + self.layers = 1 + else: + self.layers = DEFAULT_DINO_LAYERS[dino_model] + + self.dino_dim = DINO_DIM[dino_model] + self.feature_dim = self.dino_dim + self.model_name = dino_model + if preloaded_dino_module: + self.dino_model = preloaded_dino_module + else: + logging.getLogger("dinov3").setLevel(logging.WARNING) # suppress noisy dinov3 logging + logger.info(f"Loading DINOv3 model, variant {dino_model}, {compile=}") + hub_kwargs: dict[str, Any] = dict( + repo_or_dir="facebookresearch/dinov3", + model=dino_model, + source="github", + verbose=False, # Get rid of "Using cache found in ..." message + ) + # Load pretrained weights from a local cache dir if RS_DINO_WEIGHTS_DIR provides one; + # otherwise build without pretrained weights (restored from a codec checkpoint). + weights_path = resolve_dino_weights(dino_model) + if weights_path is not None: + self.dino_model = torch.hub.load(**hub_kwargs, weights=str(weights_path)) + elif require_pretrained: + raise FileNotFoundError( + f"DINOv3 pretrained weights for {dino_model} not found. Set RS_DINO_WEIGHTS_DIR " + f"to a directory containing {DINO_WEIGHT_FILENAMES[dino_model]}. These are " + f"required unless the backbone will be restored from a checkpoint. " + f"If this is inference, build the codec via VideoCodec.load_from_checkpoint, " + f"which sets require_pretrained=False; if this is training, the file must exist." + ) + else: + logger.info( + "DINOv3 pretrained weights for %s not on disk; building with " + "pretrained=False (the frozen backbone weights are restored from the " + "model checkpoint).", + dino_model, + ) + self.dino_model = torch.hub.load(**hub_kwargs, pretrained=False) + if compile: + self.dino_model.get_intermediate_layers = torch.compile( + self.dino_model.get_intermediate_layers + ) + + self.register_buffer( + "mean", + torch.tensor(IMAGENET_MEAN, dtype=torch.float)[None, :, None, None], + persistent=False, + ) + self.register_buffer( + "std", + torch.tensor(IMAGENET_STD, dtype=torch.float)[None, :, None, None], + persistent=False, + ) + self.patch_size = PATCH_SIZE + + self.requires_grad_(False) + self.eval() + + def image_normalization(self, x: torch.Tensor) -> torch.Tensor: + return (x - self.mean) / self.std + + def dino_forward(self, x: Tensor) -> List[Tensor]: + b, t, _, h, w = x.shape + x = rearrange(x, "b t c h w -> (b t) c h w") # x must be in [0, 1] + x = self.image_normalization(x) + new_height = self.patch_size * (h // self.patch_size) + new_width = self.patch_size * (w // self.patch_size) + x = torch.nn.functional.interpolate(x, (new_height, new_width), mode="bilinear", antialias=True) + + dino_features = self.dino_model.get_intermediate_layers(x, n=self.layers, norm=True, reshape=True) # type: ignore + dino_features = [ + rearrange(feature, "(b t) c h w -> b t c h w", b=b, t=t) for feature in dino_features + ] + return dino_features + + def feature_forward(self, x: Tensor) -> List[Tensor]: + """Generic backbone interface used by the RAE encoder and feature-consistency loss.""" + return self.dino_forward(x) + + +class DinoPerceptualLoss(DinoModel): + """Perceptual loss in DINOv3 feature space, used for the codec's latent-consistency term. + + Compares DINO features of the reconstruction against those of the target, averaged over the + selected backbone layers. Pass ``preloaded_dino_module=other.dino_model`` to share an + already-loaded backbone (e.g. the encoder's frozen DINO); ``normalize=True`` selects the + latent-consistency variant, which L2-normalizes features along the channel dim before the MSE so + the loss compares feature *directions* rather than magnitudes. + """ + + def __init__( + self, + dino_model: str = "dinov3_vitb16", + preloaded_dino_module: torch.nn.Module | None = None, + last_layer_only: bool = False, + layer_indices: tuple[int, ...] | None = None, + compile: bool = True, + normalize: bool = False, + ) -> None: + super().__init__( + dino_model=dino_model, + preloaded_dino_module=preloaded_dino_module, + last_layer_only=last_layer_only, + layer_indices=layer_indices, + compile=compile, + ) + self.normalize = normalize + + def forward( + self, + pred_image: Tensor, + target_image: Tensor | None = None, + *, + target_features: tuple[Tensor, ...] | None = None, + ) -> tuple[Tensor, Tensor]: + """Return ``(loss, last_target_feature)``. + + Provide ``target_features`` to reuse already-computed (detached) target features — the + latent-consistency term passes the encoder's DINO features here — otherwise the target + features are computed from ``target_image`` under ``no_grad``. + """ + pred_features = self.dino_forward(pred_image) + if target_features is None: + assert target_image is not None + with torch.no_grad(): + target_features = tuple(self.dino_forward(target_image)) + + layer_terms: list[Tensor] = [] + for p, t in zip(pred_features, target_features): + if self.normalize: + p = nn.functional.normalize(p, dim=2, eps=1e-6) + t = nn.functional.normalize(t, dim=2, eps=1e-6) + layer_terms.append(nn.functional.mse_loss(p, t)) + return torch.stack(layer_terms).mean(), target_features[-1] diff --git a/release-20261107/source/workspace_joint/mira/src/mira/codec/lingbot.py b/release-20261107/source/workspace_joint/mira/src/mira/codec/lingbot.py new file mode 100644 index 0000000000000000000000000000000000000000..1d1dcce92816fed9cc1df0db1dbe6c8dfb1f35d9 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/codec/lingbot.py @@ -0,0 +1,192 @@ +"""Local-only LingBot-Vision loading and feature extraction for the RAE codec. + +The released LingBot loader can resolve remote Hugging Face repositories. Codec training must be +reproducible and must not silently download weights, so this adapter accepts only an existing local +checkpoint file or model directory when pretrained weights are required. +""" + +from __future__ import annotations + +import importlib +from pathlib import Path +from typing import Any + +import torch +from einops import rearrange +from torch import Tensor, nn + +IMAGENET_MEAN = (0.485, 0.456, 0.406) +IMAGENET_STD = (0.229, 0.224, 0.225) + +LINGBOT_DIM = { + "small": 384, + "base": 768, + "large": 1024, + "giant": 1536, +} + +LINGBOT_CONFIG_FILES = { + "small": "configs/lbot_vision_vits.yaml", + "base": "configs/lbot_vision_vitb.yaml", + "large": "configs/lbot_vision_vitl.yaml", + "giant": "configs/lbot_vision_vitg.yaml", +} + + +def _resolve_local_path(path: str | Path) -> Path: + """Resolve a local weight path from the cwd, then relative to the MIRA repository root.""" + candidate = Path(path).expanduser() + if candidate.exists(): + return candidate.resolve() + if not candidate.is_absolute(): + mira_root = Path(__file__).resolve().parents[3] + repo_relative = (mira_root / candidate).resolve() + if repo_relative.exists(): + return repo_relative + raise FileNotFoundError( + f"LingBot weights not found at {path!s}. Set encoder.backbone_weights_path or " + "LINGBOT_VISION_MODEL_DIR to a local directory containing model.pt." + ) + + +def _lingbot_imports() -> tuple[Any, Any, Any, Any, Any]: + try: + package = importlib.import_module("lingbot_vision") + build_module = importlib.import_module("lingbot_vision.build") + except ImportError as exc: + raise ImportError( + "LingBot codec support requires the local lingbot-vision package. Install it with " + "`uv pip install --python $CONDA_PREFIX/bin/python -e ../lingbot-vision`." + ) from exc + return ( + package.load_backbone, + package.load_backbone_state, + package.load_config, + package.load_pretrained_backbone, + build_module.build_backbone_from_cfg, + ) + + +class LingBotModel(nn.Module): + """Frozen LingBot-Vision backbone exposing video-shaped intermediate patch features.""" + + backbone_type = "lingbot" + mean: Tensor + std: Tensor + + def __init__( + self, + variant: str = "large", + *, + weights_path: str | Path | None = None, + last_layer_only: bool = True, + layer_indices: tuple[int, ...] | None = None, + compile: bool = True, + require_pretrained: bool = True, + ) -> None: + super().__init__() + if variant not in LINGBOT_DIM: + raise ValueError( + f"Unsupported LingBot variant {variant!r}; expected one of {sorted(LINGBOT_DIM)}" + ) + if last_layer_only and layer_indices is not None: + raise ValueError("Pass either last_layer_only=True or layer_indices=(...), not both.") + + ( + load_backbone, + load_backbone_state, + load_config, + load_pretrained_backbone, + build_backbone_from_cfg, + ) = _lingbot_imports() + + self.model_name = variant + self.feature_dim = LINGBOT_DIM[variant] + self.layers: int | tuple[int, ...] = 1 if last_layer_only else tuple(layer_indices or ()) + config_file = LINGBOT_CONFIG_FILES[variant] + + if require_pretrained: + if weights_path is None: + raise FileNotFoundError( + "LingBot pretrained weights are required for codec training. Set " + "encoder.backbone_weights_path or LINGBOT_VISION_MODEL_DIR." + ) + local_path = _resolve_local_path(weights_path) + if local_path.is_dir(): + backbone, loaded_dim = load_pretrained_backbone( + repo_id_or_path=str(local_path), + variant=variant, + device="cpu", + dtype=torch.float32, + local_files_only=True, + verbose=False, + ) + elif local_path.is_file(): + cfg = load_config(config_file) + state = load_backbone_state(local_path) + backbone, loaded_dim = load_backbone( + cfg, + state, + device="cpu", + dtype=torch.float32, + verbose=False, + ) + else: # pragma: no cover - _resolve_local_path already guarantees this + raise FileNotFoundError(str(local_path)) + else: + # Codec checkpoints carry the frozen backbone weights. Build only the matching + # architecture here, then let VideoCodec.load_from_checkpoint restore the state dict. + cfg = load_config(config_file) + backbone, loaded_dim = build_backbone_from_cfg(cfg) + backbone.eval().requires_grad_(False) + + if loaded_dim != self.feature_dim: + raise ValueError( + f"LingBot {variant} feature dim mismatch: expected {self.feature_dim}, got {loaded_dim}" + ) + if getattr(backbone, "patch_size", None) != 16: + raise ValueError(f"LingBot codec expects patch_size=16, got {backbone.patch_size}") + n_blocks = int(getattr(backbone, "n_blocks", len(backbone.blocks))) + if isinstance(self.layers, tuple) and (not self.layers or max(self.layers) >= n_blocks): + raise ValueError(f"Invalid LingBot layers {self.layers} for a {n_blocks}-block backbone") + + self.backbone = backbone + self.backbone.eval().requires_grad_(False) + self.patch_size = int(self.backbone.patch_size) + self.register_buffer( + "mean", + torch.tensor(IMAGENET_MEAN, dtype=torch.float)[None, :, None, None], + persistent=False, + ) + self.register_buffer( + "std", + torch.tensor(IMAGENET_STD, dtype=torch.float)[None, :, None, None], + persistent=False, + ) + self._get_intermediate_layers = ( + torch.compile(self.backbone.get_intermediate_layers) + if compile + else self.backbone.get_intermediate_layers + ) + + def train(self, mode: bool = True) -> LingBotModel: + """Keep the frozen backbone in eval mode while the projection/decoder train.""" + super().train(False) + return self + + def feature_forward(self, video: Tensor) -> list[Tensor]: + """Return normalized patch features as ``(B, T, C, H/16, W/16)`` tensors. + + This method intentionally does not use ``torch.no_grad``: the encoder target call wraps it + in no-grad, while the reconstruction-consistency call must retain gradients to its pixels. + """ + b, t, _, _, _ = video.shape + images = rearrange(video, "b t c h w -> (b t) c h w") + images = (images - self.mean) / self.std + outputs = self._get_intermediate_layers( + images, + n=self.layers, + reshape=True, + norm=True, + ) + return [rearrange(feature, "(b t) c h w -> b t c h w", b=b, t=t) for feature in outputs] diff --git a/release-20261107/source/workspace_joint/mira/src/mira/codec/loss.py b/release-20261107/source/workspace_joint/mira/src/mira/codec/loss.py new file mode 100644 index 0000000000000000000000000000000000000000..c7ead8d6338626eef03a01778e2b88d1992bf624 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/codec/loss.py @@ -0,0 +1,230 @@ +"""The codec training loss: L1 + LPIPS + feature consistency, with auto-weight balancing. + +:class:`CodecLossWeights` configures which terms are active and their weights; :class:`CodecLoss` +computes them from a :class:`~mira.codec.codec_model.VideoCodecOutputs`. Both the original DINO +recipe and the LingBot recipe share the encoder backbone with their feature-consistency term. +""" + +from __future__ import annotations + +from typing import Tuple + +import torch +import torch.nn.functional as F +from einops import rearrange +from pydantic import BaseModel, ConfigDict, Field, model_validator +from torch import Tensor, nn + +from mira.codec.codec_model import VideoCodecOutputs +from mira.codec.dino import DinoModel +from mira.codec.lingbot import LingBotModel + + +def calculate_adaptive_weight( + anchor_loss: Tensor, + other_loss: Tensor, + last_layer: Tensor, + max_weight: float = 1e4, +) -> Tensor: + """VQ-GAN-style adaptive weight (Esser et al., arXiv:2012.09841 §3.3). + + Balances ``other_loss`` against ``anchor_loss`` by the ratio of their gradient norms w.r.t. the + decoder's last layer, so each perceptual term contributes a comparable gradient magnitude to the + L1 anchor. The returned factor is detached (it scales the loss but carries no gradient itself). + """ + anchor_grads = torch.autograd.grad(anchor_loss, last_layer, retain_graph=True)[0] + other_grads = torch.autograd.grad(other_loss, last_layer, retain_graph=True)[0] + return (anchor_grads.norm() / (other_grads.norm() + 1e-6)).clamp(0.0, max_weight).detach() + + +class CodecLossWeights(BaseModel): + """Weights and per-term options for :class:`CodecLoss`. + + A term is active iff its weight is ``> 0``. ``auto_weight`` rescales each active perceptual term + (LPIPS, DINO latent consistency) by :func:`calculate_adaptive_weight` against the L1 anchor. + """ + + model_config = ConfigDict(extra="forbid") + + loss_mae: float = Field(..., ge=0) + + loss_lpips_perceptual: float = Field(default=0.0, ge=0) + lpips_perceptual_frame_frac: float = Field(default=0.25, gt=0, le=1.0) + + # RAEEncoder only: consistency between DINO features of the reconstruction and the encoder's. + loss_dino_latent_consistency: float = Field(default=0.0, ge=0) + dino_latent_consistency_frame_frac: float = Field(default=0.25, gt=0, le=1.0) + + # LingBot RAEEncoder: normalized seven-layer feature consistency, sharing the encoder backbone. + loss_lingbot_feature_consistency: float = Field(default=0.0, ge=0) + lingbot_feature_consistency_frame_frac: float = Field(default=0.25, gt=0, le=1.0) + + compile_dino: bool = True + + auto_weight: bool = False + max_auto_weight: float = Field(default=1e4, gt=0) + + @model_validator(mode="after") + def _one_feature_consistency_space(self) -> CodecLossWeights: + if self.loss_dino_latent_consistency > 0 and self.loss_lingbot_feature_consistency > 0: + raise ValueError("Enable only one feature-consistency loss (DINO or LingBot).") + return self + + +# Perceptual terms rescaled by auto_weight against the L1 (loss_mae) anchor. +_AUTO_WEIGHT_LOSSES: Tuple[str, ...] = ( + "loss_lpips_perceptual", + "loss_dino_latent_consistency", + "loss_lingbot_feature_consistency", +) + + +class FeaturePerceptualLoss(nn.Module): + """Compare normalized backbone features while retaining gradients to reconstructed pixels.""" + + def __init__(self, backbone: DinoModel | LingBotModel): + super().__init__() + # The backbone belongs to the codec module. Keep a non-registering reference so it is not + # duplicated in this loss module's state dict or moved independently. + object.__setattr__(self, "_backbone", backbone) + + @property + def backbone(self) -> DinoModel | LingBotModel: + return object.__getattribute__(self, "_backbone") + + def forward(self, predicted_video: Tensor, target_features: tuple[Tensor, ...]) -> Tensor: + predicted_features = self.backbone.feature_forward(predicted_video) + terms = [ + F.mse_loss( + F.normalize(predicted, dim=2, eps=1e-6), + F.normalize(target, dim=2, eps=1e-6), + ) + for predicted, target in zip(predicted_features, target_features, strict=True) + ] + return torch.stack(terms).mean() + + +class CodecLoss(nn.Module): + """Computes the codec's reconstruction loss terms and their weighted total. + + Feature consistency needs the encoder's frozen backbone, bound after construction via + :meth:`bind_encoder_backbone`; ``auto_weight`` needs the decoder's last-layer weight, bound via + :meth:`bind_last_layer`. + """ + + def __init__(self, weights: CodecLossWeights): + super().__init__() + self.weights = weights + + self.lpips_perceptual_loss: nn.Module | None = None + if self.weights.loss_lpips_perceptual > 0: + import lpips # noqa: PLC0415 -- optional dep, loaded only when in use + + self.lpips_perceptual_loss = lpips.LPIPS(net="vgg", verbose=False).eval() + for p in self.lpips_perceptual_loss.parameters(): + p.requires_grad = False + + self.backward_metrics: dict[str, Tensor] = {} + self._last_layer: Tensor | None = None + self.feature_consistency_loss: FeaturePerceptualLoss | None = None + self._feature_loss_name: str | None = None + self._feature_frame_frac: float | None = None + + def bind_last_layer(self, param: Tensor) -> None: + self._last_layer = param + + def bind_encoder_backbone(self, backbone: DinoModel | LingBotModel) -> None: + """Bind feature consistency to the encoder's already-loaded frozen backbone.""" + expected_type: str | None = None + if self.weights.loss_dino_latent_consistency > 0: + expected_type = "dinov3" + self._feature_loss_name = "loss_dino_latent_consistency" + self._feature_frame_frac = self.weights.dino_latent_consistency_frame_frac + elif self.weights.loss_lingbot_feature_consistency > 0: + expected_type = "lingbot" + self._feature_loss_name = "loss_lingbot_feature_consistency" + self._feature_frame_frac = self.weights.lingbot_feature_consistency_frame_frac + if expected_type is None: + return + if backbone.backbone_type != expected_type: + raise ValueError( + f"{self._feature_loss_name} requires a {expected_type} encoder, got {backbone.backbone_type}" + ) + self.feature_consistency_loss = FeaturePerceptualLoss(backbone) + + def bind_encoder_dino(self, dino: DinoModel) -> None: + """Backward-compatible alias for the original DINO trainer/tests.""" + self.bind_encoder_backbone(dino) + + @property + def dino_latent_consistency_loss(self) -> FeaturePerceptualLoss | None: + """Backward-compatible alias used by existing tests and downstream code.""" + return self.feature_consistency_loss + + def _hook_clone(self, tensor: Tensor, loss_name: str) -> Tensor: + """Clone ``tensor`` and register a backward hook recording its per-term gradient norm.""" + if not tensor.requires_grad: + return tensor + clone = tensor.clone() + clone.register_hook( + lambda grad: self.backward_metrics.update({loss_name: grad.data.norm(p=2, dim=-1).mean()}) + ) + return clone + + def forward(self, model_outputs: VideoCodecOutputs, global_step: int = 0) -> dict[str, Tensor]: + self.backward_metrics.clear() # Clear metrics from previous backward hooks + + # Those are in range [-1, 1]. + predicted = model_outputs.output_video.float() + predicted = self._hook_clone(predicted, "loss_total_video") + target = model_outputs.input_video.float() + + loss: dict[str, Tensor] = {} + + if self.weights.loss_mae > 0: + loss["loss_mae"] = F.l1_loss(self._hook_clone(predicted, "loss_mae"), target) + + t_total = predicted.shape[1] + + if self.lpips_perceptual_loss is not None: + # LPIPS expects (N, 3, H, W) in [-1, 1] (the codec's native range). + t_lpips_k = max(1, round(t_total * self.weights.lpips_perceptual_frame_frac)) + t_lpips = torch.randperm(t_total, device=predicted.device)[:t_lpips_k].sort().values + predicted_lpips = self._hook_clone(predicted, "loss_lpips_perceptual") + pred_2d = rearrange(predicted_lpips[:, t_lpips], "b t c h w -> (b t) c h w") + tgt_2d = rearrange(target[:, t_lpips], "b t c h w -> (b t) c h w") + loss["loss_lpips_perceptual"] = self.lpips_perceptual_loss(pred_2d, tgt_2d).mean() + + if self.feature_consistency_loss is not None: + assert self._feature_loss_name is not None and self._feature_frame_frac is not None + assert model_outputs.backbone_features is not None + t_lc_k = max(1, round(t_total * self._feature_frame_frac)) + t_lc = torch.randperm(t_total, device=predicted.device)[:t_lc_k].sort().values + pred_lc = (self._hook_clone(predicted, self._feature_loss_name) + 1) / 2 + real_lc = tuple(f[:, t_lc].detach() for f in model_outputs.backbone_features) + loss[self._feature_loss_name] = self.feature_consistency_loss(pred_lc[:, t_lc], real_lc) + + if ( + self.weights.auto_weight + and self._last_layer is not None + and "loss_mae" in loss + and loss["loss_mae"].requires_grad + and torch.is_grad_enabled() + ): + for name in _AUTO_WEIGHT_LOSSES: + if name not in loss or not loss[name].requires_grad: + continue + factor = calculate_adaptive_weight( + loss["loss_mae"], + loss[name], + self._last_layer, + max_weight=self.weights.max_auto_weight, + ) + loss[name] = factor * loss[name] + loss[f"{name}_auto_w"] = factor + + weighted = [getattr(self.weights, k) * v for k, v in loss.items() if hasattr(self.weights, k)] + # `weighted` is non-empty for any sensible config (loss_mae is required and > 0); guard the + # degenerate all-zero-weights case so it returns a finite zero rather than raising on stack. + loss["loss_total"] = torch.stack(weighted).sum() if weighted else predicted.new_zeros(()) + return loss diff --git a/release-20261107/source/workspace_joint/mira/src/mira/codec/rae_encoder.py b/release-20261107/source/workspace_joint/mira/src/mira/codec/rae_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..128572313b68182c9dd444f7d382bf44ec3d1acb --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/codec/rae_encoder.py @@ -0,0 +1,135 @@ +"""RAEv2 encoder: a frozen feature backbone, layer aggregation, and a strided-conv bottleneck.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import torch +from einops import rearrange +from torch import Tensor, nn + +from mira.codec.config import RAEEncoderConfig +from mira.codec.dino import DINO_DIM, DinoModel +from mira.codec.lingbot import LingBotModel +from mira.ml import init_weights + + +@dataclass +class RAEEncoderOutputs: + z: Tensor + backbone_features: tuple[Tensor, ...] | None = None + + @property + def dino_features(self) -> tuple[Tensor, ...] | None: + """Backward-compatible alias for callers written before generic backbones.""" + return self.backbone_features + + +class RAEEncoder(nn.Module): + """Frozen image-feature backbone -> aggregation -> bottleneck -> latent.""" + + def __init__(self, config: RAEEncoderConfig, require_dino_weights: bool = True) -> None: + """ + require_dino_weights: Historical name for "require external pretrained backbone weights". + It can be False when the complete frozen backbone will be restored from a codec + checkpoint. + """ + super().__init__() + self.config = config + layer_indices = tuple(config.aggregation_layers) if config.aggregation_layers else None + if config.backbone_type == "dinov3": + feature_dim = DINO_DIM[config.rae_model] + # Keep this attribute name so released DINO codec checkpoint keys remain loadable. + self.rae_dino = DinoModel( + config.rae_model, + last_layer_only=(layer_indices is None), + layer_indices=layer_indices, + compile=config.should_compile_backbone, + require_pretrained=require_dino_weights, + ) + elif config.backbone_type == "lingbot": + self.rae_lingbot = LingBotModel( + config.rae_model, + weights_path=config.backbone_weights_path, + last_layer_only=(layer_indices is None), + layer_indices=layer_indices, + compile=config.should_compile_backbone, + require_pretrained=require_dino_weights, + ) + feature_dim = self.rae_lingbot.feature_dim + else: # pragma: no cover - Pydantic validates the literal + raise ValueError(f"Unsupported backbone_type: {config.backbone_type}") + + if config.bottleneck.temporal_stride > 1: + self.rae_projection = nn.Conv3d( + feature_dim, + config.latent_dim, + kernel_size=( + config.bottleneck.temporal_stride, + config.bottleneck.stride, + config.bottleneck.stride, + ), + stride=( + config.bottleneck.temporal_stride, + config.bottleneck.stride, + config.bottleneck.stride, + ), + bias=True, + ) + else: + self.rae_projection = nn.Conv2d( + feature_dim, + config.latent_dim, + kernel_size=config.bottleneck.stride, + stride=config.bottleneck.stride, + bias=True, + ) + + # Initialise only the trainable bottleneck. Applying recursively would overwrite the + # already-loaded frozen backbone. + self.rae_projection.apply(init_weights) + + @property + def rae_backbone(self) -> DinoModel | LingBotModel: + if self.config.backbone_type == "lingbot": + return self.rae_lingbot + return self.rae_dino + + def get_downsampling_factors(self) -> tuple[int, int]: + return self.config.bottleneck.temporal_stride, 16 * self.config.bottleneck.stride + + def forward(self, video: Tensor) -> RAEEncoderOutputs: + # VideoCodec normalizes to [-1, 1]; both feature backbones expect [0, 1]. + video = (video + 1) / 2 + + with torch.no_grad(): + features = self.rae_backbone.feature_forward(video) # list of (B, T, C, H, W) + + if self.config.aggregation_layers: + stacked = torch.stack(features, dim=0) + agg = stacked.mean(dim=0) + features[-1] + else: + agg = features[-1] + + if isinstance(self.rae_projection, nn.Conv3d): + x = rearrange(agg, "b t c h w -> b c t h w") + z = self.rae_projection(x) + z = rearrange(z, "b c t h w -> b t c h w") + elif isinstance(self.rae_projection, nn.Conv2d): + b, t = agg.shape[:2] + x = rearrange(agg, "b t c h w -> (b t) c h w") + z = self.rae_projection(x) + z = rearrange(z, "(b t) c h w -> b t c h w", b=b, t=t) + else: + raise TypeError(f"Unexpected bottleneck projection: {type(self.rae_projection)}") + + # RAEv2-style noise regulariser (train mode, sigma per frame ~ U(0, noise_tau)); + # like the VAE reparam noise but with a configurable scale. + if self.training and self.config.bottleneck.noise_tau > 0: + sigma = ( + torch.rand(z.shape[0], z.shape[1], 1, 1, 1, device=z.device, dtype=z.dtype) + * self.config.bottleneck.noise_tau + ) + z = z + sigma * torch.randn_like(z) + + return RAEEncoderOutputs(z=z, backbone_features=tuple(features)) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/codec/vit_decoder.py b/release-20261107/source/workspace_joint/mira/src/mira/codec/vit_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..04e8074b9f62787e1be96e2308307e16be14bb2b --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/codec/vit_decoder.py @@ -0,0 +1,269 @@ +"""ViT video decoder for the RAEv2 codec (ViTok-v2-style space-time transformer). + +The decoder is a deep ViT operating on a patchified latent. Each :class:`SpaceTimeBlock` factorises +attention into bidirectional spatial self-attention within a frame and causal temporal self-attention +across frames, so the codec stays causal in time while behaving like a ViT in space. + +It reuses :class:`mira.ml.SelfAttention` (per-head QK-norm, GQA and RoPE) and adds the +pieces ViTok needs on top: patch unembedding, axial 2D + causal 1D RoPE frequencies, LayerScale, a +SwiGLU MLP and a strided ``ConvTranspose2d`` that lifts the latent grid up to the ViT grid. +""" + +from __future__ import annotations + +from typing import Literal + +import torch +import torch.utils.checkpoint +from einops import rearrange +from torch import Tensor, nn + +from mira.codec.config import ViTDecoderConfig +from mira.ml import SelfAttention, SelfAttentionConfig, init_weights + + +def _rope_cos_sin(positions: Tensor, dim: int, theta: float) -> tuple[Tensor, Tensor]: + """1D RoPE cos/sin for a set of positions. + + Returns ``(cos, sin)`` each of shape ``(len(positions), dim)``, with consecutive pairs + repeated to match :func:`mira.ml.apply_rotary_emb`. + """ + assert dim % 2 == 0, f"RoPE dim must be even, got {dim}" + k = torch.arange(dim // 2, dtype=torch.float32, device=positions.device) + inv_freq = theta ** (-2.0 * k / dim) # (dim // 2,) + freqs = positions.float()[:, None] * inv_freq[None, :] # (N, dim // 2) + cos = freqs.cos().repeat_interleave(2, dim=-1) # (N, dim) + sin = freqs.sin().repeat_interleave(2, dim=-1) + return cos, sin + + +def temporal_rope(num_frames: int, head_dim: int, theta: float, device: torch.device): + """Causal 1D RoPE over the time axis. Shape ``(T, head_dim)``.""" + positions = torch.arange(num_frames, device=device) + return _rope_cos_sin(positions, head_dim, theta) + + +def spatial_rope(height: int, width: int, head_dim: int, theta: float, device: torch.device): + """Axial 2D RoPE over a ``height x width`` grid. Shape ``(height * width, head_dim)``. + + Half of ``head_dim`` encodes the row position, the other half the column position. + """ + assert head_dim % 4 == 0, f"2D RoPE needs head_dim divisible by 4, got {head_dim}" + half = head_dim // 2 + rows = torch.arange(height, device=device).repeat_interleave(width) # (h*w,) + cols = torch.arange(width, device=device).repeat(height) # (h*w,) + cos_h, sin_h = _rope_cos_sin(rows, half, theta) + cos_w, sin_w = _rope_cos_sin(cols, half, theta) + cos = torch.cat([cos_h, cos_w], dim=-1) # (h*w, head_dim) + sin = torch.cat([sin_h, sin_w], dim=-1) + return cos, sin + + +class LayerScale(nn.Module): + def __init__(self, dim: int, init: float = 1e-4): + super().__init__() + self.gamma = nn.Parameter(init * torch.ones(dim)) + + def forward(self, x: Tensor) -> Tensor: + return x * self.gamma + + +class SwiGLU(nn.Module): + """SwiGLU MLP (~2.67x expansion at dim_multiplier=4), matching the world-model FeedForward.""" + + def __init__(self, dim: int, dim_multiplier: int = 4, multiple_of: int = 256): + super().__init__() + hidden_dim = int(2 * dim_multiplier * dim / 3) + hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of) + self.swish_linear = nn.Linear(dim, hidden_dim, bias=False) + self.gate_linear = nn.Linear(dim, hidden_dim, bias=False) + self.output_linear = nn.Linear(hidden_dim, dim, bias=False) + + def forward(self, x: Tensor) -> Tensor: + return self.output_linear(torch.nn.functional.silu(self.swish_linear(x)) * self.gate_linear(x)) + + +class SpaceTimeBlock(nn.Module): + """Pre-norm transformer block: spatial (bidirectional) attn, temporal (causal) attn, MLP. + + Operates on tokens shaped ``(B, T, H, W, C)``. Spatial attention is over the ``H*W`` tokens + within each frame; temporal attention is over the ``T`` frames (causal when ``causal=True``). + """ + + def __init__( + self, + dim: int, + num_heads: int, + num_kv_heads: int | None, + causal: bool, + mlp_dim_multiplier: int, + layerscale_init: float, + eps: float, + qk_norm: Literal["rmsnorm", "layernorm"] = "rmsnorm", + ): + super().__init__() + attn_config = SelfAttentionConfig( + embed_dim=dim, num_heads=num_heads, num_kv_heads=num_kv_heads, qk_norm=qk_norm + ) + self.space_norm = nn.LayerNorm(dim, eps=eps) + self.space_attn = SelfAttention(attn_config, causal=False) + self.space_ls = LayerScale(dim, layerscale_init) + + self.time_norm = nn.LayerNorm(dim, eps=eps) + self.time_attn = SelfAttention(attn_config, causal=causal) + self.time_ls = LayerScale(dim, layerscale_init) + + self.mlp_norm = nn.LayerNorm(dim, eps=eps) + self.mlp = SwiGLU(dim, dim_multiplier=mlp_dim_multiplier) + self.mlp_ls = LayerScale(dim, layerscale_init) + + def forward( + self, + x: Tensor, + rope_spatial: tuple[Tensor, Tensor], + rope_temporal: tuple[Tensor, Tensor], + ) -> Tensor: + b, t, h, w, _ = x.shape + + xs = rearrange(x, "b t h w c -> (b t) (h w) c") + xs = xs + self.space_ls(self.space_attn(self.space_norm(xs), rotary_emb=rope_spatial)) + + xt = rearrange(xs, "(b t) (h w) c -> (b h w) t c", b=b, t=t, h=h, w=w) + xt = xt + self.time_ls(self.time_attn(self.time_norm(xt), rotary_emb=rope_temporal)) + + x = rearrange(xt, "(b h w) t c -> b t h w c", b=b, h=h, w=w) + x = x + self.mlp_ls(self.mlp(self.mlp_norm(x))) + return x + + +class PatchUnembed(nn.Module): + """Project tokens to per-patch pixels and fold back into frames. + + ``(B, T, H//p, W//p, width) -> (B, T * patch_size_t, out_channels, H, W)``. + """ + + def __init__(self, out_channels: int, patch_size: int, width: int, patch_size_t: int = 1): + super().__init__() + self.patch_size = patch_size + self.patch_size_t = patch_size_t + self.out_channels = out_channels + self.proj = nn.Linear(width, out_channels * patch_size_t * patch_size * patch_size) + + def forward(self, x: Tensor) -> Tensor: + x = self.proj(x) + return rearrange( + x, + "b t h w (c pt p1 p2) -> b (t pt) c (h p1) (w p2)", + c=self.out_channels, + pt=self.patch_size_t, + p1=self.patch_size, + p2=self.patch_size, + ) + + +def _build_vit_blocks( + width: int, + depth: int, + num_heads: int, + num_kv_heads: int | None, + is_causal: bool, + mlp_dim_multiplier: int, + layerscale_init: float, + eps: float, + qk_norm: Literal["rmsnorm", "layernorm"], +) -> nn.ModuleList: + return nn.ModuleList( + [ + SpaceTimeBlock( + dim=width, + num_heads=num_heads, + num_kv_heads=num_kv_heads, + causal=is_causal, + mlp_dim_multiplier=mlp_dim_multiplier, + layerscale_init=layerscale_init, + eps=eps, + qk_norm=qk_norm, + ) + for _ in range(depth) + ] + ) + + +def _apply_vit_blocks( + blocks: nn.ModuleList, + x: Tensor, + rope_spatial: tuple[Tensor, Tensor], + rope_temporal: tuple[Tensor, Tensor], + activation_checkpointing: bool, + training: bool, +) -> Tensor: + for block in blocks: + if training and activation_checkpointing: + x = torch.utils.checkpoint.checkpoint(block, x, rope_spatial, rope_temporal, use_reentrant=False) # type: ignore[assignment] # checkpoint() is typed Optional but returns the block output + else: + x = block(x, rope_spatial, rope_temporal) + return x + + +class ViTVideoDecoder(nn.Module): + """Causal-video ViT decoder for the RAEv2 codec. + + A kxk strided ``ConvTranspose2d`` lifts the latent grid to the ViT grid (e.g. a /32 latent up + to a /16 ViT grid with ``stride=2``), followed by the space-time ViT blocks and patch unembed. + """ + + def __init__(self, config: ViTDecoderConfig) -> None: + super().__init__() + self.config = config + width = config.vit_width + self.head_dim = width // config.vit_num_heads + + self.from_latent = nn.ConvTranspose2d( + config.latent_dim, + width, + kernel_size=config.bottleneck.stride, + stride=config.bottleneck.stride, + bias=True, + ) + self.blocks = _build_vit_blocks( + width, + config.vit_depth, + config.vit_num_heads, + config.vit_num_kv_heads, + config.is_causal, + config.mlp_dim_multiplier, + config.layerscale_init, + config.eps, + config.qk_norm, + ) + self.norm_out = nn.LayerNorm(width, eps=config.eps) + self.patch_unembed = PatchUnembed( + config.out_channels, config.patch_size, width, patch_size_t=config.patch_size_t + ) + + self.apply(init_weights) + + @property + def last_layer_weight(self) -> Tensor: + return self.patch_unembed.proj.weight + + def forward(self, z: Tensor) -> Tensor: + # ConvTranspose2d: lift via channels-first, then back to channels-last for ViT blocks. + b, t = z.shape[:2] + x = rearrange(z, "b t c h w -> (b t) c h w") + x = self.from_latent(x) + x = rearrange(x, "(b t) c h w -> b t h w c", b=b, t=t) + + _, t, h, w, _ = x.shape + rope_spatial = spatial_rope(h, w, self.head_dim, self.config.rope_theta_spatial, x.device) + rope_temporal = temporal_rope(t, self.head_dim, self.config.rope_theta_temporal, x.device) + x = _apply_vit_blocks( + self.blocks, + x, + rope_spatial, + rope_temporal, + self.config.activation_checkpointing, + self.training, + ) + x = self.norm_out(x) + return torch.tanh(self.patch_unembed(x)) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/codec/viz.py b/release-20261107/source/workspace_joint/mira/src/mira/codec/viz.py new file mode 100644 index 0000000000000000000000000000000000000000..d59338d2a2365bbd95b353091220bc3876d8ebb8 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/codec/viz.py @@ -0,0 +1,147 @@ +"""Codec-specific visualizations: reconstruction side-by-side and latent diagnostics. + +These build W&B-loggable artifacts from a :class:`~mira.codec.codec_model.VideoCodecOutputs`: +a ground-truth/reconstruction side-by-side video, and interactive plots of the latent's correlation +structure and per-position standard deviation. +""" + +from __future__ import annotations + +from typing import Any, Literal + +import torch +from einops import rearrange + +from mira.codec.codec_model import VideoCodecOutputs + + +def visualize_side_by_side(model_outputs: VideoCodecOutputs) -> dict: + """Concatenate the ground-truth and reconstructed videos side by side (uint8, [0, 255]).""" + pred_video = (model_outputs.output_video * 0.5 + 0.5).clamp(0, 1) + gt_video = (model_outputs.input_video * 0.5 + 0.5).clamp(0, 1) + viz_video = torch.cat([gt_video, pred_video], dim=-1) + viz_video = (255 * viz_video).to(torch.uint8) + return {"viz_video": viz_video, "pred_video": pred_video} + + +def visualize_latent_correlation( + model_outputs: VideoCodecOutputs, + correlation_dim: Literal["patch", "channels", "time"], + caption: str | None = None, +) -> Any: + """Pearson correlation matrix of the video latent as an interactive plotly heatmap. + + "channels" -> (C, C) correlation, samples = (B, T, H, W). + "patch" -> (H*W, H*W) correlation, samples = (B, T, C). + "time" -> per-patch (T, T) correlation (samples = (B, C)), tiled into an (H*T, W*T) grid laid + out by patch coordinates (i=row, j=col). + """ + import numpy as np # noqa: PLC0415 -- optional viz deps, used only here + import plotly.graph_objects as go + import wandb + + z = model_outputs.z.float() # (B, T, C, H, W) + customdata = None + hovertemplate = "row=%{y}, col=%{x}
corr=%{z:.4f}" + if correlation_dim == "channels": + z_flat = rearrange(z, "b t c h w -> (b t h w) c") + z_flat = z_flat - z_flat.mean(dim=0, keepdim=True) + z_flat = z_flat / z_flat.std(dim=0, keepdim=True).clamp_min(1e-8) + corr = (z_flat.T @ z_flat) / (z_flat.shape[0] - 1) + title, x_title, y_title = "Latent Correlation (Channels)", "Channel", "Channel" + elif correlation_dim == "patch": + z_flat = rearrange(z, "b t c h w -> (b t c) (h w)") + z_flat = z_flat - z_flat.mean(dim=0, keepdim=True) + z_flat = z_flat / z_flat.std(dim=0, keepdim=True).clamp_min(1e-8) + corr = (z_flat.T @ z_flat) / (z_flat.shape[0] - 1) + title = "Latent Correlation (Patch)" + x_title, y_title = "Patch (h*W + w)", "Patch (h*W + w)" + elif correlation_dim == "time": + # Per-patch (T, T) correlation, with B*C samples, then tiled by (h, w). + z_patch = rearrange(z, "b t c h w -> h w (b c) t") + z_patch = z_patch - z_patch.mean(dim=2, keepdim=True) + z_patch = z_patch / z_patch.std(dim=2, keepdim=True).clamp_min(1e-8) + n_samples = z_patch.shape[2] + corr_per_patch = torch.einsum("hwnt,hwns->hwts", z_patch, z_patch) / (n_samples - 1) + corr = rearrange(corr_per_patch, "h w t1 t2 -> (h t1) (w t2)") + title = "Latent Correlation (Time, per patch)" + x_title, y_title = "w*T + t", "h*T + t" + H, W, T = z_patch.shape[0], z_patch.shape[1], z_patch.shape[3] + ys, xs = np.arange(H * T), np.arange(W * T) + i_grid = np.broadcast_to((ys // T)[:, None], (H * T, W * T)) + t1_grid = np.broadcast_to((ys % T)[:, None], (H * T, W * T)) + j_grid = np.broadcast_to((xs // T)[None, :], (H * T, W * T)) + t2_grid = np.broadcast_to((xs % T)[None, :], (H * T, W * T)) + customdata = np.stack([i_grid, j_grid, t1_grid, t2_grid], axis=-1) + hovertemplate = ( + "i=%{customdata[0]}, j=%{customdata[1]}
" + "t1=%{customdata[2]}, t2=%{customdata[3]}
" + "corr=%{z:.4f}" + ) + else: + raise ValueError(f"Invalid correlation_dim {correlation_dim}, must be 'channels', 'patch', or 'time'") + + corr_np = corr.detach().cpu().float().numpy() + heatmap_kwargs: dict[str, Any] = dict( + z=corr_np, colorscale="Greens", zmin=0, zmax=1, hovertemplate=hovertemplate + ) + if customdata is not None: + heatmap_kwargs["customdata"] = customdata + fig = go.Figure(data=[go.Heatmap(**heatmap_kwargs)]) + fig.update_layout( + title=title, + xaxis_title=x_title, + yaxis_title=y_title, + yaxis=dict(autorange="reversed", scaleanchor="x", scaleratio=1), + ) + return wandb.Plotly(fig) + + +def visualize_latent_std( + model_outputs: VideoCodecOutputs, + axis: Literal["patch", "channels"], +) -> Any: + """Per-position std of the video latent as an interactive plotly chart. + + "patch" computes std over (B, T, C) for each spatial position and renders a heatmap with i (row) + and j (col) patch coordinates on the axes. "channels" computes std over (B, T, H, W) for each + channel as a bar chart. + """ + import plotly.graph_objects as go # noqa: PLC0415 -- optional viz deps, used only here + import wandb + + z = model_outputs.z.float() # (B, T, C, H, W) + _, _, _, H, W = z.shape + + if axis == "patch": + grid = rearrange(z, "b t c h w -> h w (b t c)").std(dim=2).cpu().numpy() + fig = go.Figure( + data=[ + go.Heatmap( + z=grid, + x=list(range(W)), + y=list(range(H)), + colorscale="Greens", + hovertemplate="i=%{y}, j=%{x}
std=%{z:.4f}", + ) + ] + ) + fig.update_layout( + title="Latent Std per Patch", + xaxis_title="j (col)", + yaxis_title="i (row)", + yaxis=dict(autorange="reversed", scaleanchor="x", scaleratio=1), + ) + elif axis == "channels": + stds = rearrange(z, "b t c h w -> c (b t h w)").std(dim=1).cpu().tolist() + table = wandb.Table(data=[[i, v] for i, v in enumerate(stds)], columns=["channel", "std"]) + return wandb.plot_table( + "wandb/bar/v0", + table, + {"label": "channel", "value": "std"}, + {"title": "Latent Std per Channel"}, + ) + else: + raise ValueError(f"Invalid axis {axis!r}, must be 'patch' or 'channels'") + + return wandb.Plotly(fig) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/__init__.py b/release-20261107/source/workspace_joint/mira/src/mira/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a8f931b4aadc6b7bbcfabacbf1696f04c6863226 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/__init__.py @@ -0,0 +1,40 @@ +"""mira.data: loader for the 4-player Rocket League dataset. + +Each sample bundles the 4 perspectives of one ~4 s match chunk; a clip is taken from within one chunk. + +Public API: + RocketScienceDataset, MatchClip — load time-aligned 4-perspective clips (random access / streaming) + Index, MatchEntry, Perspective, Anchor — typed schema for the dataset index (`index.json`) + Vec3, Quat, GameInfo, BallState, CarState, FrameState — typed per-frame game state + KeyVocab, DEFAULT_RL_KEYS, tensorize_actions — multi-hot keyboard action parsing + Event, replay_spans — discrete game events with frame-index mapping + +The `physics` and `viz` submodules are optional helpers over a clip's per-frame state: `physics` is +numpy-only, while `viz` needs the `viz` extra plus a system `ffmpeg` on PATH. +""" + +from .actions import DEFAULT_RL_KEYS, KeyVocab, tensorize_actions +from .dataset import MatchClip, RocketScienceDataset +from .events import Event, replay_spans +from .schema import Anchor, Index, MatchEntry, Perspective +from .state import BallState, CarState, FrameState, GameInfo, Quat, Vec3 + +__all__ = [ + "RocketScienceDataset", + "MatchClip", + "Index", + "MatchEntry", + "Perspective", + "Anchor", + "Vec3", + "Quat", + "GameInfo", + "BallState", + "CarState", + "FrameState", + "KeyVocab", + "DEFAULT_RL_KEYS", + "tensorize_actions", + "Event", + "replay_spans", +] diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/action_v10.py b/release-20261107/source/workspace_joint/mira/src/mira/data/action_v10.py new file mode 100644 index 0000000000000000000000000000000000000000..9edf8826cd244d2090025e9598cfd5a633c97283 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/action_v10.py @@ -0,0 +1,310 @@ +"""Short-history Action data paired with World-v10 GT or predicted futures.""" + +from __future__ import annotations + +import bisect +import json +import random +from collections import defaultdict +from collections.abc import Sequence +from pathlib import Path +from typing import Any, Iterator + +import torch +from torch import Tensor +from torch.utils.data import Dataset, Sampler + +from mira.action_v6.model import ActionV6Batch +from mira.data.action_v6 import ( + PREDICTED_FUTURE_ELEMENTS, + PREDICTED_FUTURE_LOCATOR_SHIFT, + PREDICTED_FUTURE_LOCATOR_ROW_MASK, + PREDICTED_FUTURE_SHAPE, + decode_predicted_future_locator, +) +from mira.data.robotwin_wam_schema import sha256_file +from mira.data.world_v7 import HISTORY_LENGTHS, WorldV7Dataset + + +class ActionV10PredictedFutureCache: + def __init__( + self, + root: str | Path, + split: str, + *, + expected_rows: int, + expected_source_manifest: str | Path, + expected_world_fingerprint: str, + ) -> None: + self.root = Path(root).expanduser().resolve() + identity = json.loads( + (self.root / "predicted_future_cache_identity.json").read_text(encoding="utf-8") + ) + self.identity = identity + if identity.get("contract") not in { + "action-v10-short-history-world-v10-online", + "action-v11-short-history-world-v11-online", + "action-v12-eval-aligned-full-epoch-world-v12-online", + }: + raise ValueError("unexpected Action-v10 predicted-cache contract") + if identity.get("world_checkpoint_fingerprint") != expected_world_fingerprint: + raise ValueError("predicted cache belongs to another World-v10 checkpoint") + split_identity = identity["splits"][split] + if int(split_identity["expanded_rows"]) != expected_rows: + raise ValueError("predicted cache expanded-row count mismatch") + if split_identity["source_manifest_sha256"] != sha256_file(expected_source_manifest): + raise ValueError("predicted cache source manifest mismatch") + split_root = self.root / split + if not (split_root / "COMPLETE.json").is_file(): + raise ValueError(f"predicted cache split {split!r} is incomplete") + self.locators = torch.from_file( + str(split_root / "locators.i64"), + shared=False, + size=expected_rows, + dtype=torch.int64, + ) + self.available_indices = torch.nonzero(self.locators >= 0).flatten().tolist() + self.shards: dict[int, Tensor] = {} + for shard_text, metadata in split_identity["shards"].items(): + shard = int(shard_text) + rows = int(metadata["rows"]) + self.shards[shard] = torch.from_file( + str(split_root / metadata["tensor_file"]), + shared=False, + size=rows * PREDICTED_FUTURE_ELEMENTS, + dtype=torch.bfloat16, + ).reshape(rows, *PREDICTED_FUTURE_SHAPE) + + def has(self, index: int) -> bool: + return int(self.locators[index]) >= 0 + + def __getitem__(self, index: int) -> Tensor: + locator = int(self.locators[index]) + if locator < 0: + raise KeyError(f"expanded row {index} is absent from predicted cache") + shard, row = decode_predicted_future_locator(locator) + value = self.shards[shard][row] + if value.shape != PREDICTED_FUTURE_SHAPE or not torch.isfinite(value).all(): + raise RuntimeError("invalid Action-v10 predicted future") + return value + + +class ActionV10Dataset(Dataset[dict[str, Any]]): + """Use the exact World-v10 short-history alignment with adjacent actions.""" + + def __init__( + self, + *, + source_manifest: str | Path, + dataset_stats: str | Path, + qwen_cache_root: str | Path, + split: str, + latent_mean: float, + latent_std: float, + predicted_cache_root: str | Path | None = None, + predicted_world_fingerprint: str | None = None, + episode_cache_size: int = 4, + ) -> None: + self.world = WorldV7Dataset( + source_manifest=source_manifest, + dataset_stats=dataset_stats, + qwen_cache_root=qwen_cache_root, + split=split, + episode_cache_size=episode_cache_size, + ) + self.source_manifest = self.world.source_manifest + self.source_rows = self.world.source_rows + self.base_counts = self.world.base_counts + self.base_cumulative = self.world.base_cumulative + self.tasks = self.world.tasks + self.task_domain_episodes = self.world.task_domain_episodes + self.latent_mean = float(latent_mean) + self.latent_std = float(latent_std) + if self.latent_std <= 0: + raise ValueError("latent_std must be positive") + self.predicted_cache = None + if predicted_cache_root is not None: + if predicted_world_fingerprint is None: + raise ValueError("predicted World fingerprint is required") + self.predicted_cache = ActionV10PredictedFutureCache( + predicted_cache_root, + split, + expected_rows=len(self), + expected_source_manifest=self.source_manifest, + expected_world_fingerprint=predicted_world_fingerprint, + ) + + def __len__(self) -> int: + return len(self.world) + + def expanded_index(self, episode: int, latent_start: int, history_index: int) -> int: + return self.world.expanded_index(episode, latent_start, history_index) + + def locate(self, index: int) -> tuple[int, int, int]: + base_global, history_index = divmod(index, len(HISTORY_LENGTHS)) + episode = bisect.bisect_right(self.base_cumulative, base_global) - 1 + latent_start = base_global - self.base_cumulative[episode] + return episode, latent_start, history_index + + def __getitem__(self, request: int | tuple[int, int]) -> dict[str, Any]: + if isinstance(request, tuple): + index, future_source = map(int, request) + else: + index, future_source = int(request), 0 + world_sample = self.world[index] + metadata = dict(world_sample["metadata"]) + episode = self.world._episode(str(self.source_rows[metadata["episode_index"]]["cache_path"])) + current_latent = int(metadata["current_latent"]) + action_start = 2 * current_latent + 1 + action = episode["action20_f32"][action_start : action_start + 20].float().reshape(20, 2, 7) + if action.shape != (20, 2, 7) or not torch.isfinite(action).all(): + raise RuntimeError("truncated/non-finite Action-v10 target") + if future_source == 0: + future = (world_sample["z_future_raw"].float() - self.latent_mean) / self.latent_std + source_name = "gt" + elif future_source == 1: + if self.predicted_cache is None: + raise RuntimeError("predicted future requested before cache completion") + future = self.predicted_cache[index] + source_name = "world_pred" + else: + raise ValueError("future_source must be 0 or 1") + metadata.update( + { + "window_id": f"{metadata['episode_sha256']}:{metadata['latent_start']}:h{metadata['history_length']}", + "action_start_20hz": action_start, + "future_source": source_name, + } + ) + return { + "z_current": ( + world_sample["z_context_raw"][:, -1:].float() - self.latent_mean + ) / self.latent_std, + "z_future_cond": future, + "state_history": world_sample["state_history"], + "state_valid_mask": world_sample["history_valid"], + "action_gt": action, + "action_valid_mask": torch.ones(20, dtype=torch.bool), + "future_source": torch.tensor(future_source, dtype=torch.int64), + "metadata": metadata, + } + + def validation_indices(self) -> list[int]: + if self.predicted_cache is None: + return [] + values = self.predicted_cache.available_indices + # Put episode-start H1 first, then retain deterministic mixed histories. + return sorted(values, key=lambda index: (0 if self.locate(index)[2] == 0 else 1, index)) + + +def collate_action_v10(samples: list[dict[str, Any]]) -> tuple[ActionV6Batch, list[dict[str, Any]]]: + from mira.data.action_v6 import collate_action_v6 + + return collate_action_v6(samples) + + +def predicted_probability_v10(step: int, *, predicted_start_step: int = 10_000) -> float: + return 0.0 if step < predicted_start_step else 1.0 + + +class ActionV10Sampler(Sampler[tuple[int, int]]): + """Exact global 50% H1 and GT-to-predicted source switch at step 10k.""" + + def __init__( + self, + dataset: ActionV10Dataset, + *, + seed: int, + rank: int, + world_size: int, + micro_batch: int, + accumulation: int, + predicted_start_step: int = 10_000, + clean_probability: float = 0.5, + supplemental_expanded_index: int | None = None, + ) -> None: + if world_size != 8 or micro_batch * accumulation * world_size != 512: + raise ValueError("Action-v10 sampler requires the audited global batch 512") + self.dataset = dataset + self.seed = seed + self.rank = rank + self.world_size = world_size + self.micro_batch = micro_batch + self.accumulation = accumulation + self.predicted_start_step = int(predicted_start_step) + self.clean_probability = clean_probability + self.supplemental_expanded_index = supplemental_expanded_index + self.consumed = 0 + self.predicted_buckets: dict[tuple[int, str, str], list[int]] = defaultdict(list) + if dataset.predicted_cache is not None: + for index in dataset.predicted_cache.available_indices: + episode, _latent_start, history_index = dataset.locate(index) + row = dataset.source_rows[episode] + self.predicted_buckets[(history_index, str(row["task"]), str(row["domain"]))].append(index) + + def __len__(self) -> int: + return 2**31 + + @staticmethod + def _history_index(global_position: int) -> int: + local_position, rank = divmod(global_position, 8) + optimizer_step, local_slot = divmod(local_position, 64) + if (local_slot + rank) % 2 == 0: + return 0 + other_ordinal = local_slot * 4 + rank // 2 + return 1 + ((other_ordinal + optimizer_step * 256) % 3) + + def __iter__(self) -> Iterator[tuple[int, int]]: + position = self.consumed + local_per_step = self.micro_batch * self.accumulation + while True: + global_position = position * self.world_size + self.rank + optimizer_step = position // local_per_step + local_position, global_rank = divmod(global_position, self.world_size) + _step, local_slot = divmod(local_position, local_per_step) + if ( + self.supplemental_expanded_index is not None + and global_rank == 0 + and local_slot == 0 + ): + if self.predicted_start_step > optimizer_step: + raise RuntimeError("supplemental replay requires predicted-future training") + if not self.dataset.predicted_cache or not self.dataset.predicted_cache.has( + self.supplemental_expanded_index + ): + raise RuntimeError("supplemental lift_pot row is absent from predicted cache") + yield self.supplemental_expanded_index, 1 + position += 1 + continue + history_index = self._history_index(global_position) + rng = random.Random(self.seed + global_position * 1_000_003) + task = self.dataset.tasks[rng.randrange(len(self.dataset.tasks))] + desired = "clean" if rng.random() < self.clean_probability else "randomized" + domains = self.dataset.task_domain_episodes[task] + domain = desired if desired in domains else sorted(domains)[rng.randrange(len(domains))] + source = int( + predicted_probability_v10( + optimizer_step, predicted_start_step=self.predicted_start_step + ) + ) + if source: + bucket = self.predicted_buckets.get((history_index, task, domain), []) + if not bucket: + raise RuntimeError(f"no predicted h{HISTORY_LENGTHS[history_index]} cache for {task}/{domain}") + index = bucket[rng.randrange(len(bucket))] + else: + episodes = domains[domain] + episode = episodes[rng.randrange(len(episodes))] + latent_start = 0 if history_index == 0 else rng.randrange(self.dataset.base_counts[episode]) + index = self.dataset.expanded_index(episode, latent_start, history_index) + yield index, source + position += 1 + + def mark_consumed(self, count: int) -> None: + self.consumed += int(count) + + def state_dict(self) -> dict[str, int]: + return {"consumed": self.consumed} + + def load_state_dict(self, value: dict[str, int]) -> None: + self.consumed = int(value["consumed"]) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/action_v12.py b/release-20261107/source/workspace_joint/mira/src/mira/data/action_v12.py new file mode 100644 index 0000000000000000000000000000000000000000..515296078ea26532ce3e7e5faf206a00b522f559 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/action_v12.py @@ -0,0 +1,179 @@ +"""Eval-aligned full-epoch sampling for Action-v12. + +H1/H3/H6 are growing prefixes and are therefore legal only at episode start. +H10 sweeps every legal latent start without replacement. The layout mirrors +``WorldV12EvalAlignedSampler`` while returning the future-source bit required +by the Action dataset. +""" + +from __future__ import annotations + +import math +import random +from collections.abc import Sequence +from typing import Iterator + +from torch.utils.data import Sampler + +from mira.data.action_v6_sampler import predicted_probability +from mira.data.action_v10 import ActionV10Dataset +from mira.data.world_v7 import HISTORY_LENGTHS + + +class ActionV12EpochSampler(Sampler[tuple[int, int]]): + """Exact 25% H1/H3/H6/H10 with deterministic full-cache sweeps.""" + + _WORLD_SIZE = 8 + + def __init__( + self, + dataset: ActionV10Dataset, + *, + seed: int, + rank: int, + world_size: int, + micro_batch: int, + accumulation: int, + curriculum: Sequence[tuple[int, int, float, float]], + optimizer_step_offset: int = 0, + ) -> None: + local_per_step = int(micro_batch) * int(accumulation) + if world_size != self._WORLD_SIZE: + raise ValueError("Action-v12 sampler requires eight ranks") + if local_per_step <= 0: + raise ValueError("Action-v12 sampler requires a positive local batch") + if (local_per_step * world_size) % len(HISTORY_LENGTHS): + raise ValueError("global batch must divide evenly across four histories") + if dataset.world.base_windows <= 0 or not dataset.source_rows: + raise ValueError("Action-v12 requires non-empty episode and H10 strata") + if optimizer_step_offset < 0: + raise ValueError("Action-v12 optimizer-step offset cannot be negative") + self.dataset = dataset + self.seed = int(seed) + self.rank = int(rank) + self.world_size = int(world_size) + self.micro_batch = int(micro_batch) + self.accumulation = int(accumulation) + self.local_per_step = local_per_step + self.curriculum = tuple(tuple(value) for value in curriculum) + self.optimizer_step_offset = int(optimizer_step_offset) + self.consumed = 0 + self._affine_cache: dict[tuple[int, int], tuple[int, int]] = {} + self._gate_buckets: dict[int, list[int]] = {index: [] for index in range(4)} + if dataset.predicted_cache is not None: + for index in dataset.predicted_cache.available_indices: + self._gate_buckets[dataset.locate(index)[2]].append(index) + + def __len__(self) -> int: + return 2**31 + + @classmethod + def layout( + cls, global_position: int, local_per_step: int + ) -> tuple[int, int, int, int]: + local_position, rank = divmod(global_position, cls._WORLD_SIZE) + optimizer_step, local_slot = divmod(local_position, local_per_step) + history_index = (local_slot + rank + optimizer_step) % len(HISTORY_LENGTHS) + return optimizer_step, local_slot, rank, history_index + + @classmethod + def history_ordinal(cls, global_position: int, local_per_step: int) -> tuple[int, int]: + optimizer_step, local_slot, rank, history_index = cls.layout( + global_position, local_per_step + ) + preceding = 0 + for previous_slot in range(local_slot + 1): + rank_limit = rank if previous_slot == local_slot else cls._WORLD_SIZE + for previous_rank in range(rank_limit): + previous_history = ( + previous_slot + previous_rank + optimizer_step + ) % len(HISTORY_LENGTHS) + preceding += int(previous_history == history_index) + rows_per_history = cls._WORLD_SIZE * local_per_step // len(HISTORY_LENGTHS) + return history_index, optimizer_step * rows_per_history + preceding + + def _affine_parameters(self, history_index: int, epoch: int, size: int) -> tuple[int, int]: + key = (history_index, epoch) + if key in self._affine_cache: + return self._affine_cache[key] + rng = random.Random( + self.seed + history_index * 1_000_003 + epoch * 10_000_019 + size * 97 + ) + multiplier = rng.randrange(1, size + 1) + while math.gcd(multiplier, size) != 1: + multiplier = 1 if multiplier == size else multiplier + 1 + offset = rng.randrange(size) + self._affine_cache[key] = (multiplier, offset) + return multiplier, offset + + def _permuted(self, history_index: int, ordinal: int, size: int) -> int: + epoch, position = divmod(ordinal, size) + multiplier, offset = self._affine_parameters(history_index, epoch, size) + return (multiplier * position + offset) % size + + def __iter__(self) -> Iterator[tuple[int, int]]: + position = self.consumed + episode_count = len(self.dataset.source_rows) + while True: + absolute_position = ( + position + self.optimizer_step_offset * self.local_per_step + ) + global_position = absolute_position * self.world_size + self.rank + optimizer_step, _slot, _rank, _history = self.layout( + global_position, self.local_per_step + ) + history_index, ordinal = self.history_ordinal( + global_position, self.local_per_step + ) + if history_index < 3: + episode = self._permuted(history_index, ordinal, episode_count) + index = self.dataset.expanded_index(episode, 0, history_index) + else: + base_global = self._permuted( + history_index, ordinal, self.dataset.world.base_windows + ) + index = base_global * len(HISTORY_LENGTHS) + history_index + probability = predicted_probability( + optimizer_step, curriculum=self.curriculum + ) + rng = random.Random(self.seed + global_position * 1_000_003 + 17) + future_source = int(rng.random() < probability) + if future_source and ( + self.dataset.predicted_cache is None + or not self.dataset.predicted_cache.has(index) + ): + scope = ( + self.dataset.predicted_cache.identity["splits"]["train"].get( + "cache_scope" + ) + if self.dataset.predicted_cache is not None + else None + ) + bucket = self._gate_buckets[history_index] + if scope != "bounded_gate" or not bucket: + raise RuntimeError( + f"Action-v12 predicted cache misses aligned expanded row {index}" + ) + index = bucket[ordinal % len(bucket)] + yield index, future_source + position += 1 + + def mark_consumed(self, count: int) -> None: + self.consumed += int(count) + + def state_dict(self) -> dict[str, int]: + return { + "consumed": self.consumed, + "local_per_step": self.local_per_step, + "optimizer_step_offset": self.optimizer_step_offset, + } + + def load_state_dict(self, value: dict[str, int]) -> None: + if int(value.get("local_per_step", self.local_per_step)) != self.local_per_step: + raise ValueError("Action-v12 batch layout changed across resume") + if ( + int(value.get("optimizer_step_offset", self.optimizer_step_offset)) + != self.optimizer_step_offset + ): + raise ValueError("Action-v12 optimizer-step offset changed across resume") + self.consumed = int(value["consumed"]) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/action_v6.py b/release-20261107/source/workspace_joint/mira/src/mira/data/action_v6.py new file mode 100644 index 0000000000000000000000000000000000000000..164b46de233329a2c98e8123b1383dc15208d7bf --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/action_v6.py @@ -0,0 +1,298 @@ +"""Action-v6 windows joined to immutable World-v6 latent/source identities.""" + +from __future__ import annotations + +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import torch +from safetensors.torch import load_file +from torch import Tensor +from torch.utils.data import Dataset + +from mira.action_v6.model import ActionV6Batch +from mira.data.robotwin_wam_schema import read_jsonl +from mira.data.world_v6 import WorldV6Dataset, window_id + +PREDICTED_FUTURE_SHAPE = (3, 10, 32, 9, 12) +PREDICTED_FUTURE_ELEMENTS = 3 * 10 * 32 * 9 * 12 +PREDICTED_FUTURE_LOCATOR_SHIFT = 48 +PREDICTED_FUTURE_LOCATOR_ROW_MASK = (1 << PREDICTED_FUTURE_LOCATOR_SHIFT) - 1 + + +def encode_predicted_future_locator(shard: int, row: int) -> int: + """Pack an uint8 shard and row into a non-negative signed int64.""" + if not 0 <= shard < 256: + raise ValueError("predicted-future shard must fit in uint8") + if not 0 <= row <= PREDICTED_FUTURE_LOCATOR_ROW_MASK: + raise ValueError("predicted-future row exceeds the locator namespace") + return (shard << PREDICTED_FUTURE_LOCATOR_SHIFT) | row + + +def decode_predicted_future_locator(locator: int) -> tuple[int, int]: + if locator < 0: + raise ValueError("negative predicted-future locator is the missing sentinel") + return ( + locator >> PREDICTED_FUTURE_LOCATOR_SHIFT, + locator & PREDICTED_FUTURE_LOCATOR_ROW_MASK, + ) + + +class PredictedFutureCacheReader: + def __init__( + self, + root: str | Path, + split: str, + *, + expected_windows: int, + expected_manifest_sha256: str, + expected_world_sha256: str, + ) -> None: + self.root = Path(root).expanduser().resolve() + identity_path = self.root / "predicted_future_cache_identity.json" + identity = json.loads(identity_path.read_text(encoding="utf-8")) + if identity["world_checkpoint_sha256"] != expected_world_sha256: + raise ValueError("predicted-future cache belongs to another World checkpoint") + split_identity = identity["splits"][split] + if int(split_identity["manifest_windows"]) != expected_windows: + raise ValueError("predicted-future cache manifest length mismatch") + if split_identity["window_manifest_sha256"] != expected_manifest_sha256: + raise ValueError("predicted-future cache manifest SHA mismatch") + split_root = self.root / split + if not (split_root / "COMPLETE.json").is_file(): + raise ValueError(f"predicted-future cache split {split!r} is incomplete") + self.locators = torch.from_file( + str(split_root / "locators.i64"), + shared=False, + size=expected_windows, + dtype=torch.int64, + ) + self.shards: dict[int, Tensor] = {} + for shard_text, metadata in sorted( + split_identity["shards"].items(), key=lambda item: int(item[0]) + ): + shard = int(shard_text) + rows = int(metadata["rows"]) + path = split_root / metadata["tensor_file"] + value = ( + torch.from_file( + str(path), + shared=False, + size=rows * PREDICTED_FUTURE_ELEMENTS, + dtype=torch.bfloat16, + ).reshape(rows, *PREDICTED_FUTURE_SHAPE) + if rows + else torch.empty((0, *PREDICTED_FUTURE_SHAPE), dtype=torch.bfloat16) + ) + self.shards[shard] = value + + def has(self, index: int) -> bool: + return int(self.locators[index]) >= 0 + + def __getitem__(self, index: int) -> Tensor: + locator = int(self.locators[index]) + if locator < 0: + raise KeyError(f"window {index} is not in the predicted-future subset") + shard, row = decode_predicted_future_locator(locator) + if shard not in self.shards or row >= len(self.shards[shard]): + raise RuntimeError("invalid predicted-future locator") + value = self.shards[shard][row] + if value.shape != PREDICTED_FUTURE_SHAPE or not torch.isfinite(value).all(): + raise RuntimeError("invalid predicted-future tensor") + return value + + +class ActionV6Dataset(WorldV6Dataset): + def __init__( + self, + *, + latent_mean: float, + latent_std: float, + predicted_cache_root: str | Path | None = None, + predicted_world_sha256: str | None = None, + split: str, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if latent_std <= 0: + raise ValueError("latent_std must be positive") + self.latent_mean = float(latent_mean) + self.latent_std = float(latent_std) + self.split = split + self.predicted_cache = None + if predicted_cache_root is not None: + if predicted_world_sha256 is None: + raise ValueError("predicted World identity is required with a cache") + self.predicted_cache = PredictedFutureCacheReader( + predicted_cache_root, + split, + expected_windows=len(self), + expected_manifest_sha256=self.window_manifest_sha256, + expected_world_sha256=predicted_world_sha256, + ) + + def _normalize_latent(self, value: Tensor) -> Tensor: + return (value.float() - self.latent_mean) / self.latent_std + + def __getitem__(self, request: int | tuple[int, int]) -> dict[str, Any]: + if isinstance(request, tuple): + index, future_source = int(request[0]), int(request[1]) + else: + index, future_source = int(request), 0 + source_index = int(self.source_indices[index]) + episode_index, latent_start = self._locate_source(source_index) + row = self.source_rows[episode_index] + episode = self._episode(str(row["cache_path"])) + latent = episode["world_latent_raw_bf16"] + context = latent[:, latent_start : latent_start + 10] + future = latent[:, latent_start + 10 : latent_start + 20] + state_start = 2 * latent_start + state = self._normalize_state( + episode["joint_target_state20_f32"][state_start : state_start + 20] + ).reshape(20, 2, 7) + action_start = 2 * latent_start + 19 + action = episode["action20_f32"][action_start : action_start + 20].float().reshape(20, 2, 7) + if context.shape != (3, 10, 32, 9, 12) or future.shape != (3, 10, 32, 9, 12): + raise RuntimeError("truncated Action-v6 latent window") + if state.shape != (20, 2, 7) or action.shape != (20, 2, 7): + raise RuntimeError("truncated Action-v6 state/action window") + if not torch.isfinite(state).all() or not torch.isfinite(action).all(): + raise FloatingPointError("Action-v6 window contains non-finite state/action") + identifier = window_id(str(row["episode_sha256"]), latent_start) + if future_source == 0: + future_condition = self._normalize_latent(future) + source_name = "gt" + elif future_source == 1: + if self.predicted_cache is None: + raise RuntimeError("predicted future requested without a certified cache") + future_condition = self.predicted_cache[index] + source_name = "world_pred" + else: + raise ValueError("future_source must be 0 (gt) or 1 (world_pred)") + return { + "z_current": self._normalize_latent(context[:, -1:]), + "z_future_cond": future_condition, + "state_history": state, + "state_valid_mask": torch.ones(20, dtype=torch.bool), + "action_gt": action, + "action_valid_mask": torch.ones(20, dtype=torch.bool), + "future_source": torch.tensor(future_source, dtype=torch.int64), + "metadata": { + "window_id": identifier, + "source_index": source_index, + "episode_sha256": row["episode_sha256"], + "latent_start": latent_start, + "action_start_20hz": action_start, + "task": row["task"], + "domain": row["domain"], + "future_source": source_name, + }, + } + + +def collate_action_v6(samples: list[dict[str, Any]]) -> tuple[ActionV6Batch, list[dict[str, Any]]]: + batch = ActionV6Batch( + z_current=torch.stack([sample["z_current"] for sample in samples]), + z_future_cond=torch.stack([sample["z_future_cond"] for sample in samples]), + state_history=torch.stack([sample["state_history"] for sample in samples]), + state_valid_mask=torch.stack([sample["state_valid_mask"] for sample in samples]), + action_gt=torch.stack([sample["action_gt"] for sample in samples]), + action_valid_mask=torch.stack([sample["action_valid_mask"] for sample in samples]), + future_source=torch.stack([sample["future_source"] for sample in samples]), + ) + return batch, [sample["metadata"] for sample in samples] + + +class ExactColdStartDataset(Dataset[dict[str, Any]]): + """Deployment-exact repeat-20 cold starts with immutable expert labels.""" + + def __init__(self, manifest: str | Path) -> None: + self.manifest_path = Path(manifest).expanduser().resolve() + self.rows = read_jsonl(self.manifest_path) + complete = self.manifest_path.parent / "COMPLETE.json" + if not complete.is_file(): + raise ValueError(f"exact-cold cache is incomplete: {complete}") + self.identity = json.loads(complete.read_text(encoding="utf-8")) + if int(self.identity["rows"]) != len(self.rows): + raise ValueError("exact-cold manifest row count differs from COMPLETE identity") + if self.identity.get("contract") != "deployment_exact_repeat20_initial_rgb_and_state_to_world97314_ema": + raise ValueError("unexpected exact-cold cache contract") + self.task_domain_rows: dict[str, dict[str, list[int]]] = defaultdict( + lambda: defaultdict(list) + ) + for index, row in enumerate(self.rows): + self.task_domain_rows[str(row["task"])][str(row["domain"])].append(index) + + def __len__(self) -> int: + return len(self.rows) + + def __getitem__(self, index: int) -> dict[str, Any]: + row = self.rows[index] + value = load_file(str(row["tensor_path"]), device="cpu") + expected = { + "z_current": (3, 1, 32, 9, 12), + "z_future_cond": (3, 10, 32, 9, 12), + "state_history": (20, 2, 7), + "action_gt": (20, 2, 7), + } + for key, shape in expected.items(): + if tuple(value[key].shape) != shape or not torch.isfinite(value[key]).all(): + raise RuntimeError(f"invalid exact-cold tensor {key} for row {index}") + return { + "z_current": value["z_current"], + "z_future_cond": value["z_future_cond"], + "state_history": value["state_history"], + "state_valid_mask": torch.ones(20, dtype=torch.bool), + "action_gt": value["action_gt"], + "action_valid_mask": torch.ones(20, dtype=torch.bool), + "future_source": torch.tensor(2, dtype=torch.int64), + "metadata": { + "window_id": f"exact-cold:{row['episode_sha256']}", + "episode_sha256": row["episode_sha256"], + "task": row["task"], + "domain": row["domain"], + "future_source": "world_pred_exact_cold", + "sample_source": "exact_cold", + }, + } + + +class ActionV7MixedDataset(Dataset[dict[str, Any]]): + """Join expert windows, exact cold starts, and indexed critical events.""" + + def __init__( + self, + expert: ActionV6Dataset, + cold: ExactColdStartDataset, + critical_index: str | Path, + ) -> None: + self.expert = expert + self.cold = cold + critical_path = Path(critical_index).expanduser().resolve() + size = critical_path.stat().st_size // 8 + if size <= 0 or critical_path.stat().st_size != size * 8: + raise ValueError("critical-event index is empty or not packed int64") + self.critical = torch.from_file( + str(critical_path), shared=False, size=size, dtype=torch.int64 + ) + if int(self.critical.min()) < 0 or int(self.critical.max()) >= len(expert): + raise ValueError("critical-event index points outside expert dataset") + + def __len__(self) -> int: + return len(self.expert) + len(self.cold) + + def __getitem__(self, request: tuple[int, int, int]) -> dict[str, Any]: + source, index, future_source = map(int, request) + if source == 0: + sample = self.expert[index, future_source] + sample["metadata"]["sample_source"] = "expert_regular" + return sample + if source == 1: + return self.cold[index] + if source == 2: + sample = self.expert[int(self.critical[index]), 1] + sample["metadata"]["sample_source"] = "expert_critical" + return sample + raise ValueError(f"unknown Action-v7 sample source: {source}") diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/action_v6_sampler.py b/release-20261107/source/workspace_joint/mira/src/mira/data/action_v6_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..5c3b1047044d402826f5bf298c4bc4895e7552a4 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/action_v6_sampler.py @@ -0,0 +1,299 @@ +"""Task/domain/future-source balanced sampler with exact deterministic resume.""" + +from __future__ import annotations + +import bisect +import random +from collections import defaultdict +from collections.abc import Sequence +from typing import Iterator + +import numpy as np +from torch.utils.data import Sampler + +from .action_v6 import ActionV6Dataset, ActionV7MixedDataset + + +def predicted_probability( + step: int, + *, + compressed_total: int | None = None, + curriculum: Sequence[tuple[int, int, float, float]] | None = None, +) -> float: + if curriculum is not None: + if compressed_total is not None: + raise ValueError("explicit curriculum cannot be combined with compressed_total") + if not curriculum: + raise ValueError("curriculum must not be empty") + for start, end, start_p, end_p in curriculum: + if end <= start or not (0.0 <= start_p <= 1.0 and 0.0 <= end_p <= 1.0): + raise ValueError("invalid predicted-future curriculum segment") + if start <= step < end: + progress = (step - start) / (end - start) + return start_p + progress * (end_p - start_p) + if step < curriculum[0][0]: + return curriculum[0][2] + return curriculum[-1][3] + if compressed_total is not None: + if compressed_total <= 0: + raise ValueError("compressed curriculum length must be positive") + step = min(99_999, int(step * 100_000 / compressed_total)) + if step < 10_000: + return 0.0 + if step < 40_000: + return 0.5 * (step - 10_000) / 30_000 + if step < 80_000: + return 0.5 + if step < 90_000: + return 0.5 + 0.25 * (step - 80_000) / 10_000 + return 0.75 + + +class ActionV6BalancedSampler(Sampler[tuple[int, int]]): + def __init__( + self, + dataset: ActionV6Dataset, + *, + seed: int, + rank: int, + world_size: int, + micro_batch: int, + accumulation: int, + clean_probability: float = 0.5, + compressed_curriculum_steps: int | None = None, + curriculum: Sequence[tuple[int, int, float, float]] | None = None, + force_gt: bool = False, + ) -> None: + if not dataset.full_identity_index: + raise ValueError("formal Action sampler requires the full immutable window index") + self.dataset = dataset + self.seed = seed + self.rank = rank + self.world_size = world_size + self.micro_batch = micro_batch + self.accumulation = accumulation + self.clean_probability = clean_probability + self.compressed_curriculum_steps = compressed_curriculum_steps + self.curriculum = tuple(curriculum) if curriculum is not None else None + self.force_gt = force_gt + self.consumed = 0 + self.full_strata: dict[tuple[str, str], tuple[list[int], list[int]]] = {} + for task, domains in dataset.task_domain_episodes.items(): + for domain, episodes in domains.items(): + cumulative = [] + total = 0 + for episode in episodes: + total += dataset.source_window_counts[episode] + cumulative.append(total) + if total <= 0: + raise RuntimeError(f"empty full-train Action stratum: {task}/{domain}") + self.full_strata[(task, domain)] = (episodes, cumulative) + self.predicted_buckets: dict[tuple[str, str], list[int]] = defaultdict(list) + if dataset.predicted_cache is not None: + for index in range(len(dataset)): + if dataset.predicted_cache.has(index): + episode, _ = dataset._locate_source(int(dataset.source_indices[index])) + row = dataset.source_rows[episode] + self.predicted_buckets[(str(row["task"]), str(row["domain"]))].append(index) + + def __len__(self) -> int: + return 2**31 + + def __iter__(self) -> Iterator[tuple[int, int]]: + position = self.consumed + while True: + global_position = position * self.world_size + self.rank + rng = random.Random(self.seed + global_position * 1_000_003) + task = self.dataset.tasks[rng.randrange(len(self.dataset.tasks))] + desired = "clean" if rng.random() < self.clean_probability else "randomized" + domains = self.dataset.task_domain_episodes[task] + domain = desired if desired in domains else sorted(domains)[rng.randrange(len(domains))] + optimizer_step = position // (self.micro_batch * self.accumulation) + probability = 0.0 if self.force_gt else predicted_probability( + optimizer_step, + compressed_total=self.compressed_curriculum_steps, + curriculum=self.curriculum, + ) + use_predicted = rng.random() < probability + if use_predicted: + candidates = self.predicted_buckets.get((task, domain), []) + if not candidates: + raise RuntimeError(f"predicted cache has no candidate for {task}/{domain}") + index = candidates[rng.randrange(len(candidates))] + source = 1 + else: + episodes, cumulative = self.full_strata[(task, domain)] + stratum_offset = rng.randrange(cumulative[-1]) + episode_position = bisect.bisect_right(cumulative, stratum_offset) + episode = episodes[episode_position] + previous = cumulative[episode_position - 1] if episode_position else 0 + latent_start = stratum_offset - previous + index = self.dataset.source_window_index(episode, latent_start) + source = 0 + yield index, source + position += 1 + + def mark_consumed(self, count: int) -> None: + self.consumed += int(count) + + def state_dict(self) -> dict[str, int]: + return {"consumed": self.consumed} + + def load_state_dict(self, value: dict[str, int]) -> None: + self.consumed = int(value["consumed"]) + + +class ActionV7CorrectiveSampler(Sampler[tuple[int, int, int]]): + """Deterministic 50/40/10 expert/cold/critical corrective mixture.""" + + def __init__( + self, + dataset: ActionV7MixedDataset, + *, + seed: int, + rank: int, + world_size: int, + regular_share: float = 0.5, + cold_share: float = 0.4, + critical_share: float = 0.1, + regular_predicted_probability: float = 0.75, + clean_probability: float = 0.5, + ) -> None: + shares = (regular_share, cold_share, critical_share) + if any(value < 0 for value in shares) or abs(sum(shares) - 1.0) > 1e-9: + raise ValueError("Action-v7 source shares must be non-negative and sum to one") + if not 0 <= regular_predicted_probability <= 1: + raise ValueError("regular predicted probability must be in [0,1]") + self.dataset = dataset + self.seed = seed + self.rank = rank + self.world_size = world_size + self.regular_share = regular_share + self.cold_boundary = regular_share + cold_share + self.regular_predicted_probability = regular_predicted_probability + self.clean_probability = clean_probability + self.consumed = 0 + self.tasks = sorted(dataset.expert.tasks) + self.full_strata: dict[tuple[str, str], tuple[list[int], list[int]]] = {} + for task, domains in dataset.expert.task_domain_episodes.items(): + for domain, episodes in domains.items(): + cumulative = [] + total = 0 + for episode in episodes: + total += dataset.expert.source_window_counts[episode] + cumulative.append(total) + self.full_strata[(task, domain)] = (episodes, cumulative) + self.predicted_buckets: dict[tuple[str, str], list[int]] = defaultdict(list) + cache = dataset.expert.predicted_cache + if cache is None: + raise ValueError("Action-v7 requires the certified predicted-future cache") + for index in range(len(dataset.expert)): + if cache.has(index): + episode, _ = dataset.expert._locate_source( + int(dataset.expert.source_indices[index]) + ) + row = dataset.expert.source_rows[episode] + self.predicted_buckets[(str(row["task"]), str(row["domain"]))].append(index) + self.critical_buckets: dict[tuple[str, str], list[int]] = defaultdict(list) + for critical_row, dataset_index in enumerate(dataset.critical.tolist()): + episode, _ = dataset.expert._locate_source( + int(dataset.expert.source_indices[dataset_index]) + ) + row = dataset.expert.source_rows[episode] + self.critical_buckets[(str(row["task"]), str(row["domain"]))].append( + critical_row + ) + + def __len__(self) -> int: + return 2**31 + + def __iter__(self) -> Iterator[tuple[int, int, int]]: + position = self.consumed + while True: + global_position = position * self.world_size + self.rank + rng = random.Random(self.seed + global_position * 1_000_003) + task = self.tasks[rng.randrange(len(self.tasks))] + desired = "clean" if rng.random() < self.clean_probability else "randomized" + domains = self.dataset.expert.task_domain_episodes[task] + domain = desired if desired in domains else sorted(domains)[rng.randrange(len(domains))] + draw = rng.random() + if draw < self.regular_share: + predicted = rng.random() < self.regular_predicted_probability + if predicted: + bucket = self.predicted_buckets[(task, domain)] + yield 0, bucket[rng.randrange(len(bucket))], 1 + else: + episodes, cumulative = self.full_strata[(task, domain)] + offset = rng.randrange(cumulative[-1]) + episode_position = bisect.bisect_right(cumulative, offset) + episode = episodes[episode_position] + previous = cumulative[episode_position - 1] if episode_position else 0 + latent_start = offset - previous + yield 0, self.dataset.expert.source_window_index(episode, latent_start), 0 + elif draw < self.cold_boundary: + bucket = self.dataset.cold.task_domain_rows[task][domain] + yield 1, bucket[rng.randrange(len(bucket))], 2 + else: + bucket = self.critical_buckets.get((task, domain), []) + if not bucket: + raise RuntimeError(f"no critical predicted window for {task}/{domain}") + yield 2, bucket[rng.randrange(len(bucket))], 1 + position += 1 + + def mark_consumed(self, count: int) -> None: + self.consumed += int(count) + + def state_dict(self) -> dict[str, int]: + return {"consumed": self.consumed} + + def load_state_dict(self, value: dict[str, int]) -> None: + self.consumed = int(value["consumed"]) + + +def overfit64_indices(dataset: ActionV6Dataset) -> list[int]: + tasks = [dataset.tasks[index] for index in np.linspace(0, len(dataset.tasks) - 1, 8, dtype=int)] + values = [] + for task in tasks: + for desired in ("clean", "randomized"): + episodes = dataset.task_domain_episodes[task][desired] + candidates = [] + for episode in episodes: + for latent_start in range(dataset.source_window_counts[episode]): + candidates.append(dataset.source_window_index(episode, latent_start)) + if len(candidates) == 4: + break + if len(candidates) == 4: + break + if len(candidates) != 4: + raise RuntimeError(f"cannot select four overfit windows for {task}/{desired}") + values.extend(candidates) + if len(values) != 64 or len(set(values)) != 64: + raise RuntimeError("overfit64 selection is not exactly 64 distinct windows") + return values + + +class Overfit64Sampler(Sampler[tuple[int, int]]): + def __init__(self, dataset: ActionV6Dataset, *, rank: int, world_size: int) -> None: + self.indices = overfit64_indices(dataset) + self.rank = rank + self.world_size = world_size + self.consumed = 0 + + def __len__(self) -> int: + return 2**31 + + def __iter__(self) -> Iterator[tuple[int, int]]: + position = self.consumed + while True: + global_position = position * self.world_size + self.rank + yield self.indices[global_position % len(self.indices)], 0 + position += 1 + + def mark_consumed(self, count: int) -> None: + self.consumed += int(count) + + def state_dict(self) -> dict[str, int]: + return {"consumed": self.consumed} + + def load_state_dict(self, value: dict[str, int]) -> None: + self.consumed = int(value["consumed"]) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/actions.py b/release-20261107/source/workspace_joint/mira/src/mira/data/actions.py new file mode 100644 index 0000000000000000000000000000000000000000..846a0522b76de78fe31aa13dab3e62f6be20a461 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/actions.py @@ -0,0 +1,119 @@ +"""Keyboard actions: parsing the per-frame `.jsonl` into a multi-hot tensor. + +The 4-player Rocket League data is keyboard-only (no mouse/analog): every `.jsonl` line is +`{"keys": [...]}` with one line per video frame. We turn that into a multi-hot tensor over a +fixed key vocabulary, downsampling to `target_fps` by OR-ing key presses over each window. + +Downsampling contract: integer-only downsampling, keys OR-ed over the window, int32 multi-hot. The +fixed vocabulary order below must stay stable so the multi-hot ordering is consistent across +consumers. +""" + +from __future__ import annotations + +import json +import warnings +from collections.abc import Iterable +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Literal + +from .clips import compute_stride + +if TYPE_CHECKING: + import torch + +# Stable, documented ordering of the 9 keys present in the 4-player Rocket League data. +# (drive: W/S, steer/air: A/D, jump: Space, boost: LShiftKey, drift/air-roll: LControlKey, +# plus Q/E powerslide/air-roll binds). These are the keys present in the data. +DEFAULT_RL_KEYS: tuple[str, ...] = ( + "W", + "A", + "S", + "D", + "Q", + "E", + "Space", + "LShiftKey", + "LControlKey", +) + + +@dataclass(frozen=True) +class KeyVocab: + """Fixed key vocabulary defining the multi-hot ordering. + + `on_unknown` controls what happens when a `.jsonl` line contains a key outside the vocab: + "warn" (default, drop + warn once per distinct key), "ignore" (drop silently), or "error" (raise). + """ + + keys: tuple[str, ...] + on_unknown: Literal["warn", "ignore", "error"] = "warn" + _index: dict[str, int] = field(default_factory=dict, compare=False, repr=False) + + def __post_init__(self) -> None: + if self.on_unknown not in ("warn", "ignore", "error"): + raise ValueError(f"on_unknown must be 'warn', 'ignore', or 'error', got {self.on_unknown!r}") + object.__setattr__(self, "_index", {k: i for i, k in enumerate(self.keys)}) + + @classmethod + def default_rl(cls, on_unknown: Literal["warn", "ignore", "error"] = "warn") -> "KeyVocab": + return cls(DEFAULT_RL_KEYS, on_unknown=on_unknown) + + def __len__(self) -> int: + return len(self.keys) + + +def tensorize_actions( + lines: Iterable[str | bytes], + vocab: KeyVocab, + source_fps: float, + target_fps: int, + keep_last_partial: bool = False, +) -> torch.Tensor: + """Parse `.jsonl` action lines into a multi-hot tensor of shape (n_steps, len(vocab)) int32. + + Downsampling uses the same integer stride as frame decoding (`clips.compute_stride`), so frames + and actions stay aligned. n_steps = floor(n_lines / stride); the trailing partial window is + dropped by default, since a step is normally only emitted once a full window has accumulated. + Set `keep_last_partial=True` to instead emit that trailing window OR-ed over whatever frames + remain — used when a clip runs to the end of a chunk and its final window is short, so the real + keys held over those frames are kept rather than lost. + """ + import torch + + factor = compute_stride(source_fps, target_fps) + n_keys = len(vocab) + + steps: list[torch.Tensor] = [] + window = torch.zeros(n_keys, dtype=torch.int32) + count = 0 + unknown_seen: set[str] = set() + + for line in lines: + # A blank line counts as a frame with no keys held (preserve per-frame alignment rather than + # dropping the frame). `keys` may be absent or an explicit null ("no keys this frame"); both + # mean an empty set. + line = line.strip() + keys = (json.loads(line).get("keys") or []) if line else [] + for k in keys: + idx = vocab._index.get(k) + if idx is None: + if k not in unknown_seen and vocab.on_unknown != "ignore": + if vocab.on_unknown == "error": + raise ValueError(f"Unknown key {k!r} not in vocab {vocab.keys}") + warnings.warn(f"Dropping unknown key {k!r} (not in vocab)", stacklevel=2) + unknown_seen.add(k) + continue + window[idx] = 1 # OR over the downsampling window + count += 1 + if count == factor: + steps.append(window) + window = torch.zeros(n_keys, dtype=torch.int32) + count = 0 + + if keep_last_partial and count > 0: + steps.append(window) + + if not steps: + return torch.zeros((0, n_keys), dtype=torch.int32) + return torch.stack(steps, dim=0) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/batch.py b/release-20261107/source/workspace_joint/mira/src/mira/data/batch.py new file mode 100644 index 0000000000000000000000000000000000000000..8ff25f45afe6de01a92688bac2b190e2a1b636e3 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/batch.py @@ -0,0 +1,70 @@ +"""The batch container the models read: video frames plus their aligned actions. + +The models consume only ``video`` ``(B, T, C, H, W)`` uint8 and ``actions`` (an +:class:`~mira.world_model.actions_config.ActionTensors`). There is no audio: the codec +and world model are video-only here. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any + +import torch + +from mira.world_model.actions_config import ActionTensors + + +# A dataclass (not Pydantic) because Pydantic + torch.compile() has issues: Pydantic's validation +# can't be compiled, and model_construct() leads to an infinite loop during compilation. +@dataclass +class VideoActionBatch: + """A batch of video frames and the aligned actions that produced them. + + Metadata should not live here — only what the models actually read. + """ + + # Plain ``torch.Tensor`` fields whose torch methods propagate generically. ``actions`` is an + # ``ActionTensors`` container handled explicitly in ``to``/``pin_memory``/``clone`` below (it + # implements the same methods), so device moves and copies still reach it. + _TENSOR_ATTRIBUTES = ["video"] + + video: torch.Tensor # (B, T, C, H, W) uint8 + actions: ActionTensors + + def to(self, *args: Any, **kwargs: Any) -> VideoActionBatch: + """Propagate ``torch.Tensor.to`` to the video and the actions.""" + return VideoActionBatch( + video=self.video.to(*args, **kwargs), actions=self.actions.to(*args, **kwargs) + ) + + def pin_memory(self) -> VideoActionBatch: + """Propagate ``torch.Tensor.pin_memory`` to the video and the actions (called by the loader).""" + return VideoActionBatch(video=self.video.pin_memory(), actions=self.actions.pin_memory()) + + def clone(self) -> VideoActionBatch: + """Deep-copy the batch, propagating ``torch.Tensor.clone`` to the video and the actions.""" + return VideoActionBatch(video=self.video.clone(), actions=self.actions.clone()) + + def __len__(self) -> int: + assert self.video.shape[0] == self.actions.batch_size + return self.video.shape[0] + + def slice_time(self, start: int | None, end: int | None, *, fps: int) -> VideoActionBatch: + """Slice the batch in time to ``[start, end)``. Views the tensors, does not copy. + + ``fps`` is accepted so callers can slice by a single time convention; video and actions are + both frame-indexed here, so it is not needed to resolve the indices. + """ + return VideoActionBatch( + video=self.video[:, start:end], + actions=self.actions.slice_time(start, end), + ) + + def cat_time(self, other: VideoActionBatch) -> VideoActionBatch: + """Concatenate with another batch along the time dimension.""" + assert len(self) == len(other), f"Batch sizes must match: {len(self)} != {len(other)}" + return VideoActionBatch( + video=torch.cat([self.video, other.video.to(self.video.device)], dim=1), + actions=self.actions.cat_time(other.actions.to(self.actions.key_presses.device)), + ) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/clips.py b/release-20261107/source/workspace_joint/mira/src/mira/data/clips.py new file mode 100644 index 0000000000000000000000000000000000000000..15b8d69e81599000740c134e6c0555f491d63fa4 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/clips.py @@ -0,0 +1,49 @@ +"""Clip enumeration: turning a full match recording into fixed-length, fps-downsampled windows. + +The contract: non-overlapping windows of `clip_len` frames at `target_fps` via an integer stride; +a trailing window shorter than `clip_len` is dropped. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Iterator +from itertools import islice + +try: + from itertools import batched # type: ignore[attr-defined] # Python 3.12+; fallback below +except ImportError: # Python 3.10 / 3.11 + + def batched(iterable: Iterable, n: int) -> Iterator[tuple]: + it = iter(iterable) + while batch := tuple(islice(it, n)): + yield batch + + +def compute_stride(source_fps: float, target_fps: int) -> int: + """Integer decode stride mapping `source_fps` down to `target_fps`. + + Allows a little slack because measured fps is sometimes slightly off (e.g. 29.97 vs 30). + Raises if the source fps is not (close to) an integer multiple of the target. + """ + if target_fps <= 0: + raise ValueError(f"target_fps must be positive, got {target_fps}") + stride = max(1, round(source_fps / target_fps)) + if abs(target_fps * stride - source_fps) > 0.5: + raise ValueError(f"Source fps {source_fps} not an integer multiple of target fps {target_fps}") + return stride + + +def compute_clip_frame_indices( + total_frames: int, source_fps: float, clip_len: int, target_fps: int +) -> tuple[list[list[int]], int]: + """Return (list_of_clips, stride) where each clip is `clip_len` source-frame indices. + + Indices step by `stride` so the decoded clip plays at `target_fps`. The final short window + (if any) is dropped. + """ + stride = compute_stride(source_fps, target_fps) + indices = list(range(0, total_frames, stride)) + clips = [list(x) for x in batched(indices, clip_len)] + if clips and len(clips[-1]) < clip_len: + clips.pop() + return clips, stride diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/dataset.py b/release-20261107/source/workspace_joint/mira/src/mira/data/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df37ca511f6074e97668c9aa944cb7aac21cea7 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/dataset.py @@ -0,0 +1,641 @@ +"""RocketScienceDataset: load time-aligned 4-perspective clips of Rocket League matches. + +One WebDataset sample is one *(match, chunk)*: a ~4 s window (80 frames at 20 fps) of a match, +bundling all perspectives — members `p{i}.mp4` / `p{i}.jsonl` (ordered by `player_id`) + `meta.json`, +sample key `{match_id}_c{chunk:05d}`. Each chunk carries its own per-frame action and physics track. +A clip is taken from within a single chunk. + +Two access patterns: + * `load_match(match_id, ...)` — random access (reads only the chunks the requested clips need) + * `iter_clips(...)` — stream shards, one decoded clip at a time (each sample = one chunk) +""" + +from __future__ import annotations + +import json +import logging +import random +import tarfile +from collections.abc import Iterator +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING + +from .actions import KeyVocab, tensorize_actions +from .clips import compute_clip_frame_indices, compute_stride +from .decode import decode_frames +from .events import Event, events_in_frame_window, overlaps_any, parse_anchors, replay_spans +from .schema import Index, MatchEntry +from .state import FrameState + +if TYPE_CHECKING: + import torch + +logger = logging.getLogger(__name__) + +N_PLAYERS = 4 + + +def _read_member(tar: tarfile.TarFile, member: "tarfile.TarInfo | str") -> bytes: + """Read a tar member's bytes, raising if it is missing or not a regular file.""" + info = tar.getmember(member) if isinstance(member, str) else member + f = tar.extractfile(info) + if f is None: + raise ValueError(f"tar member is not a readable file: {info.name}") + return f.read() + + +def _parse_member(name: str) -> tuple[str, str]: + """Split a tar member basename into (sample_key, field). The WebDataset key is everything before + the first dot (the chunk key has no dots); the field is the rest, e.g. `p0.mp4` / `meta.json`.""" + key, _, field = name.partition(".") + return key, field + + +def _perspective_index(field: str) -> int | None: + """Perspective index from a field like `p0.mp4`/`p3.jsonl`, or None for non-`p{i}` fields.""" + if not field.startswith("p") or "." not in field: + return None + head = field.split(".", 1)[0][1:] + return int(head) if head.isdigit() else None + + +def chunk_key(match_id: str, chunk_idx: int) -> str: + """WebDataset sample key for one (match, chunk). + + The WebDataset key is everything before the first '.', so `match_id` must contain no '.' (else + member parsing would split the key wrongly). + """ + if "." in match_id: + raise ValueError(f"match_id must not contain '.': {match_id!r}") + return f"{match_id}_c{chunk_idx:05d}" + + +def parse_chunk_key(key: str) -> tuple[str, int] | None: + """Inverse of `chunk_key`: `{match_id}_c{idx}` -> (match_id, idx), or None if not a chunk key.""" + base, sep, idx = key.rpartition("_c") + if not sep or not base or not idx.isdigit(): + return None + return base, int(idx) + + +@dataclass +class MatchClip: + """One time-aligned within-chunk window of the selected perspectives of a match. + + The perspective axis (size P) is ordered by `player_id` (NOT by team — read `teams`). With the + default `perspective="all"`, P=4; selecting a single perspective gives P=1. + + `frame_indices` are **chunk-local** source-frame indices (into chunk `chunk_idx`), shared across + perspectives. `clip_id` is a per-match running index over all chunks' clips (chunk 0's clips + first, then chunk 1's, ...). Full per-perspective metadata is in `metadata`. + """ + + match_id: str + chunk_idx: int + clip_id: int + perspectives: list[int] # selected source-perspective indices (0..n_players-1), player_id order + frame_indices: list[int] # chunk-local source-frame indices, shared across perspectives + stride: int + target_fps: int + src_fps: float # the match's true source fps (frames / duration); exact, not target_fps * stride + player_ids: list[int] # per selected perspective + teams: list[int] # per selected perspective + recording_offsets: list[float] # recording_offset_sec per selected perspective (master clock) + metadata: list[dict] # full per-perspective metadata + actions: "torch.Tensor" # (P, T, n_keys) int32 multi-hot + events: list[Event] # events overlapping this window (mapped via the first selected perspective) + frames: "torch.Tensor | None" = None # (P, T, C, H, W) uint8; None if decode=False + physics: list[list[FrameState]] | None = None # per perspective, T per-frame game-state dicts + # (None if the dataset carries no physics). All perspectives share the same world state; kept + # per-perspective so it stays frame-aligned with that perspective's frames/actions. + global_frame_indices: list[int] | None = None # match-global source-frame index per step (same T + # as frame_indices). Lets a step be placed on the master clock — master_sec = recording_offset + + # g / src_fps — for event/phase mapping that must see anchors outside the clip window. + video_bytes: list[bytes] | None = None # per selected perspective, the chunk's compressed mp4 + # bytes (set when decode=False and carry_video=True), for decoding a drawn clip later via + # `decode_perspective`. Shared by reference across all clips read from the same chunk. + + def decode_perspective(self, p: int, frame_size: tuple[int, int] | None = None) -> "torch.Tensor": + """Decode selected perspective `p`'s carried video bytes to a (T, C, H, W) uint8 tensor.""" + if self.video_bytes is None: + raise ValueError("clip carries no video_bytes; read it with carry_video=True") + return decode_frames(self.video_bytes[p], self.frame_indices, frame_size) + + +@dataclass +class _ClipPlan: + """A single planned within-chunk clip (computed from the index, before any bytes are read).""" + + clip_id: int + chunk_idx: int + local: list[int] # chunk-local source-frame indices + g0: int # match-global start frame (for event/replay mapping) + g_end: int # match-global end frame (exclusive) + + +@dataclass +class _MatchPlan: + """Per-match constants: the full within-chunk clip plan + alignment metadata.""" + + entry: MatchEntry + plan: list[_ClipPlan] + stride: int + src_fps: float + events: list[Event] + meta: list[dict] + replays: list[tuple[int, int]] + + +class RocketScienceDataset: + def __init__(self, index_path: str | Path, vocab: KeyVocab | None = None): + self.index_path = Path(index_path) + self.root = self.index_path.parent + self.vocab = vocab or KeyVocab.default_rl() + + self.index: Index = Index.load(self.index_path) + self.matches: dict[str, MatchEntry] = {} + # original-chunk-index -> position in chunk_frames, per match (chunks may be non-contiguous) + self._chunk_pos: dict[str, dict[int, int]] = {} + for e in self.index.entries: + e.perspectives.sort(key=lambda p: p.player_id) # define the p0..p3 axis + self.matches[e.match_id] = e + self._chunk_pos[e.match_id] = {e.chunk_id(pos): pos for pos in range(len(e.chunk_frames))} + + @classmethod + def from_local(cls, path: str | Path, **kwargs) -> "RocketScienceDataset": + """`path` may be the dataset directory (containing index.json) or the index.json itself.""" + path = Path(path) + if path.is_dir(): + path = path / "index.json" + if not path.exists(): + raise FileNotFoundError(f"No index at {path}.") + return cls(path, **kwargs) + + @classmethod + def from_hub( + cls, + repo_id: str, + split: str | None = None, + subdir: str | None = None, + revision: str | None = None, + shards: int | None = None, + **kwargs, + ) -> "RocketScienceDataset": + """Download one split of a dataset repo from the HuggingFace Hub and load it (random access). + + The repo holds each split under its own prefix: `{split}/index.json` plus WebDataset shards, + flat (`test/dataset_*.tar`) or in numbered subfolders (`train/000/dataset_*.tar`); + `index.json` records the shard paths, so both layouts load identically. Pass `split` to + choose one; only that prefix is downloaded. `subdir` overrides the prefix for a non-split + layout. Requires the `hf` extra. + + Pass `shards=N` to download only the first `N` tar shards (plus the index) and restrict the + dataset to the matches they contain -- handy for a quick smoke test without pulling the full + split (e.g. `shards=1` fetches a single shard). `None` (default) downloads every shard. + + The tars are standard WebDataset shards and can also be read with + `datasets.load_dataset("webdataset", data_files="hf://datasets//train/*/*.tar", ...)` + (flat splits: `.../test/*.tar`). + """ + from huggingface_hub import snapshot_download + + prefix = subdir if subdir is not None else (split if split is not None else "data") + + if shards is None: + # fnmatch-based, so `{prefix}/*` also matches shards nested in subfolders + local = snapshot_download( + repo_id, repo_type="dataset", revision=revision, allow_patterns=[f"{prefix}/*"] + ) + return cls.from_local(Path(local) / prefix, **kwargs) + + if shards < 1: + raise ValueError(f"shards must be >= 1 (or None for all), got {shards}") + # Fetch the index first, pick the first `shards` tar files, then download only those. + index_local = snapshot_download( + repo_id, repo_type="dataset", revision=revision, allow_patterns=[f"{prefix}/index.json"] + ) + index = Index.load(Path(index_local) / prefix / "index.json") + keep_shards = sorted({e.shard for e in index.entries})[:shards] + local = snapshot_download( + repo_id, + repo_type="dataset", + revision=revision, + allow_patterns=[f"{prefix}/index.json", *(f"{prefix}/{s}" for s in keep_shards)], + ) + ds = cls.from_local(Path(local) / prefix, **kwargs) + ds._restrict_to_shards(set(keep_shards)) + return ds + + def _restrict_to_shards(self, keep_shards: set[str]) -> None: + """Drop every match whose shard is not in `keep_shards` (used by `from_hub(shards=...)`).""" + self.index.entries = [e for e in self.index.entries if e.shard in keep_shards] + self.index.total_samples = len(self.index.entries) + self.matches = {mid: e for mid, e in self.matches.items() if e.shard in keep_shards} + self._chunk_pos = {mid: p for mid, p in self._chunk_pos.items() if mid in self.matches} + + def match_ids(self) -> list[str]: + return list(self.matches) + + # -- per-match planning (no bytes read) ------------------------------- + + def max_clip_frames(self, target_fps: int) -> int: + """Longest ``clip_len`` (in ``target_fps`` frames) that fits inside a single chunk of at + least one match, or ``0`` if the dataset holds no usable match. + + A clip of ``clip_len`` indices spans ``(clip_len - 1) * stride + 1`` source frames and must + fit within one chunk (see :meth:`_plan_match`), so per match the largest feasible ``clip_len`` + is ``(max(chunk_frames) - 1) // stride + 1``. Matches whose fps is not an integer multiple of + ``target_fps`` (``compute_stride`` raises) are skipped, mirroring the streaming read path. + This reads only index metadata (frame counts / durations), no video. + """ + best = 0 + for entry in self.matches.values(): + if not entry.chunk_frames or not entry.perspectives: + continue + duration = entry.perspectives[0].duration + if duration <= 0: + continue + src_fps = sum(entry.chunk_frames) / duration + try: + stride = compute_stride(src_fps, target_fps) + except ValueError: + continue + best = max(best, (max(entry.chunk_frames) - 1) // stride + 1) + return best + + def _plan_match(self, entry: MatchEntry, clip_len: int, target_fps: int) -> _MatchPlan: + """Enumerate every within-chunk clip of a match; a clip whose span exceeds the largest + chunk raises.""" + persp = entry.perspectives + total = sum(entry.chunk_frames) + for p in persp: + if p.frames != total: + raise ValueError( + f"{entry.match_id}: perspective {p.player_id} has {p.frames} frames != " + f"sum(chunk_frames)={total}" + ) + src_fps = total / persp[0].duration + stride = compute_stride(src_fps, target_fps) + + # A clip of clip_len indices at this stride spans (clip_len-1)*stride + 1 source frames. + span = (clip_len - 1) * stride + 1 + biggest = max(entry.chunk_frames) + if span > biggest: + raise ValueError( + f"{entry.match_id}: a clip_len={clip_len} clip @ {target_fps}fps spans {span} source " + f"frames, but a clip must fit in one chunk (largest is {biggest} frames). " + f"Reduce clip_len or raise target_fps." + ) + + offsets = [0] + for f in entry.chunk_frames: + offsets.append(offsets[-1] + f) + + plan: list[_ClipPlan] = [] + cid = 0 + for c, n_frames in enumerate(entry.chunk_frames): + chunk_clips, _ = compute_clip_frame_indices(n_frames, src_fps, clip_len, target_fps) + for local in chunk_clips: + g0 = offsets[c] + local[0] + g_end = offsets[c] + local[-1] + stride + plan.append(_ClipPlan(cid, c, local, g0, g_end)) + cid += 1 + + events_all = parse_anchors(persp[0].anchors) # anchors identical across perspectives + replays = replay_spans(events_all, src_fps, persp[0].recording_offset_sec, total) + return _MatchPlan(entry, plan, stride, src_fps, events_all, [p.model_dump() for p in persp], replays) + + @staticmethod + def _select_plan( + mp: _MatchPlan, exclude_replays: bool, clip_ids: list[int] | None, max_clips: int | None + ) -> list[_ClipPlan]: + """Apply clip_ids / exclude_replays / max_clips to a match's clip plan. `clip_ids` selects by + the per-match running `clip_id`.""" + want = set(clip_ids) if clip_ids is not None else None + out: list[_ClipPlan] = [] + for cp in mp.plan: + if want is not None and cp.clip_id not in want: + continue + if exclude_replays and overlaps_any(cp.g0, cp.g_end, mp.replays): + continue + out.append(cp) + if max_clips is not None and len(out) >= max_clips: + break + return out + + @staticmethod + def _select_perspectives(perspective: str | int, n: int, rng: "random.Random") -> list[int]: + """Resolve the `perspective` selector to a list of source-perspective indices. + + "all" -> [0..n-1]; "random" -> one random index (per call, so per clip when streaming); + an int i -> [i]; "playerK" (1-based) -> [K-1]. + """ + if isinstance(perspective, int): + if not 0 <= perspective < n: + raise ValueError(f"perspective index {perspective} out of range [0,{n})") + return [perspective] + if perspective == "all": + return list(range(n)) + if perspective == "random": + return [rng.randrange(n)] + if isinstance(perspective, str) and perspective.startswith("player"): + k = int(perspective.removeprefix("player")) - 1 + if not 0 <= k < n: + raise ValueError(f"{perspective!r} out of range (have {n} players)") + return [k] + raise ValueError(f"Invalid perspective {perspective!r}; use 'all', 'random', 'playerK', or int") + + # -- assembling one within-chunk clip -------------------------------- + + def _assemble( + self, mp: _MatchPlan, cp: _ClipPlan, chunk: list[dict], sel: list[int], + target_fps: int, decode: bool, frame_size, action_fps: int | None = None, + carry_video: bool = False, + ) -> MatchClip: # fmt: skip + """Build a MatchClip for `cp` from a single chunk's bytes. `chunk[i]` is + `{"video": bytes, "lines": list[bytes]}` for perspective i. + + `action_fps` decouples the action sample rate from the frame `target_fps`. When `None` + (default) actions are tensorized at `target_fps` — one action step per decoded frame. When + set, actions are tensorized at `action_fps` over the same clip line-span, so the action time + dim becomes `clip_len * (action_fps // target_fps)` (e.g. 10fps frames + 20fps actions -> 2 + actions/frame). `action_fps` must be a positive integer multiple of `target_fps`. + """ + import torch + + persp = mp.entry.perspectives + clip_len = len(cp.local) + l0, l_end = cp.local[0], cp.local[-1] + mp.stride + + if action_fps is None: + act_fps, n_action_steps = target_fps, clip_len + else: + if action_fps < target_fps or action_fps % target_fps != 0: + raise ValueError( + f"action_fps ({action_fps}) must be a positive integer multiple of " + f"target_fps ({target_fps})" + ) + act_fps, n_action_steps = action_fps, clip_len * (action_fps // target_fps) + + per_actions = [] + for i in sel: + # All perspectives are frame-aligned, so actions use the same planned stride as the + # frame indices (mp.src_fps), not a per-perspective re-derivation. `keep_last_partial` + # OR-s a short final window (a clip running to the chunk's end) into a real step rather + # than dropping it, so the trailing step carries the keys actually held over its frames. + a = tensorize_actions( + chunk[i]["lines"][l0:l_end], self.vocab, mp.src_fps, act_fps, keep_last_partial=True + ) + # A clip ending at the chunk boundary can have a short final action window (the chunk + # ends mid-window), so with action_fps > target_fps (multiple action steps per frame) it + # yields fewer than `n_action_steps`. Hold the last step to pad back to the nominal count + # so actions stay aligned to the clip's frames. (No-op when the window is full, e.g. + # action_fps == target_fps, which is every released config.) + if a.shape[0] < n_action_steps: + a = torch.cat([a, a[-1:].expand(n_action_steps - a.shape[0], -1)], dim=0) + if a.shape[0] != n_action_steps: + raise ValueError( + f"{mp.entry.match_id} clip {cp.clip_id}: {a.shape[0]} action steps != {n_action_steps}" + ) + per_actions.append(a) + actions = torch.stack(per_actions, dim=0) + + frames = None + if decode: + frames = torch.stack([decode_frames(chunk[i]["video"], cp.local, frame_size) for i in sel], dim=0) + if frames.shape[1] != clip_len: + raise ValueError( + f"{mp.entry.match_id} clip {cp.clip_id}: decoded {frames.shape[1]} != {clip_len}" + ) + + physics = None + if all(chunk[i].get("physics") is not None for i in sel): + physics = [[json.loads(chunk[i]["physics"][f]) for f in cp.local] for i in sel] + + offs = [p.recording_offset_sec for p in persp] + return MatchClip( + match_id=mp.entry.match_id, + chunk_idx=cp.chunk_idx, + clip_id=cp.clip_id, + perspectives=list(sel), + frame_indices=cp.local, + stride=mp.stride, + target_fps=target_fps, + src_fps=mp.src_fps, + player_ids=[persp[i].player_id for i in sel], + teams=[persp[i].team for i in sel], + recording_offsets=[offs[i] for i in sel], + metadata=[mp.meta[i] for i in sel], + actions=actions, + events=events_in_frame_window(mp.events, cp.g0, cp.g_end, mp.src_fps, offs[sel[0]]), + frames=frames, + physics=physics, + global_frame_indices=[cp.g0 + (li - cp.local[0]) for li in cp.local], + video_bytes=[chunk[i]["video"] for i in sel] if carry_video else None, + ) + + # -- reading chunk samples ------------------------------------------- + + def _chunk_position(self, match_id: str, orig: int) -> int | None: + """Position in `chunk_frames` of the chunk with original source index `orig`, or None.""" + return self._chunk_pos.get(match_id, {}).get(orig) + + def _read_chunk(self, tar: tarfile.TarFile, entry: MatchEntry, ci: int) -> list[dict]: + """Read one chunk's perspectives (`{"video", "lines"}`, optional `"physics"`) from an open tar. + + `ci` is the position into `chunk_frames`; the on-disk sample key uses the chunk's ORIGINAL + source index (`entry.chunk_id(ci)`), which differs when the match has non-contiguous chunks.""" + key = chunk_key(entry.match_id, entry.chunk_id(ci)) + # Resolve members by basename (the streaming path does the same): WebDataset tars may store + # members under a path prefix (`./key...` or a subdir), which `getmember(full_name)` misses. + members = {Path(m.name).name: m for m in tar.getmembers() if m.isfile()} + + def _member(name: str) -> tarfile.TarInfo: + m = members.get(name) + if m is None: + raise ValueError(f"{entry.match_id}: tar member missing: {name}") + return m + + out = [] + for i in range(entry.n_players): + part = { + "video": _read_member(tar, _member(f"{key}.p{i}.mp4")), + "lines": _read_member(tar, _member(f"{key}.p{i}.jsonl")).splitlines(), + } + phys_name = f"{key}.p{i}.physics.jsonl" + if phys_name in members: + part["physics"] = _read_member(tar, members[phys_name]).splitlines() + out.append(part) + return out + + # -- public access ---------------------------------------------------- + + def load_match( + self, + match_id: str, + clip_len: int = 16, + target_fps: int = 10, + exclude_replays: bool = False, + decode: bool = True, + max_clips: int | None = None, + perspective: str | int = "all", + frame_size: tuple[int, int] | None = None, + seed: int = 0, + clip_ids: list[int] | None = None, + action_fps: int | None = None, + ) -> list[MatchClip]: + """Random access: build the requested clips, reading only the chunks they need. + + A clip is taken from within a single chunk, so it is at most one chunk long (~80 frames at + 20 fps); a request where `clip_len` at the resulting stride exceeds the largest chunk raises. + + `action_fps` (additive; see `_assemble`) decouples the action sample rate from the frame + `target_fps`; `None` keeps one action step per frame. + """ + entry = self.matches[match_id] + rng = random.Random(seed) + mp = self._plan_match(entry, clip_len, target_fps) + selected = self._select_plan(mp, exclude_replays, clip_ids, max_clips) + + needed = sorted({cp.chunk_idx for cp in selected}) + chunks: dict[int, list[dict]] = {} + if needed: + with tarfile.open(self.root / entry.shard, "r") as tar: + for ci in needed: + chunks[ci] = self._read_chunk(tar, entry, ci) + + out = [] + for cp in selected: + sel = self._select_perspectives(perspective, entry.n_players, rng) + out.append( + self._assemble(mp, cp, chunks[cp.chunk_idx], sel, target_fps, decode, frame_size, action_fps) + ) + return out + + def iter_clips( + self, + clip_len: int = 16, + target_fps: int = 10, + exclude_replays: bool = False, + decode: bool = True, + perspective: str | int = "all", + frame_size: tuple[int, int] | None = None, + seed: int = 0, + action_fps: int | None = None, + carry_video: bool = False, + ) -> Iterator[MatchClip]: + """Stream shards, yielding one decoded clip at a time (each sample = one (match, chunk)). + + `action_fps` (additive; see `_assemble`) decouples the action sample rate from the frame + `target_fps`; `None` keeps one action step per frame. `carry_video` attaches each clip's + compressed per-perspective mp4 bytes (`MatchClip.video_bytes`) so decoding can be deferred; + use it with `decode=False` to stream undecoded clips that a consumer decodes on demand. + """ + rng = random.Random(seed) + plans: dict[str, _MatchPlan] = {} # cache per-match plan within a run + failed: set[str] = set() # matches whose plan raised; skipped (logged once) rather than fatal + for shard in sorted({e.shard for e in self.index.entries}): + yield from self._stream_shard( + shard, + plans, + failed, + clip_len, + target_fps, + exclude_replays, + decode, + perspective, + frame_size, + rng, + action_fps, + carry_video, + ) + + def _stream_shard( + self, + shard, + plans, + failed, + clip_len, + target_fps, + exclude_replays, + decode, + perspective, + frame_size, + rng, + action_fps=None, + carry_video=False, + ) -> Iterator[MatchClip]: + def emit(key: str, parts: dict[int, dict]) -> Iterator[MatchClip]: + parsed = parse_chunk_key(key) + if parsed is None: + return + match_id, orig = parsed # `orig` is the chunk's ORIGINAL source index (from the key) + entry = self.matches.get(match_id) + if entry is None or match_id in failed: + return + mp = plans.get(match_id) + if mp is None: + # A bad match (e.g. a clip too long for its chunks) should not abort the whole + # stream; skip it and keep going, unlike load_match's explicit single-match request. + try: + mp = plans[match_id] = self._plan_match(entry, clip_len, target_fps) + except ValueError as err: + failed.add(match_id) + logger.warning("Skipping match %s while streaming: %s", match_id, err) + return + pos = self._chunk_position(match_id, orig) # map original index -> position in chunk_frames + if pos is None: + return + # A single bad chunk (missing perspective member, short physics, decode failure) should + # skip that chunk and keep the stream alive, the same way _plan_match errors skip a match + # above -- otherwise one corrupt sample aborts the whole training run. Build the clips + # eagerly so a failure is caught here rather than escaping the generator mid-iteration. + try: + chunk = [self._require_part(parts, i) for i in range(entry.n_players)] + clips = [] + for cp in mp.plan: + if cp.chunk_idx != pos: + continue + if exclude_replays and overlaps_any(cp.g0, cp.g_end, mp.replays): + continue + sel = self._select_perspectives(perspective, entry.n_players, rng) + clips.append( + self._assemble( + mp, cp, chunk, sel, target_fps, decode, frame_size, action_fps, carry_video + ) + ) + except (ValueError, IndexError, KeyError, RuntimeError, OSError) as err: + logger.warning("Skipping chunk %s c%05d while streaming: %s", match_id, orig, err) + return + yield from clips + + cur_key: str | None = None + parts: dict[int, dict] = {} + with tarfile.open(self.root / shard, "r|*") as tar: + for m in tar: + if not m.isfile(): + continue + key, field = _parse_member(Path(m.name).name) + if key != cur_key: + if cur_key is not None: + yield from emit(cur_key, parts) + cur_key, parts = key, {} + i = _perspective_index(field) + if i is None: # meta.json etc. + continue + if field.endswith(".mp4"): + parts.setdefault(i, {})["video"] = _read_member(tar, m) + elif field.endswith(".physics.jsonl"): # check before the bare .jsonl below + parts.setdefault(i, {})["physics"] = _read_member(tar, m).splitlines() + elif field.endswith(".jsonl"): + parts.setdefault(i, {})["lines"] = _read_member(tar, m).splitlines() + if cur_key is not None: + yield from emit(cur_key, parts) + + @staticmethod + def _require_part(parts: dict[int, dict], i: int) -> dict: + part = parts.get(i) + if not part or "video" not in part or "lines" not in part: + raise ValueError(f"chunk sample missing perspective {i} (have {sorted(parts)})") + return part diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/decode.py b/release-20261107/source/workspace_joint/mira/src/mira/data/decode.py new file mode 100644 index 0000000000000000000000000000000000000000..88dface5eb7241197167c4de1fbd60e964a17a44 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/decode.py @@ -0,0 +1,50 @@ +"""Video decoding via torchcodec, from raw in-tar bytes. + +Decode from mp4 bytes (no temp files); fetch exactly the requested frame indices. torch/torchcodec +are imported lazily so the torch-free parts of the package (schema, events, clip enumeration) work +without them installed. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + import torch + + +def decode_frames( + video_bytes: bytes, + frame_indices: list[int], + frame_size: tuple[int, int] | None = None, +) -> torch.Tensor: + """Decode the given frame indices into a uint8 tensor of shape (T, C, H, W). + + If `frame_size=(H, W)` is given, frames are resampled to it with antialiased bilinear + interpolation (typically a downscale). The source is decoded full-res first, then resized. + """ + from torchcodec.decoders import VideoDecoder # pyright: ignore[reportPrivateImportUsage] + + decoder = VideoDecoder(video_bytes, device="cpu") + frames = decoder.get_frames_at(frame_indices).data # (T, C, H, W) uint8 + if frame_size is not None: + frames = _resize(frames, frame_size) + return frames + + +def _resize(frames: torch.Tensor, frame_size: tuple[int, int]) -> torch.Tensor: + """Resample (T, C, H, W) uint8 frames to `frame_size=(H, W)`, returning uint8. + + No-op when already at the target size. Antialiased bilinear interpolation runs in float; + the result is rounded and clamped back into the valid uint8 range (antialiasing can ring + slightly past [0, 255]). + """ + import torch + import torch.nn.functional as F + + if tuple(frames.shape[-2:]) == tuple(frame_size): + return frames + resized = F.interpolate( + frames.float(), size=frame_size, mode="bilinear", align_corners=False, antialias=True + ) + return resized.round().clamp_(0, 255).to(torch.uint8) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/events.py b/release-20261107/source/workspace_joint/mira/src/mira/data/events.py new file mode 100644 index 0000000000000000000000000000000000000000..0751aa26afed7cdb05d82d38f1190561a1b04348 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/events.py @@ -0,0 +1,80 @@ +"""Game events ("anchors") and their alignment to video frames. + +Discrete events live in the per-perspective `anchors`, each `{event_type, event_name, master_sec}`, +where `master_sec` is on a single match-wide master clock shared by all 4 perspectives. + +Each perspective's recording starts at a slightly different point on that master clock, captured +by `recording_offset_sec` (per perspective). To place an event on a *specific perspective's* +frame timeline: + + frame_index = round((master_sec - recording_offset_sec) * fps) + +Note `recording_offset_sec` differs across the 4 perspectives of a match (typically by a few +frames), so the same event maps to slightly different frame indices per perspective. Frame-index +alignment ignores this offset; offset-corrected alignment uses the formula above. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +REPLAY_START = "GoalReplayStarted" +REPLAY_END = "GoalReplayEnded" + + +@dataclass(frozen=True) +class Event: + event_type: int + event_name: str + master_sec: float + + def frame_index(self, fps: float, recording_offset_sec: float) -> int: + """Frame index of this event on a given perspective's timeline (may be out of range).""" + return round((self.master_sec - recording_offset_sec) * fps) + + +def parse_anchors(anchors: list) -> list[Event]: + """Build Events from anchors given as dicts or as objects with the matching attributes.""" + + def get(a, k): + return a[k] if isinstance(a, dict) else getattr(a, k) + + return [Event(get(a, "event_type"), get(a, "event_name"), get(a, "master_sec")) for a in anchors] + + +def events_in_frame_window( + events: list[Event], f_start: int, f_end: int, fps: float, recording_offset_sec: float +) -> list[Event]: + """Events whose frame index falls in [f_start, f_end) on this perspective's timeline.""" + return [e for e in events if f_start <= e.frame_index(fps, recording_offset_sec) < f_end] + + +def replay_spans( + events: list[Event], fps: float, recording_offset_sec: float, n_frames: int +) -> list[tuple[int, int]]: + """Frame-index [start, end) spans covering goal-replay segments (non-live-gameplay). + + Pairs each GoalReplayStarted with the next GoalReplayEnded. Spans are clamped to + [0, n_frames); a dangling start (replay running at recording end) extends to n_frames. + """ + spans: list[tuple[int, int]] = [] + start: int | None = None + for e in sorted(events, key=lambda x: x.master_sec): + f = e.frame_index(fps, recording_offset_sec) + if e.event_name == REPLAY_START: + start = f + elif e.event_name == REPLAY_END and start is not None: + lo, hi = max(0, min(start, f)), min(n_frames, max(start, f)) + if hi > lo: + spans.append((lo, hi)) + start = None + if start is not None: + lo = max(0, min(start, n_frames)) + if n_frames > lo: + spans.append((lo, n_frames)) + return spans + + +def overlaps_any(f_start: int, f_end: int, spans: list[tuple[int, int]]) -> bool: + """Whether [f_start, f_end) intersects any span.""" + return any(f_start < hi and lo < f_end for lo, hi in spans) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/joint_eval_language.py b/release-20261107/source/workspace_joint/mira/src/mira/data/joint_eval_language.py new file mode 100644 index 0000000000000000000000000000000000000000..1c37ca842712c1b144020ea79add89f3f2c4ad26 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/joint_eval_language.py @@ -0,0 +1,83 @@ +"""Eval-language augmentation for the isolated joint continuation branch. + +A draw counter, not worker RNG, selects the instruction so distributed restart +reproduces the same samples. +""" + +from __future__ import annotations + +import hashlib +import math +from typing import Any, Iterator + +from mira.data.joint_online import JointEvalAlignedSampler, JointOnlineRoboTwinDataset + + +SOURCES = ("seen", "full_goal") + + +def parse_instruction_mix(value: str) -> dict[str, float]: + result: dict[str, float] = {} + for part in value.split(","): + name, separator, weight = part.partition("=") + if not separator or name not in SOURCES or name in result: + raise ValueError(f"Invalid instruction mix component: {part!r}") + result[name] = float(weight) + if set(result) != set(SOURCES) or any(not math.isfinite(x) or x < 0 or x > 1 for x in result.values()): + raise ValueError(f"Instruction mix needs nonnegative weights for {SOURCES}") + if abs(sum(result.values()) - 1.0) > 1e-9: + raise ValueError("Instruction mix weights must sum to 1") + return result + + +def select_instruction(row: dict[str, Any], draw: int, mix: dict[str, float]) -> tuple[str, str]: + pool = row.get("instruction_pool_v2") + if pool is None: + raise ValueError("Eval-language mix requires instruction_pool_v2") + digest = hashlib.sha256(f"{row['episode_sha256']}\0{draw}\0eval-language-v1".encode()).digest() + fraction = int.from_bytes(digest[:8], "big") / 2**64 + cumulative = 0.0 + source = SOURCES[-1] + for choice in SOURCES: + cumulative += mix[choice] + if fraction < cumulative: + source = choice + break + options = pool[source] + if isinstance(options, str): + options = [options] + if not options or not all(isinstance(item, str) and item.strip() for item in options): + raise ValueError(f"Empty or invalid instruction pool for {source}") + selected = options[int.from_bytes(digest[8:16], "big") % len(options)] + return selected, source + + +class JointEvalLanguageDataset(JointOnlineRoboTwinDataset): + def __init__(self, *, instruction_mix: str, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.instruction_mix = parse_instruction_mix(instruction_mix) + missing = [row["episode_sha256"] for row in self.source_rows if "instruction_pool_v2" not in row] + if missing: + raise ValueError(f"Missing instruction pools for {len(missing)} episodes") + + def __getitem__(self, index: int | tuple[int, int]) -> dict[str, Any]: + anchor_index, draw = index if isinstance(index, tuple) else (int(index), int(index)) + sample = super().__getitem__(int(anchor_index)) + episode, _ = self._locate(int(anchor_index)) + text, source = select_instruction(self.source_rows[episode], int(draw), self.instruction_mix) + sample["metadata"]["instruction"] = text + sample["metadata"]["instruction_source"] = source + return sample + + +class JointEvalLanguageSampler(JointEvalAlignedSampler): + def __init__(self, *args: Any, emit_draw_index: bool = False, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.emit_draw_index = bool(emit_draw_index) + + def __iter__(self) -> Iterator[int | tuple[int, int]]: + for local_position, anchor_index in enumerate(super().__iter__(), start=self.consumed): + if self.emit_draw_index: + yield anchor_index, local_position * self.world_size + self.rank + else: + yield anchor_index diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/joint_online.py b/release-20261107/source/workspace_joint/mira/src/mira/data/joint_online.py new file mode 100644 index 0000000000000000000000000000000000000000..b77ccf7de8a3ad8facddd19177d392246fa49602 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/joint_online.py @@ -0,0 +1,279 @@ +"""Cache-free RoboTwin input pipeline for joint World + Action training. + +Only lightweight JSON manifests are materialized. RGB, robot state and action targets are read +directly from the original RoboTwin zip/HDF5 episodes for every sample; codec latents and Qwen +hidden states are deliberately produced online by the trainer. +""" + +from __future__ import annotations + +import bisect +import io +import itertools +import random +import zipfile +from collections import defaultdict +from dataclasses import dataclass, fields +from pathlib import Path +from typing import Any, Iterator + +import h5py +import torch +from torch import Tensor +from torch.utils.data import Dataset, Sampler +from mira.data.robotwin_rgb import official_image_decoder + +from mira.data.robotwin_wam_schema import ( + CAMERA_PATHS, + RAW_VECTOR_PATH, + half_up_source_indices, + read_jsonl, +) + + +def anchor_layout(anchor: int, frames: int) -> dict[str, Tensor]: + """Match the official adapter: duplicate observation 0, then append observations. + + Anchor is the current 20 Hz observation, not a latent-window start. Future RGB and + actions start at anchor+1. A partial final codec cell is NOT a valid world target. + """ + if not 0 <= anchor < frames - 1: + raise IndexError((anchor, frames)) + context = torch.arange(anchor - 19, anchor + 1).clamp_min(0) + future = torch.arange(anchor + 1, anchor + 21) + valid = future < frames + history_count = min(20, anchor + 2) + return { + "indices": torch.cat([context, future.clamp_max(frames - 1)]), + "history_valid": torch.arange(20) >= 20 - history_count, + "context_valid": torch.arange(10) >= 10 - (history_count + 1) // 2, + "action_valid": valid, + "future_valid": valid.reshape(10, 2).all(dim=1), + "future_rgb_valid": valid, + } + + +@dataclass +class JointOnlineBatch: + video: Tensor + state_history_raw: Tensor + history_valid: Tensor + context_valid: Tensor + action_gt: Tensor + action_valid: Tensor + future_valid: Tensor + future_rgb_valid: Tensor + + def to(self, *args: Any, **kwargs: Any) -> "JointOnlineBatch": + return JointOnlineBatch( + **{ + field.name: getattr(self, field.name).to(*args, **kwargs) + for field in fields(self) + } + ) + + +def _decode(dataset: h5py.Dataset, indices: list[int]) -> Tensor: + decode = official_image_decoder() + # The official decoder handles both legacy JPEGs and marked standard RGB. + # Decode padding duplicates only once. No caller-side channel swap is valid. + frames = {} + for index in dict.fromkeys(indices): + image = torch.from_numpy(decode(dataset[index])) + if image.ndim != 3 or image.shape[-1] != 3 or image.dtype != torch.uint8: + raise ValueError(f"Expected HWC uint8 RGB, got {image.shape} {image.dtype}") + frames[index] = image.permute(2, 0, 1).contiguous() + return torch.stack([frames[index] for index in indices]) + + +class JointOnlineRoboTwinDataset(Dataset[dict[str, Any]]): + """Read an eval-aligned short-history sample from raw RoboTwin storage. + + Each integer index identifies a current observation, including cold start and tail. + History grows as in the official adapter; it is never sampled independently of progress. + """ + + def __init__( + self, + *, + dataset_root: str | Path, + manifest: str | Path, + embodiment: str = "aloha-agilex", + ) -> None: + self.dataset_root = Path(dataset_root).expanduser().resolve() + rows = read_jsonl(manifest) + self.source_rows = [row for row in rows if str(row["robot"]) == embodiment] + if not self.source_rows: + raise ValueError(f"No {embodiment!r} episodes in {manifest}") + self.base_counts = [int(row["n_video20_frames"]) - 1 for row in self.source_rows] + if min(self.base_counts) < 1: + raise ValueError("Joint episodes need at least two observations") + self.base_cumulative = [0] + for count in self.base_counts: + self.base_cumulative.append(self.base_cumulative[-1] + count) + self.tasks = sorted({str(row["task"]) for row in self.source_rows}) + self.task_domain_episodes: dict[str, dict[str, list[int]]] = defaultdict( + lambda: defaultdict(list) + ) + for episode, row in enumerate(self.source_rows): + self.task_domain_episodes[str(row["task"])][str(row["domain"])].append(episode) + + @property + def base_windows(self) -> int: + return self.base_cumulative[-1] + + def __len__(self) -> int: + return self.base_windows + + def anchor_index(self, episode: int, anchor: int) -> int: + if not 0 <= episode < len(self.source_rows) or not 0 <= anchor < self.base_counts[episode]: + raise IndexError((episode, anchor)) + return self.base_cumulative[episode] + anchor + + def _locate(self, index: int) -> tuple[int, int]: + if not 0 <= index < self.base_windows: + raise IndexError(index) + episode = bisect.bisect_right(self.base_cumulative, index) - 1 + return episode, index - self.base_cumulative[episode] + + def __getitem__(self, index: int) -> dict[str, Any]: + episode_index, anchor = self._locate(int(index)) + row = self.source_rows[episode_index] + archive_path = self.dataset_root / str(row["archive"]) + with zipfile.ZipFile(archive_path) as archive: + payload = archive.read(str(row["member"])) + with h5py.File(io.BytesIO(payload), "r") as episode: + source_indices = half_up_source_indices(int(row["n_source_frames"])).long() + # Legacy manifests dropped an odd final observation; new joint manifests retain it. + recorded = int(row["n_video20_frames"]) + if recorded not in (source_indices.numel(), source_indices.numel() - source_indices.numel() % 2): + raise ValueError("Manifest/source resampling mismatch") + source_indices = source_indices[:recorded] + + if source_indices.numel() != int(row["n_video20_frames"]): + raise ValueError("Resampling contract changed; rebuild manifest") + layout = anchor_layout(anchor, source_indices.numel()) + selected = source_indices[layout["indices"]].tolist() + views = [] + for camera_path in CAMERA_PATHS: + camera = episode[camera_path] + if not isinstance(camera, h5py.Dataset): + raise TypeError(f"{camera_path} is not an HDF5 dataset") + decoded = _decode(camera, selected) + views.append(decoded) + video = torch.stack(views) + if video.shape[1] != 40: + raise RuntimeError(f"Expected 40 online RGB frames, got {tuple(video.shape)}") + + # h5py fancy indexing rejects repeated/non-strict indices from padding. + unique, inverse = torch.unique(torch.tensor(selected), sorted=True, return_inverse=True) + vector = torch.from_numpy( + episode[RAW_VECTOR_PATH][unique.numpy()].astype("float32", copy=False) + )[inverse] + state = vector[:20].reshape(20, 2, 7) + # The action at each 20 Hz step is the next absolute simulator drive target. + action = vector[20:].reshape(20, 2, 7) + + history_valid = layout["history_valid"] + context_valid = layout["context_valid"] + if not torch.isfinite(state).all() or not torch.isfinite(action).all(): + raise FloatingPointError("RoboTwin state/action contains non-finite values") + return { + "video": video, + "state_history_raw": state, + "history_valid": history_valid, + "context_valid": context_valid, + "action_gt": action, + "action_valid": layout["action_valid"], + "future_valid": layout["future_valid"], + "future_rgb_valid": layout["future_rgb_valid"], + "metadata": { + "episode_sha256": row["episode_sha256"], + "task": row["task"], + "domain": row["domain"], + "instruction": row["instruction"], + "input_color_order": "rgb", + "current_anchor": anchor, + "history_length": int(context_valid.sum()), + "progress": anchor / max(1, self.base_counts[episode_index] - 1), + }, + } + + +class JointEvalAlignedSampler(Sampler[int]): + """Task/domain/episode balanced, then uniform over every current anchor.""" + + def __init__( + self, + dataset: JointOnlineRoboTwinDataset, + *, + seed: int, + rank: int = 0, + world_size: int = 1, + start_index: int = 0, + clean_probability: float = 0.5, + task_weights: dict[str, float] | None = None, + ) -> None: + self.dataset = dataset + self.seed = int(seed) + self.rank = int(rank) + self.world_size = int(world_size) + self.consumed = int(start_index) + self.clean_probability = float(clean_probability) + if not 0.0 <= self.clean_probability <= 1.0: + raise ValueError("clean_probability must be in [0, 1]") + # None keeps the historical uniform task draw (and its exact random stream). + self.task_cumulative: list[float] | None = None + if task_weights is not None: + if set(task_weights) != set(dataset.tasks): + raise ValueError("task_weights must cover exactly the dataset tasks") + self.task_cumulative = list(itertools.accumulate(float(task_weights[t]) for t in dataset.tasks)) + if self.task_cumulative[-1] <= 0: + raise ValueError("task_weights must not all be zero") + + def __len__(self) -> int: + return 2**31 + + def __iter__(self) -> Iterator[int]: + local_position = self.consumed + while True: + global_position = local_position * self.world_size + self.rank + rng = random.Random(self.seed + global_position * 1_000_003) + if self.task_cumulative is None: + task = self.dataset.tasks[rng.randrange(len(self.dataset.tasks))] + else: + draw = rng.random() * self.task_cumulative[-1] + task = self.dataset.tasks[bisect.bisect_right(self.task_cumulative, draw)] + domains = self.dataset.task_domain_episodes[task] + desired = "clean" if rng.random() < self.clean_probability else "randomized" + domain = desired if desired in domains else sorted(domains)[rng.randrange(len(domains))] + episodes = domains[domain] + episode = episodes[rng.randrange(len(episodes))] + anchor = rng.randrange(self.dataset.base_counts[episode]) + yield self.dataset.anchor_index(episode, anchor) + local_position += 1 + + def mark_consumed(self, count: int) -> None: + self.consumed += int(count) + + def state_dict(self) -> dict[str, int]: + return {"consumed": self.consumed} + + def load_state_dict(self, value: dict[str, int]) -> None: + self.consumed = int(value["consumed"]) + + +def collate_joint_online( + samples: list[dict[str, Any]], +) -> tuple[JointOnlineBatch, list[dict[str, Any]]]: + batch = JointOnlineBatch( + video=torch.stack([sample["video"] for sample in samples]), + state_history_raw=torch.stack([sample["state_history_raw"] for sample in samples]), + history_valid=torch.stack([sample["history_valid"] for sample in samples]), + context_valid=torch.stack([sample["context_valid"] for sample in samples]), + action_gt=torch.stack([sample["action_gt"] for sample in samples]), + action_valid=torch.stack([sample["action_valid"] for sample in samples]), + future_valid=torch.stack([sample["future_valid"] for sample in samples]), + future_rgb_valid=torch.stack([sample["future_rgb_valid"] for sample in samples]), + ) + return batch, [sample["metadata"] for sample in samples] diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/physics.py b/release-20261107/source/workspace_joint/mira/src/mira/data/physics.py new file mode 100644 index 0000000000000000000000000000000000000000..d97b29217b9548185ac2270aff948a51543da1ae --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/physics.py @@ -0,0 +1,299 @@ +"""Pure helpers for the per-frame physics / game state attached to a clip. + +``clip.physics`` is ``list[list[FrameState]]`` — one list per selected perspective, each a per-frame +state frame-aligned 1:1 with the clip's frames / actions along the T axis (see +:mod:`mira.data.state` for the field layout). + +These functions are numpy-only so they are easy to unit-test, separate from any rendering layer that +consumes them. + +Coordinate system (standard Rocket League "Standard" arena): x in ~[-4096, 4096] (side walls), y in +~[-5120, 5120] (the goal-to-goal long axis), z in ~[0, 2044] (floor to ceiling). Distances are in +"uu" (Unreal units). +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +import numpy as np + +from .events import parse_anchors +from .state import CarState, FrameState, Vec3 + +if TYPE_CHECKING: + from .dataset import MatchClip + +# Rocket League "Standard" arena half-extents in Unreal units (uu). Used to frame the minimap; the +# observed data slightly exceeds these at the corners/goal mouths, so the minimap pads a little. +FIELD_X = 4096.0 # half-width (side walls) +FIELD_Y = 5120.0 # half-length (back walls / goal line) +FIELD_Z = 2044.0 # ceiling + +N_CARS = 4 # the dataset is 2v2, so every physics frame carries exactly 4 cars + + +def _xyz(d: Vec3) -> tuple[float, float, float]: + """Extract an (x, y, z) triple from a ``{"x":..,"y":..,"z":..}`` location/velocity dict.""" + return float(d["x"]), float(d["y"]), float(d["z"]) + + +def perspective_has_clock(persp_physics: list[FrameState]) -> bool: + """The match clock (``game.time_remaining``) is logged only on the local (``is_local``) + perspective; on the other perspectives it is identically 0.0. Returns whether THIS perspective + carries the clock (its ``time_remaining`` advances over the clip).""" + vals = {round(float(fr["game"]["time_remaining"]), 3) for fr in persp_physics} + return vals != {0.0} + + +def ball_track(persp_physics: list[FrameState]) -> np.ndarray: + """(T, 3) array of ball world positions over one perspective's clip.""" + return np.array([_xyz(fr["ball"]["location"]) for fr in persp_physics], dtype=np.float64) + + +def _min_lag_residual(a: np.ndarray, b: np.ndarray, max_lag: int) -> float: + """Smallest mean per-frame distance between two (T,3) tracks over integer lags in [-max_lag, + max_lag]. Compares two (T,3) tracks that share a world but sit on offset recording clocks. + + Returns ``inf`` when no lag yields an overlap to compare (e.g. an empty track), so a degenerate + clip reads as "could not establish agreement" rather than a misleading perfect 0.0.""" + best = float("inf") + for k in range(-max_lag, max_lag + 1): + x, y = (a[k:], b[: len(b) - k]) if k >= 0 else (a[:k], b[-k:]) + if len(x) == 0 or len(x) != len(y): + continue + best = min(best, float(np.linalg.norm(x - y, axis=1).mean())) + return best + + +def ball_moves(persp_physics: list[FrameState], min_uu: float = 1.0) -> bool: + """True if the ball position is not frozen across the clip (total path length > ``min_uu``).""" + track = ball_track(persp_physics) + if len(track) < 2: + return False + return float(np.linalg.norm(np.diff(track, axis=0), axis=1).sum()) > min_uu + + +def local_car(frame: FrameState) -> CarState: + """The ``is_local`` car in one physics frame (raises if not exactly one).""" + locals_ = [c for c in frame["cars"] if c.get("is_local")] + if len(locals_) != 1: + raise ValueError(f"expected exactly one is_local car, found {len(locals_)}") + return locals_[0] + + +# --- per-step badge (motion-authoritative, anchor-explained) ------------------------------------ +# +# During post-goal celebrations and replays the live physics freezes (ball/cars/clock constant) +# while the broadcast video keeps rolling. Actual motion is authoritative for the frozen state; the +# event anchors supply the reason. A frame is never simultaneously "moving/LIVE" and "frozen". +# +# Anchor windows on the master clock (per goal): +# KickoffStarted -> KickoffEnded : KICKOFF window (cars actively drive — NOT frozen) +# GoalScored -> next KickoffStarted : GOAL-PAUSE window (celebration; physics frozen) +# GoalReplayStarted -> GoalReplayEnded : REPLAY window (physics frozen) +# Anchors are matched even when the governing event lies OUTSIDE the clip window. + +# Badge codes. +LIVE = "LIVE" +KICKOFF = "KICKOFF" +PAUSE = "PAUSE" # goal pause (post-goal celebration) +REPLAY = "REPLAY" +FROZEN = "FROZEN" # frozen with no matching anchor window (boundary/offset slack) + +# Anchor-window codes (what the anchors say is happening, independent of motion). +_WIN_KICKOFF = "kickoff" +_WIN_GOAL_PAUSE = "goal_pause" +_WIN_REPLAY = "replay" +_WIN_PLAY = "play" + + +@dataclass +class Badge: + """One step's display badge: a `code`, a short `label`, and whether to show a frozen note.""" + + code: str + label: str + frozen: bool + + +def anchor_window_at_master_sec(events, master_sec: float) -> str: + """Which anchor window a master-clock time falls in: kickoff / goal_pause / replay / play. + + `events` is the full anchor list (pass the match-wide anchors, not the in-window subset).""" + win = _WIN_PLAY + for e in sorted(events, key=lambda x: x.master_sec): + if e.master_sec > master_sec: + break + name = e.event_name + if name == "KickoffStarted": + win = _WIN_KICKOFF + elif name == "KickoffEnded": + win = _WIN_PLAY + elif name == "GoalScored": + win = _WIN_GOAL_PAUSE + elif name == "GoalReplayStarted": + win = _WIN_REPLAY + elif name == "GoalReplayEnded": + win = _WIN_PLAY # play resumes at the following KickoffStarted (usually same instant) + return win + + +def frozen_steps(persp_physics: list[FrameState], eps_uu: float = 2.0) -> list[bool]: + """Per-step flag: True where live physics is frozen (ball + all cars unmoved vs a neighbour). + + Motion is the source of truth for whether the radar is moving. Each step is compared to its + successor; the last step is compared to its predecessor (so a lone trailing step is judged too).""" + n = len(persp_physics) + if n < 2: + return [False] * n + + def _still(a: FrameState, b: FrameState) -> bool: + moved = np.linalg.norm(np.array(_xyz(a["ball"]["location"])) - _xyz(b["ball"]["location"])) + for ca, cb in zip(a["cars"], b["cars"]): + moved += np.linalg.norm(np.array(_xyz(ca["location"])) - _xyz(cb["location"])) + return bool(moved < eps_uu) + + out = [_still(persp_physics[i], persp_physics[i + 1]) for i in range(n - 1)] + out.append(_still(persp_physics[-1], persp_physics[-2])) + return out + + +def _windows_for_clip(clip: "MatchClip", perspective: int) -> list[str] | None: + """Per-step anchor window for a clip, or None if anchors/global indices are unavailable.""" + anchors = clip.metadata[perspective].get("anchors") if clip.metadata else None + g_idx = clip.global_frame_indices + if not anchors or g_idx is None: + return None + events = parse_anchors(anchors) + offset = clip.recording_offsets[perspective] + return [anchor_window_at_master_sec(events, offset + g / clip.src_fps) for g in g_idx] + + +def step_badges(clip: "MatchClip", perspective: int = 0) -> list[Badge]: + """Per-step display badge for a clip (length T). MOTION decides frozen vs moving; ANCHORS supply + the reason. The badge can never be both "moving/LIVE" and "frozen": + + moving + kickoff window -> KICKOFF (no frozen note; cars are driving to the ball) + moving otherwise -> LIVE + frozen + replay window -> REPLAY (frozen note) + frozen + goal-pause win -> PAUSE (frozen note) + frozen + no window match -> FROZEN (neutral frozen note; never green LIVE) + """ + t = int(clip.actions.shape[1]) + frozen = frozen_steps(clip.physics[perspective]) if clip.physics is not None else [False] * t + windows = _windows_for_clip(clip, perspective) + + badges: list[Badge] = [] + for i in range(t): + is_frozen = frozen[i] if i < len(frozen) else False + win = windows[i] if windows is not None else None + if not is_frozen: + if win == _WIN_KICKOFF: + badges.append(Badge(KICKOFF, "KICKOFF", False)) + else: + badges.append(Badge(LIVE, "● LIVE", False)) + else: + if win == _WIN_REPLAY: + badges.append(Badge(REPLAY, "REPLAY · ⏸ physics frozen", True)) + elif win == _WIN_GOAL_PAUSE: + badges.append(Badge(PAUSE, "GOAL PAUSE · ⏸ physics frozen", True)) + else: + badges.append(Badge(FROZEN, "⏸ physics frozen", True)) + return badges + + +@dataclass +class Check: + """One consistency assertion: a human label, whether it passed, and a short detail string.""" + + label: str + ok: bool + detail: str = "" + + +def consistency_checks(clip: "MatchClip") -> list[Check]: + """Frame-alignment / sanity checks across a clip's frames, actions and physics. + + Each :class:`Check` is independent and never raises, so the explorer can render a full PASS/FAIL + table even when one mapping is broken. The match clock's per-perspective availability is reported + as a non-fatal informational check. + """ + checks: list[Check] = [] + p = len(clip.player_ids) + t = int(clip.actions.shape[1]) + + checks.append(Check("≥1 perspective", p >= 1, f"P={p}")) + + if clip.physics is None: + checks.append(Check("physics present", False, "clip.physics is None")) + return checks + checks.append(Check("physics present", True, f"{p} perspectives")) + + # len(frames) == len(actions) == len(physics), per perspective. + n_frames = None if clip.frames is None else int(clip.frames.shape[1]) + lens_ok = all(len(pp) == t for pp in clip.physics) + if n_frames is not None: + lens_ok = lens_ok and n_frames == t + detail = f"T_actions={t}" + (f", T_frames={n_frames}" if n_frames is not None else "") + detail += f", T_physics={[len(pp) for pp in clip.physics]}" + checks.append(Check("frames == actions == physics (per perspective)", lens_ok, detail)) + + # All perspectives observe the SAME world, but each is recorded on its own clock (see + # `recording_offset_sec`), so chunk-local frame f is a slightly different master-time instant + # per perspective — the ball tracks agree only up to a ~1-frame shift. Reports the best + # cross-perspective residual after allowing a +/-1 frame lag; a small residual means the + # perspectives share one world (just sub-frame-misaligned in time). + if p > 1: + b0 = ball_track(clip.physics[0]) + residuals = [_min_lag_residual(b0, ball_track(clip.physics[pi]), 1) for pi in range(1, p)] + worst = max(residuals) if residuals else 0.0 + offs = [round(o, 3) for o in clip.recording_offsets] + checks.append( + Check( + "perspectives share one world (ball ≈, ±1-frame lag)", + worst < 30.0, # uu; well under a car length, vs ~50 uu at zero lag + f"worst residual {worst:.1f} uu (offsets {offs})", + ) + ) + + # is_local picks exactly one car, and it matches the perspective's player_id. + local_ok, local_detail = True, "" + for pi, pp in enumerate(clip.physics): + try: + lc = local_car(pp[0]) + except ValueError as exc: + local_ok, local_detail = False, str(exc) + break + if lc["player_id"] != clip.player_ids[pi]: + local_ok = False + local_detail = f"persp {pi}: is_local player {lc['player_id']} != {clip.player_ids[pi]}" + break + checks.append(Check("is_local ↔ perspective player_id", local_ok, local_detail)) + + # Physics actually evolves (ball not frozen) — catches a stuck/duplicated state stream. + moves = ball_moves(clip.physics[0]) + track = ball_track(clip.physics[0]) + path = 0.0 if len(track) < 2 else float(np.linalg.norm(np.diff(track, axis=0), axis=1).sum()) + checks.append(Check("ball moves over clip", moves, f"path={path:.0f} uu")) + + # N_CARS per frame (2v2), boost in [0, 1]. + n_cars = {len(fr["cars"]) for pp in clip.physics for fr in pp} + checks.append( + Check(f"{N_CARS} cars every frame (2v2)", n_cars == {N_CARS}, f"car counts={sorted(n_cars)}") + ) + boosts = [c.get("boost_amount", 0.0) for pp in clip.physics for fr in pp for c in fr["cars"]] + bmin, bmax = (min(boosts), max(boosts)) if boosts else (0.0, 0.0) + checks.append(Check("boost in [0, 1]", 0.0 <= bmin and bmax <= 1.0, f"[{bmin:.2f}, {bmax:.2f}]")) + + # The match clock is logged only on the local perspective; informational, never fails the suite. + has_clock = perspective_has_clock(clip.physics[0]) + checks.append( + Check( + "match clock present (logged on the local perspective)", + True, # informational + "clock advances" if has_clock else "≡ 0.0 — clock is carried by another (local) perspective", + ) + ) + return checks diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/robotwin_loader.py b/release-20261107/source/workspace_joint/mira/src/mira/data/robotwin_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..78990c2cda6723637fecc56addcac1e9fba3337d --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/robotwin_loader.py @@ -0,0 +1,992 @@ +"""Streaming RoboTwin 2.0 codec data directly from the downloaded zip archives. + +RoboTwin stores one HDF5 file per episode. Each HDF5 file contains frame-aligned JPEG observations +from ``head_camera``, ``left_camera``, and ``right_camera``. The codec is video-only, so this loader +does not materialize robot actions. It emits empty, time-aligned ``ActionTensors`` only to satisfy +the shared ``VideoActionBatch`` interface. + +Training uses cyclic view allocation: a stable hash assigns each episode a starting camera and the +epoch advances it to the next camera. Every episode therefore covers all three views once every +three epochs without decoding three highly correlated samples back-to-back or reading its HDF5 +payload three times. +""" + +from __future__ import annotations + +import hashlib +import io +import json +import logging +import random +import re +import zipfile +from concurrent.futures import ThreadPoolExecutor, as_completed +from contextlib import ExitStack +from dataclasses import asdict, dataclass +from itertools import count +from pathlib import Path +from typing import Any, Literal, Sequence + +import h5py +import torch +from torch.utils.data import DataLoader, IterableDataset, get_worker_info +from torchvision.io import ImageReadMode, decode_jpeg + +from mira.world_model.actions_config import ActionConfig, ActionTensors, stack_action_tensors + +from .batch import VideoActionBatch + +logger = logging.getLogger(__name__) + +CAMERA_NAMES = ("head_camera", "left_camera", "right_camera") +CameraName = Literal["head_camera", "left_camera", "right_camera"] + +_COLLECTION_RE = re.compile(r"^(?P.+)_(?Pclean|randomized)_(?P\d+)$") +_EPISODE_RE = re.compile(r"/data/episode(?P\d+)\.hdf5$") + + +def _stable_int(value: str, seed: int = 0) -> int: + digest = hashlib.sha256(f"{seed}:{value}".encode()).digest() + return int.from_bytes(digest[:8], "big") + + +@dataclass(frozen=True) +class RoboTwinEpisode: + """One HDF5 episode stored as a member of a RoboTwin zip archive.""" + + archive: str + member: str + task: str + robot: str + domain: str + episode: int + uncompressed_bytes: int + compressed_bytes: int + + @property + def key(self) -> str: + return f"{self.archive}::{self.member}" + + @classmethod + def from_dict(cls, value: dict[str, Any]) -> RoboTwinEpisode: + return cls( + archive=str(value["archive"]), + member=str(value["member"]), + task=str(value["task"]), + robot=str(value["robot"]), + domain=str(value["domain"]), + episode=int(value["episode"]), + uncompressed_bytes=int(value["uncompressed_bytes"]), + compressed_bytes=int(value["compressed_bytes"]), + ) + + +@dataclass(frozen=True) +class FixedRoboTwinCase: + """A reproducible episode/time-window used for periodic three-view visualization.""" + + entry: RoboTwinEpisode + start_frame: int + + @property + def slug(self) -> str: + raw = ( + f"{self.entry.task}_{self.entry.robot}_{self.entry.domain}_" + f"episode{self.entry.episode:04d}" + ) + return re.sub(r"[^A-Za-z0-9_.-]+", "-", raw) + + +@dataclass +class RoboTwinClipMeta: + """Provenance for one decoded RoboTwin camera clip.""" + + task: str + robot: str + domain: str + episode: int + camera: CameraName + archive: str + member: str + start_frame: int + frame_indices: list[int] + + # Compatibility fields used by the existing codec visualization caption path. + perspective: int = 0 + player_id: int = 0 + clip_id: int = 0 + chunk_idx: int = 0 + + @property + def match_id(self) -> str: + return f"{self.task}/{self.robot}_{self.domain}/episode{self.episode}" + + @property + def caption(self) -> str: + return ( + f"{self.task} | {self.robot}/{self.domain} | ep{self.episode} | " + f"{self.camera} | frame {self.start_frame}" + ) + + +def _parse_archive(archive: Path, dataset_root: Path) -> list[RoboTwinEpisode]: + collection_match = _COLLECTION_RE.match(archive.stem) + if collection_match is None: + raise ValueError( + f"Unexpected RoboTwin collection name {archive.stem!r}; expected " + "'_(clean|randomized)_'." + ) + task = archive.parent.name + robot = collection_match.group("robot") + domain = collection_match.group("domain") + relative_archive = archive.relative_to(dataset_root).as_posix() + + entries: list[RoboTwinEpisode] = [] + with zipfile.ZipFile(archive) as handle: + for info in handle.infolist(): + episode_match = _EPISODE_RE.search(info.filename) + if episode_match is None: + continue + entries.append( + RoboTwinEpisode( + archive=relative_archive, + member=info.filename, + task=task, + robot=robot, + domain=domain, + episode=int(episode_match.group("episode")), + uncompressed_bytes=info.file_size, + compressed_bytes=info.compress_size, + ) + ) + return sorted(entries, key=lambda entry: entry.episode) + + +def _write_jsonl(path: Path, entries: Sequence[RoboTwinEpisode]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + with temporary.open("w", encoding="utf-8") as handle: + for entry in entries: + handle.write(json.dumps(asdict(entry), ensure_ascii=False, sort_keys=True) + "\n") + temporary.replace(path) + + +def minimum_source_frames(clip_len: int, source_fps: int, target_fps: int) -> int: + """Minimum source episode length needed for one fixed-rate output clip.""" + return _frame_offsets(clip_len, source_fps, target_fps)[-1] + 1 + + +def _manifest_signature(path: Path) -> dict[str, Any]: + resolved = path.expanduser().resolve() + stat = resolved.stat() + return { + "path": str(resolved), + "size": stat.st_size, + "mtime_ns": stat.st_mtime_ns, + } + + +def _episode_camera_lengths(payload: bytes, entry: RoboTwinEpisode) -> tuple[int, int, int]: + with h5py.File(io.BytesIO(payload), "r") as episode: + paths = [f"observation/{camera}/rgb" for camera in CAMERA_NAMES] + missing = [path for path in paths if path not in episode] + if missing: + raise ValueError(f"{entry.key} is missing {missing}") + datasets = [episode[path] for path in paths] + if not all(isinstance(dataset, h5py.Dataset) for dataset in datasets): + raise ValueError(f"{entry.key} has a non-dataset camera entry") + return tuple(len(dataset) for dataset in datasets) # type: ignore[return-value] + + +def _probe_positions(n_entries: int, n_probes: int) -> list[int]: + if n_entries < 1: + return [] + n_probes = min(max(1, n_probes), n_entries) + if n_probes == 1: + return [n_entries // 2] + return sorted( + { + round(probe_index * (n_entries - 1) / (n_probes - 1)) + for probe_index in range(n_probes) + } + ) + + +def _audit_archive( + dataset_root: Path, + archive: str, + entries: Sequence[RoboTwinEpisode], + *, + min_source_frames: int, + probes_per_archive: int, +) -> dict[str, Any]: + """Probe one archive and fully inspect it only when a probe is incompatible.""" + ordered = sorted(entries, key=lambda entry: entry.episode) + inspected: dict[str, dict[str, Any]] = {} + + with zipfile.ZipFile(dataset_root / archive) as handle: + + def inspect(entry: RoboTwinEpisode) -> dict[str, Any]: + existing = inspected.get(entry.key) + if existing is not None: + return existing + try: + lengths = _episode_camera_lengths(handle.read(entry.member), entry) + aligned = len(set(lengths)) == 1 + compatible = aligned and lengths[0] >= min_source_frames + result = { + "archive": entry.archive, + "member": entry.member, + "task": entry.task, + "robot": entry.robot, + "domain": entry.domain, + "episode": entry.episode, + "camera_lengths": list(lengths), + "aligned": aligned, + "compatible": compatible, + "error": None, + } + except (KeyError, OSError, RuntimeError, ValueError, zipfile.BadZipFile) as exc: + result = { + "archive": entry.archive, + "member": entry.member, + "task": entry.task, + "robot": entry.robot, + "domain": entry.domain, + "episode": entry.episode, + "camera_lengths": None, + "aligned": False, + "compatible": False, + "error": f"{type(exc).__name__}: {exc}", + } + inspected[entry.key] = result + return result + + probes = [inspect(ordered[index]) for index in _probe_positions(len(ordered), probes_per_archive)] + full_scan = not all(result["compatible"] for result in probes) + if full_scan: + for entry in ordered: + inspect(entry) + + invalid = [result for result in inspected.values() if not result["compatible"]] + return { + "archive": archive, + "full_scan": full_scan, + "episodes": len(ordered), + "inspected": list(inspected.values()), + "invalid": invalid, + } + + +def build_robotwin_compatible_manifests( + dataset_root: str | Path, + train_manifest: str | Path, + val_manifest: str | Path, + output_dir: str | Path, + *, + clip_len: int, + source_fps: int, + target_fps: int, + probes_per_archive: int = 3, + workers: int = 8, + force: bool = False, +) -> dict[str, Any]: + """Build clip-compatible manifests with adaptive archive auditing. + + Each archive is first checked at evenly spaced probe episodes. If any probe is too short, + misaligned, corrupt, or missing a camera, every episode in that archive is inspected exactly. + Archives whose probes all pass remain eligible without reading every payload. This catches + systematic short-trajectory collections efficiently while avoiding a full dataset decompression. + """ + if probes_per_archive < 1: + raise ValueError("probes_per_archive must be at least 1") + if workers < 1: + raise ValueError("workers must be at least 1") + + dataset_root = Path(dataset_root).expanduser().resolve() + train_manifest = Path(train_manifest).expanduser().resolve() + val_manifest = Path(val_manifest).expanduser().resolve() + output_dir = Path(output_dir).expanduser().resolve() + output_dir.mkdir(parents=True, exist_ok=True) + summary_path = output_dir / "summary.json" + expected = { + "version": 1, + "dataset_root": str(dataset_root), + "train_manifest": _manifest_signature(train_manifest), + "val_manifest": _manifest_signature(val_manifest), + "clip_len": clip_len, + "source_fps": source_fps, + "target_fps": target_fps, + "min_source_frames": minimum_source_frames(clip_len, source_fps, target_fps), + "probes_per_archive": probes_per_archive, + } + compatible_train_path = output_dir / "train.jsonl" + compatible_val_path = output_dir / "val.jsonl" + index_path = output_dir / "compatibility_index.jsonl" + if ( + not force + and summary_path.is_file() + and compatible_train_path.is_file() + and compatible_val_path.is_file() + and index_path.is_file() + ): + saved = json.loads(summary_path.read_text(encoding="utf-8")) + if saved.get("settings") == expected: + return saved + + train_entries = load_robotwin_manifest(train_manifest) + val_entries = load_robotwin_manifest(val_manifest) + all_entries = train_entries + val_entries + entries_by_archive: dict[str, list[RoboTwinEpisode]] = {} + for entry in all_entries: + entries_by_archive.setdefault(entry.archive, []).append(entry) + + audit_results: list[dict[str, Any]] = [] + min_source_frames = expected["min_source_frames"] + with ThreadPoolExecutor(max_workers=min(workers, len(entries_by_archive))) as executor: + futures = { + executor.submit( + _audit_archive, + dataset_root, + archive, + entries, + min_source_frames=min_source_frames, + probes_per_archive=probes_per_archive, + ): archive + for archive, entries in entries_by_archive.items() + } + for completed_count, future in enumerate(as_completed(futures), start=1): + result = future.result() + audit_results.append(result) + if completed_count % 25 == 0 or completed_count == len(futures): + logger.info( + "RoboTwin compatibility audit: %d/%d archives", + completed_count, + len(futures), + ) + + audit_results.sort(key=lambda result: result["archive"]) + invalid_records = [record for result in audit_results for record in result["invalid"]] + invalid_keys = { + f"{record['archive']}::{record['member']}" + for record in invalid_records + } + compatible_train = [entry for entry in train_entries if entry.key not in invalid_keys] + compatible_val = [entry for entry in val_entries if entry.key not in invalid_keys] + if not compatible_train or not compatible_val: + raise RuntimeError( + "Compatibility filtering removed an entire split; inspect the generated audit index" + ) + + _write_jsonl(compatible_train_path, compatible_train) + _write_jsonl(compatible_val_path, compatible_val) + temporary_index = index_path.with_suffix(index_path.suffix + ".tmp") + with temporary_index.open("w", encoding="utf-8") as handle: + for result in audit_results: + for record in sorted(result["inspected"], key=lambda item: item["member"]): + handle.write(json.dumps(record, ensure_ascii=False, sort_keys=True) + "\n") + temporary_index.replace(index_path) + + invalid_groups: dict[str, int] = {} + for record in invalid_records: + key = f"{record['task']}|{record['robot']}|{record['domain']}" + invalid_groups[key] = invalid_groups.get(key, 0) + 1 + exact_scans = sum(len(result["inspected"]) for result in audit_results) + summary = { + "settings": expected, + "archives": len(audit_results), + "fully_scanned_archives": sum(bool(result["full_scan"]) for result in audit_results), + "exact_episode_scans": exact_scans, + "probe_verified_archives": sum(not result["full_scan"] for result in audit_results), + "input_train_episodes": len(train_entries), + "input_val_episodes": len(val_entries), + "compatible_train_episodes": len(compatible_train), + "compatible_val_episodes": len(compatible_val), + "invalid_episodes": len(invalid_keys), + "invalid_fraction": len(invalid_keys) / len(all_entries), + "invalid_groups": dict(sorted(invalid_groups.items())), + "compatible_train_manifest": str(compatible_train_path), + "compatible_val_manifest": str(compatible_val_path), + "compatibility_index": str(index_path), + } + temporary_summary = summary_path.with_suffix(summary_path.suffix + ".tmp") + temporary_summary.write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n") + temporary_summary.replace(summary_path) + return summary + + +def build_robotwin_manifests( + dataset_root: str | Path, + output_dir: str | Path, + *, + val_fraction: float = 0.02, + seed: int = 2026, +) -> dict[str, Any]: + """Scan zip central directories and build stable episode-level train/validation manifests. + + Splitting is performed independently inside every task/robot/domain archive. At least one + episode is retained on each side when an archive has two or more episodes, so validation covers + the full embodiment/domain distribution without leaking an episode across splits. + """ + if not 0 < val_fraction < 1: + raise ValueError(f"val_fraction must be between 0 and 1, got {val_fraction}") + dataset_root = Path(dataset_root).expanduser().resolve() + output_dir = Path(output_dir).expanduser().resolve() + archive_paths = sorted((dataset_root / "dataset").glob("*/*.zip")) + if not archive_paths: + raise FileNotFoundError(f"No RoboTwin zip archives found under {dataset_root / 'dataset'}") + + train_entries: list[RoboTwinEpisode] = [] + val_entries: list[RoboTwinEpisode] = [] + empty_archives: list[str] = [] + for archive in archive_paths: + entries = _parse_archive(archive, dataset_root) + if not entries: + empty_archives.append(archive.relative_to(dataset_root).as_posix()) + continue + + ranked = sorted(entries, key=lambda entry: _stable_int(entry.key, seed)) + n_val = max(1, round(len(entries) * val_fraction)) if len(entries) > 1 else 0 + n_val = min(n_val, max(0, len(entries) - 1)) + val_keys = {entry.key for entry in ranked[:n_val]} + train_entries.extend(entry for entry in entries if entry.key not in val_keys) + val_entries.extend(entry for entry in entries if entry.key in val_keys) + + train_entries.sort(key=lambda entry: (entry.task, entry.archive, entry.episode)) + val_entries.sort(key=lambda entry: (entry.task, entry.archive, entry.episode)) + _write_jsonl(output_dir / "train.jsonl", train_entries) + _write_jsonl(output_dir / "val.jsonl", val_entries) + + summary = { + "dataset_root": str(dataset_root), + "seed": seed, + "val_fraction": val_fraction, + "archives": len(archive_paths), + "empty_archives": empty_archives, + "train_episodes": len(train_entries), + "val_episodes": len(val_entries), + "tasks": len({entry.task for entry in train_entries + val_entries}), + "robots": sorted({entry.robot for entry in train_entries + val_entries}), + "domains": sorted({entry.domain for entry in train_entries + val_entries}), + "cameras": list(CAMERA_NAMES), + } + summary_path = output_dir / "summary.json" + temporary_summary = summary_path.with_suffix(".json.tmp") + temporary_summary.write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n") + temporary_summary.replace(summary_path) + return summary + + +def load_robotwin_manifest( + manifest_path: str | Path, + *, + tasks: Sequence[str] = (), + robots: Sequence[str] = (), + domains: Sequence[str] = (), +) -> list[RoboTwinEpisode]: + """Load and optionally filter a RoboTwin JSONL manifest.""" + manifest_path = Path(manifest_path) + if not manifest_path.is_file(): + raise FileNotFoundError( + f"RoboTwin manifest not found: {manifest_path}. Run scripts/build_robotwin_manifest.py." + ) + task_filter, robot_filter, domain_filter = set(tasks), set(robots), set(domains) + entries: list[RoboTwinEpisode] = [] + with manifest_path.open(encoding="utf-8") as handle: + for line_number, line in enumerate(handle, start=1): + if not line.strip(): + continue + try: + entry = RoboTwinEpisode.from_dict(json.loads(line)) + except (KeyError, TypeError, ValueError, json.JSONDecodeError) as exc: + raise ValueError(f"Invalid manifest row {manifest_path}:{line_number}") from exc + if task_filter and entry.task not in task_filter: + continue + if robot_filter and entry.robot not in robot_filter: + continue + if domain_filter and entry.domain not in domain_filter: + continue + entries.append(entry) + if not entries: + raise ValueError( + f"No RoboTwin episodes remain after filtering {manifest_path}; " + f"tasks={list(tasks)}, robots={list(robots)}, domains={list(domains)}" + ) + return entries + + +def _rank_and_world_size() -> tuple[int, int]: + if torch.distributed.is_available() and torch.distributed.is_initialized(): + return torch.distributed.get_rank(), torch.distributed.get_world_size() + return 0, 1 + + +def _frame_offsets(clip_len: int, source_fps: int, target_fps: int) -> list[int]: + if clip_len < 1: + raise ValueError(f"clip_len must be positive, got {clip_len}") + if source_fps < target_fps: + raise ValueError( + f"RoboTwin upsampling is disabled: source_fps={source_fps}, target_fps={target_fps}" + ) + # Half-up nearest-neighbour sampling avoids Python's banker's rounding at x.5 timestamps. + return [int(frame * source_fps / target_fps + 0.5) for frame in range(clip_len)] + + +def _decode_jpeg_frames(dataset: h5py.Dataset, indices: Sequence[int]) -> torch.Tensor: + encoded = [ + torch.frombuffer(bytearray(bytes(dataset[index])), dtype=torch.uint8) for index in indices + ] + decoded = decode_jpeg(encoded, mode=ImageReadMode.RGB) + assert isinstance(decoded, list) + return torch.stack(decoded, dim=0) + + +def _decode_episode_payload( + payload: bytes, + entry: RoboTwinEpisode, + *, + views: Sequence[CameraName], + clip_len: int, + source_fps: int, + target_fps: int, + start_frame: int | None, + rng: random.Random | None, +) -> tuple[dict[CameraName, torch.Tensor], int, list[int]]: + offsets = _frame_offsets(clip_len, source_fps, target_fps) + with h5py.File(io.BytesIO(payload), "r") as episode: + camera_paths: dict[CameraName, str] = { + view: f"observation/{view}/rgb" for view in views + } + missing = [path for path in camera_paths.values() if path not in episode] + if missing: + raise ValueError(f"{entry.key} is missing required camera datasets: {missing}") + camera_datasets: dict[CameraName, h5py.Dataset] = {} + for view, path in camera_paths.items(): + dataset = episode[path] + if not isinstance(dataset, h5py.Dataset): + raise ValueError(f"{entry.key}:{path} is not an HDF5 dataset") + camera_datasets[view] = dataset + lengths = {len(dataset) for dataset in camera_datasets.values()} + if len(lengths) != 1: + raise ValueError(f"{entry.key} has misaligned camera lengths: {sorted(lengths)}") + n_frames = lengths.pop() + max_start = n_frames - 1 - offsets[-1] + if max_start < 0: + raise ValueError( + f"{entry.key} has {n_frames} frames, shorter than {clip_len} @ " + f"{target_fps}fps sampled from {source_fps}fps" + ) + if start_frame is None: + if rng is None: + raise ValueError("rng is required when start_frame is not fixed") + start_frame = rng.randint(0, max_start) + elif not 0 <= start_frame <= max_start: + raise ValueError( + f"Fixed start_frame={start_frame} is outside [0, {max_start}] for {entry.key}" + ) + indices = [start_frame + offset for offset in offsets] + videos: dict[CameraName, torch.Tensor] = { + view: _decode_jpeg_frames(dataset, indices) + for view, dataset in camera_datasets.items() + } + return videos, start_frame, indices + + +def _empty_actions(clip_len: int, target_fps: int) -> ActionTensors: + config = ActionConfig(valid_keys=[], source_fps=target_fps, target_fps=target_fps) + actions = ActionTensors(config=config, batch_size=1) + actions.key_presses = torch.zeros((1, clip_len, 0), dtype=torch.int32) + actions.mouse_movements = torch.zeros((1, clip_len, 2), dtype=torch.float32) + return actions + + +def _sample( + video: torch.Tensor, + entry: RoboTwinEpisode, + camera: CameraName, + start_frame: int, + frame_indices: list[int], + target_fps: int, +) -> dict[str, Any]: + return { + "video": video, + "actions": _empty_actions(video.shape[0], target_fps), + "metadata": RoboTwinClipMeta( + task=entry.task, + robot=entry.robot, + domain=entry.domain, + episode=entry.episode, + camera=camera, + archive=entry.archive, + member=entry.member, + start_frame=start_frame, + frame_indices=frame_indices, + perspective=CAMERA_NAMES.index(camera), + player_id=CAMERA_NAMES.index(camera), + clip_id=entry.episode, + ), + } + + +def _collate(samples: list[dict[str, Any]]) -> tuple[VideoActionBatch, list[RoboTwinClipMeta]]: + video = torch.stack([sample["video"] for sample in samples], dim=0) + actions = stack_action_tensors([sample["actions"] for sample in samples]) + metadata = [sample["metadata"] for sample in samples] + return VideoActionBatch(video=video, actions=actions), metadata + + +class _RoboTwinIterable(IterableDataset): + """Archive-sharded, infinite RoboTwin episode stream with cyclic three-view allocation.""" + + def __init__( + self, + dataset_root: str | Path, + manifest_path: str | Path, + *, + clip_len: int, + source_fps: int, + target_fps: int, + shuffle: bool, + infinite: bool, + seed: int, + archive_mix_size: int, + tasks: Sequence[str], + robots: Sequence[str], + domains: Sequence[str], + ) -> None: + super().__init__() + if archive_mix_size < 1: + raise ValueError(f"archive_mix_size must be >= 1, got {archive_mix_size}") + self.dataset_root = Path(dataset_root).expanduser().resolve() + entries = load_robotwin_manifest( + manifest_path, tasks=tasks, robots=robots, domains=domains + ) + self.entries_by_archive: dict[str, list[RoboTwinEpisode]] = {} + for entry in entries: + self.entries_by_archive.setdefault(entry.archive, []).append(entry) + self.clip_len = clip_len + self.source_fps = source_fps + self.target_fps = target_fps + self.shuffle = shuffle + self.infinite = infinite + self.seed = seed + self.archive_mix_size = archive_mix_size + + def _my_archives(self) -> tuple[list[str], int, int]: + rank, world_size = _rank_and_world_size() + worker = get_worker_info() + worker_id, num_workers = (worker.id, worker.num_workers) if worker is not None else (0, 1) + rank_archives = sorted(self.entries_by_archive)[rank::world_size] + return rank_archives[worker_id::num_workers], rank, worker_id + + def __iter__(self): + my_archives, rank, worker_id = self._my_archives() + if not my_archives: + raise RuntimeError( + "This RoboTwin dataloader worker received no archives. Reduce dataloader.num_workers " + "or the distributed world size, or broaden the dataset filters." + ) + + bad_samples = 0 + invalid_entries: set[str] = set() + epochs = count() if self.infinite else range(1) + for epoch in epochs: + rng = random.Random(self.seed + epoch * 1_000_003 + rank * 10_007 + worker_id) + archives = list(my_archives) + if self.shuffle: + rng.shuffle(archives) + yielded = 0 + + for block_start in range(0, len(archives), self.archive_mix_size): + block = archives[block_start : block_start + self.archive_mix_size] + queues = { + archive: [ + entry + for entry in self.entries_by_archive[archive] + if entry.key not in invalid_entries + ] + for archive in block + } + if self.shuffle: + for entries in queues.values(): + rng.shuffle(entries) + + with ExitStack() as stack: + handles = { + archive: stack.enter_context( + zipfile.ZipFile(self.dataset_root / archive) + ) + for archive in block + } + while any(queues.values()): + active = [archive for archive, entries in queues.items() if entries] + if self.shuffle: + rng.shuffle(active) + for archive in active: + entry = queues[archive].pop() + view_epoch = epoch if self.shuffle else 0 + camera = CAMERA_NAMES[ + (_stable_int(entry.key, self.seed) + view_epoch) % len(CAMERA_NAMES) + ] + try: + payload = handles[archive].read(entry.member) + videos, start_frame, indices = _decode_episode_payload( + payload, + entry, + views=(camera,), + clip_len=self.clip_len, + source_fps=self.source_fps, + target_fps=self.target_fps, + start_frame=None, + rng=rng, + ) + except ( + KeyError, + OSError, + RuntimeError, + ValueError, + zipfile.BadZipFile, + ) as exc: + invalid_entries.add(entry.key) + bad_samples += 1 + if bad_samples <= 10: + logger.warning( + "Skipping invalid RoboTwin episode %s: %s", + entry.key, + exc, + ) + continue + yielded += 1 + yield _sample( + videos[camera], + entry, + camera, + start_frame, + indices, + self.target_fps, + ) + if yielded == 0: + raise RuntimeError( + "RoboTwin worker completed an epoch without a valid clip. Check clip_len/fps, " + "camera fields, and the generated manifest." + ) + + +def create_robotwin_loader( + dataset_root: str | Path, + manifest_path: str | Path, + *, + clip_len: int = 40, + source_fps: int = 30, + target_fps: int = 20, + batch_size: int = 1, + num_workers: int = 4, + shuffle: bool = True, + infinite: bool = True, + seed: int = 2026, + archive_mix_size: int = 8, + tasks: Sequence[str] = (), + robots: Sequence[str] = (), + domains: Sequence[str] = (), + prefetch_factor: int = 2, + pin_memory: bool | None = None, +) -> DataLoader: + """Build the codec loader for zipped RoboTwin HDF5 episodes.""" + dataset = _RoboTwinIterable( + dataset_root, + manifest_path, + clip_len=clip_len, + source_fps=source_fps, + target_fps=target_fps, + shuffle=shuffle, + infinite=infinite, + seed=seed, + archive_mix_size=archive_mix_size, + tasks=tasks, + robots=robots, + domains=domains, + ) + rank, world_size = _rank_and_world_size() + rank_archives = sorted(dataset.entries_by_archive)[rank::world_size] + if not rank_archives: + raise ValueError( + f"Distributed rank {rank}/{world_size} received no RoboTwin archives. Reduce the GPU " + "count or broaden the task/robot/domain filters." + ) + effective_workers = min(num_workers, len(rank_archives)) + if effective_workers != num_workers: + logger.warning( + "Reducing RoboTwin dataloader workers from %d to %d for rank %d (%d archives)", + num_workers, + effective_workers, + rank, + len(rank_archives), + ) + return DataLoader( + dataset, + batch_size=batch_size, + num_workers=effective_workers, + prefetch_factor=prefetch_factor if effective_workers > 0 else None, + persistent_workers=effective_workers > 0, + pin_memory=torch.cuda.is_available() if pin_memory is None else pin_memory, + collate_fn=_collate, + drop_last=True, + ) + + +def _stratified_candidates(entries: Sequence[RoboTwinEpisode], seed: int) -> list[RoboTwinEpisode]: + groups: dict[tuple[str, str, str], list[RoboTwinEpisode]] = {} + for entry in entries: + groups.setdefault((entry.task, entry.robot, entry.domain), []).append(entry) + for group_entries in groups.values(): + group_entries.sort(key=lambda entry: _stable_int(entry.key, seed)) + group_order = sorted(groups, key=lambda group: _stable_int("|".join(group), seed)) + + ordered: list[RoboTwinEpisode] = [] + while any(groups.values()): + for group in group_order: + if groups[group]: + ordered.append(groups[group].pop()) + return ordered + + +def _episode_max_start( + dataset_root: Path, + entry: RoboTwinEpisode, + clip_len: int, + source_fps: int, + target_fps: int, +) -> int: + with zipfile.ZipFile(dataset_root / entry.archive) as archive: + payload = archive.read(entry.member) + offsets = _frame_offsets(clip_len, source_fps, target_fps) + with h5py.File(io.BytesIO(payload), "r") as episode: + paths = [f"observation/{camera}/rgb" for camera in CAMERA_NAMES] + missing = [path for path in paths if path not in episode] + if missing: + raise ValueError(f"{entry.key} is missing {missing}") + datasets = [episode[path] for path in paths] + if not all(isinstance(dataset, h5py.Dataset) for dataset in datasets): + raise ValueError(f"{entry.key} has a non-dataset camera entry") + lengths = {len(dataset) for dataset in datasets if isinstance(dataset, h5py.Dataset)} + if len(lengths) != 1: + raise ValueError(f"{entry.key} has misaligned camera lengths: {sorted(lengths)}") + return lengths.pop() - 1 - offsets[-1] + + +def prepare_fixed_robotwin_cases( + dataset_root: str | Path, + manifest_path: str | Path, + cases_path: str | Path, + *, + num_cases: int, + clip_len: int, + source_fps: int, + target_fps: int, + seed: int, + tasks: Sequence[str] = (), + robots: Sequence[str] = (), + domains: Sequence[str] = (), +) -> list[FixedRoboTwinCase]: + """Select and persist diverse fixed cases, reusing the same cases after resume.""" + if num_cases < 1: + return [] + dataset_root = Path(dataset_root).expanduser().resolve() + cases_path = Path(cases_path) + expected_settings = { + "dataset_root": str(dataset_root), + "manifest_path": str(Path(manifest_path).expanduser().resolve()), + "num_cases": num_cases, + "clip_len": clip_len, + "source_fps": source_fps, + "target_fps": target_fps, + "seed": seed, + "sampling": "nearest_half_up_v1", + "tasks": list(tasks), + "robots": list(robots), + "domains": list(domains), + } + if cases_path.is_file(): + saved = json.loads(cases_path.read_text()) + if saved.get("settings") == expected_settings: + cases = [ + FixedRoboTwinCase( + entry=RoboTwinEpisode.from_dict(case["entry"]), + start_frame=int(case["start_frame"]), + ) + for case in saved["cases"] + ] + if len(cases) == num_cases: + return cases + logger.warning("Fixed-case settings changed; rebuilding %s", cases_path) + + entries = load_robotwin_manifest( + manifest_path, tasks=tasks, robots=robots, domains=domains + ) + cases: list[FixedRoboTwinCase] = [] + for entry in _stratified_candidates(entries, seed): + try: + max_start = _episode_max_start( + dataset_root, entry, clip_len, source_fps, target_fps + ) + except (KeyError, OSError, RuntimeError, ValueError, zipfile.BadZipFile) as exc: + logger.warning("Cannot use fixed RoboTwin case %s: %s", entry.key, exc) + continue + if max_start < 0: + continue + start_frame = _stable_int(entry.key, seed + 1) % (max_start + 1) + cases.append(FixedRoboTwinCase(entry=entry, start_frame=start_frame)) + if len(cases) == num_cases: + break + if len(cases) != num_cases: + raise RuntimeError(f"Could prepare only {len(cases)} of {num_cases} fixed RoboTwin cases") + + payload = { + "settings": expected_settings, + "cameras": list(CAMERA_NAMES), + "cases": [ + {"entry": asdict(case.entry), "start_frame": case.start_frame} for case in cases + ], + } + cases_path.parent.mkdir(parents=True, exist_ok=True) + temporary = cases_path.with_suffix(cases_path.suffix + ".tmp") + temporary.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n") + temporary.replace(cases_path) + return cases + + +def load_fixed_robotwin_case( + dataset_root: str | Path, + case: FixedRoboTwinCase, + *, + clip_len: int, + source_fps: int, + target_fps: int, +) -> list[tuple[VideoActionBatch, RoboTwinClipMeta]]: + """Decode all three aligned camera views for one persisted fixed case.""" + dataset_root = Path(dataset_root).expanduser().resolve() + with zipfile.ZipFile(dataset_root / case.entry.archive) as archive: + payload = archive.read(case.entry.member) + videos, start_frame, indices = _decode_episode_payload( + payload, + case.entry, + views=CAMERA_NAMES, + clip_len=clip_len, + source_fps=source_fps, + target_fps=target_fps, + start_frame=case.start_frame, + rng=None, + ) + loaded: list[tuple[VideoActionBatch, RoboTwinClipMeta]] = [] + for camera in CAMERA_NAMES: + sample = _sample( + videos[camera], + case.entry, + camera, + start_frame, + indices, + target_fps, + ) + batch, metadata = _collate([sample]) + loaded.append((batch, metadata[0])) + return loaded diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/robotwin_rgb.py b/release-20261107/source/workspace_joint/mira/src/mira/data/robotwin_rgb.py new file mode 100644 index 0000000000000000000000000000000000000000..a74e07af9076b79f486ffc6e633bad15c3df4e2c --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/robotwin_rgb.py @@ -0,0 +1,26 @@ +"""Use the same marker-aware image decoder as the official RoboTwin server.""" +from functools import lru_cache +import os +from pathlib import Path +import sys + + +@lru_cache(maxsize=1) +def official_image_decoder(): + root = Path(os.environ.get( + "ROBOTWIN_EVAL_ROOT", + Path(__file__).resolve().parents[4] / "transfer/robotwin-official-20260921", + )).expanduser().resolve() + if not (root / "XPolicyLab/utils/process_data.py").is_file(): + raise FileNotFoundError( + f"Official RGB decoder missing under {root}; set ROBOTWIN_EVAL_ROOT to " + "the complete pinned RoboTwin checkout (including XPL-RGB1 support)." + ) + if str(root) not in sys.path: + sys.path.insert(0, str(root)) + from XPolicyLab.utils import process_data + if Path(process_data.__file__).resolve() != root / "XPolicyLab/utils/process_data.py": + raise RuntimeError("A different XPolicyLab checkout is already imported") + if getattr(process_data, "_RGB_MARKER_PAYLOAD", None) != b"XPL-RGB1": + raise RuntimeError("Official image decoder lacks legacy/standard RGB format support") + return process_data.decode_image_bit diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/robotwin_wam_loader.py b/release-20261107/source/workspace_joint/mira/src/mira/data/robotwin_wam_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..71a31e12fcd1c6517d1cef22ba37d40cf66385d6 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/robotwin_wam_loader.py @@ -0,0 +1,233 @@ +"""Map-style loader and deterministic task/domain sampler for cached Stage-W data.""" + +from __future__ import annotations + +import bisect +import json +import random +from collections import OrderedDict, defaultdict +from dataclasses import dataclass, fields +from pathlib import Path +from typing import Any, Iterator + +import torch +from safetensors.torch import load_file +from torch import Tensor +from torch.utils.data import Dataset, Sampler + +from .robotwin_wam_schema import CONTEXT_LATENTS, FUTURE_LATENTS, read_jsonl, world_window_slices + + +@dataclass +class RoboTwinWorldBatch: + """Only legal inputs to the Stage-W model; no future state or future action exists here.""" + + world_context_raw: Tensor + world_future_raw: Tensor + joint_target_history: Tensor + action_history: Tensor + history_valid: Tensor + text_hidden: Tensor + text_mask: Tensor + future_valid: Tensor + view_valid: Tensor + + def to(self, *args: Any, **kwargs: Any) -> "RoboTwinWorldBatch": + return RoboTwinWorldBatch( + **{field.name: getattr(self, field.name).to(*args, **kwargs) for field in fields(self)} + ) + + +class RoboTwinWAMDataset(Dataset[dict[str, Any]]): + def __init__( + self, + manifest: str | Path, + dataset_stats: str | Path, + *, + require_real_text: bool = True, + episode_cache_size: int = 2, + ) -> None: + self.manifest_path = Path(manifest).expanduser().resolve() + self.rows = read_jsonl(self.manifest_path) + if not self.rows: + raise ValueError(f"Empty Stage-W cache manifest: {manifest}") + if require_real_text and any(bool(row.get("text_cache_debug_only")) for row in self.rows): + raise ValueError("Formal Stage-W training refuses deterministic debug text embeddings") + if any(row.get("state_semantics") != "simulator_drive_target_not_measured_qpos" for row in self.rows): + raise ValueError("Ambiguous state semantics in Stage-W manifest") + + stats = json.loads(Path(dataset_stats).read_text(encoding="utf-8")) + self.state_mean = torch.tensor(stats["mean"], dtype=torch.float32) + self.state_std = torch.tensor(stats["std"], dtype=torch.float32).clamp_min( + float(stats.get("normalization_std_floor", 1.0e-2)) + ) + self.normalization_clip = float(stats.get("normalization_clip", 5.0)) + if self.state_mean.shape != (14,) or self.state_std.shape != (14,): + raise ValueError("Stage-W state statistics must be 14D") + + self.window_counts = [int(row["n_latents"]) - CONTEXT_LATENTS - FUTURE_LATENTS + 1 for row in self.rows] + if any(count <= 0 for count in self.window_counts): + raise ValueError("Manifest contains an episode without a complete Stage-W window") + self.cumulative = [0] + for count in self.window_counts: + self.cumulative.append(self.cumulative[-1] + count) + self.episode_cache_size = max(1, episode_cache_size) + self._episode_cache: OrderedDict[str, dict[str, Tensor]] = OrderedDict() + self._text_cache: OrderedDict[str, dict[str, Tensor]] = OrderedDict() + + self.task_domain_episodes: dict[str, dict[str, list[int]]] = defaultdict(lambda: defaultdict(list)) + for index, row in enumerate(self.rows): + self.task_domain_episodes[str(row["task"])][str(row["domain"])].append(index) + self.tasks = sorted(self.task_domain_episodes) + + def __len__(self) -> int: + return self.cumulative[-1] + + def window_index(self, episode_index: int, latent_start: int) -> int: + if not 0 <= latent_start < self.window_counts[episode_index]: + raise IndexError((episode_index, latent_start)) + return self.cumulative[episode_index] + latent_start + + def _locate(self, index: int) -> tuple[int, int]: + if not 0 <= index < len(self): + raise IndexError(index) + episode = bisect.bisect_right(self.cumulative, index) - 1 + return episode, index - self.cumulative[episode] + + @staticmethod + def _lru_load(path: str, cache: OrderedDict[str, dict[str, Tensor]], limit: int) -> dict[str, Tensor]: + if path in cache: + value = cache.pop(path) + cache[path] = value + return value + value = load_file(path, device="cpu") + cache[path] = value + while len(cache) > limit: + cache.popitem(last=False) + return value + + def _normalize(self, value: Tensor) -> Tensor: + return ((value.float() - self.state_mean) / self.state_std).clamp( + -self.normalization_clip, self.normalization_clip + ) + + def __getitem__(self, index: int) -> dict[str, Any]: + episode_index, latent_start = self._locate(index) + row = self.rows[episode_index] + episode = self._lru_load(str(row["cache_path"]), self._episode_cache, self.episode_cache_size) + text = self._lru_load(str(row["text_cache_path"]), self._text_cache, 64) + slices = world_window_slices(latent_start) + latent = episode["world_latent_raw_bf16"] + context = latent[:, slices["context"]] + future = latent[:, slices["future"]] + if context.shape != (3, 10, 32, 9, 12) or future.shape != (3, 10, 32, 9, 12): + raise RuntimeError(f"Invalid cached window shape for {row['episode_sha256']}:{latent_start}") + + state = episode["joint_target_state20_f32"] + action = episode["action20_f32"] + state_start = 2 * latent_start + q_history = self._normalize(state[state_start : state_start + 20]).reshape(20, 2, 7) + if q_history.shape != (20, 2, 7): + raise RuntimeError("Truncated state history") + history_valid = torch.ones(20, dtype=torch.bool) + if state_start == 0: + # The first previous action does not exist. A zero placeholder is replaced by the + # model's learned BOS vector and cannot leak into the valid history. + previous = torch.zeros(20, 14, dtype=torch.float32) + previous[1:] = action[:19] + history_valid[0] = False + else: + previous = action[state_start - 1 : state_start + 19] + a_history = self._normalize(previous).reshape(20, 2, 7) + if a_history.shape != (20, 2, 7): + raise RuntimeError("Truncated action history") + + return { + "world_context_raw": context, + "world_future_raw": future, + "joint_target_history": q_history, + "action_history": a_history, + "history_valid": history_valid, + "text_hidden": text["text_hidden_bf16"], + "text_mask": text["text_mask_bool"], + "future_valid": torch.ones(10, dtype=torch.bool), + "view_valid": torch.ones(3, dtype=torch.bool), + "metadata": { + "episode_sha256": row["episode_sha256"], + "latent_start": latent_start, + "task": row["task"], + "domain": row["domain"], + "instruction": row["instruction"], + }, + } + + +def collate_robotwin_wam(samples: list[dict[str, Any]]) -> tuple[RoboTwinWorldBatch, list[dict[str, Any]]]: + max_text = max(sample["text_hidden"].shape[0] for sample in samples) + text = torch.zeros(len(samples), max_text, 4096, dtype=torch.bfloat16) + mask = torch.zeros(len(samples), max_text, dtype=torch.bool) + for index, sample in enumerate(samples): + length = sample["text_hidden"].shape[0] + text[index, :length] = sample["text_hidden"] + mask[index, :length] = sample["text_mask"] + batch = RoboTwinWorldBatch( + world_context_raw=torch.stack([sample["world_context_raw"] for sample in samples]), + world_future_raw=torch.stack([sample["world_future_raw"] for sample in samples]), + joint_target_history=torch.stack([sample["joint_target_history"] for sample in samples]), + action_history=torch.stack([sample["action_history"] for sample in samples]), + history_valid=torch.stack([sample["history_valid"] for sample in samples]), + text_hidden=text, + text_mask=mask, + future_valid=torch.stack([sample["future_valid"] for sample in samples]), + view_valid=torch.stack([sample["view_valid"] for sample in samples]), + ) + return batch, [sample["metadata"] for sample in samples] + + +class DeterministicBalancedSampler(Sampler[int]): + """Infinite, resumable task-first sampler whose prefetch does not advance saved state.""" + + def __init__( + self, + dataset: RoboTwinWAMDataset, + *, + seed: int, + rank: int = 0, + world_size: int = 1, + clean_probability: float = 0.5, + start_index: int = 0, + ) -> None: + self.dataset = dataset + self.seed = seed + self.rank = rank + self.world_size = world_size + self.clean_probability = clean_probability + self.consumed = start_index + + def __len__(self) -> int: + return 2**31 + + def __iter__(self) -> Iterator[int]: + local_position = self.consumed + while True: + global_position = local_position * self.world_size + self.rank + rng = random.Random(self.seed + global_position * 1_000_003) + task = self.dataset.tasks[rng.randrange(len(self.dataset.tasks))] + domains = self.dataset.task_domain_episodes[task] + desired = "clean" if rng.random() < self.clean_probability else "randomized" + if desired not in domains: + desired = sorted(domains)[rng.randrange(len(domains))] + episodes = domains[desired] + episode = episodes[rng.randrange(len(episodes))] + latent_start = rng.randrange(self.dataset.window_counts[episode]) + yield self.dataset.window_index(episode, latent_start) + local_position += 1 + + def mark_consumed(self, samples: int) -> None: + self.consumed += samples + + def state_dict(self) -> dict[str, int]: + return {"consumed": self.consumed} + + def load_state_dict(self, state: dict[str, int]) -> None: + self.consumed = int(state["consumed"]) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/robotwin_wam_schema.py b/release-20261107/source/workspace_joint/mira/src/mira/data/robotwin_wam_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..8a429c69716290ce4f7ce862df0c4d3d7b8bce08 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/robotwin_wam_schema.py @@ -0,0 +1,199 @@ +"""Immutable RoboTwin Stage-W data contracts. + +The raw RoboTwin field named ``joint_action`` is a record of simulator drive targets, not a +measured joint position. This module deliberately calls it ``joint_target_state`` everywhere +outside the raw-HDF5 boundary so a later deployment adapter cannot silently confuse the two. +""" + +from __future__ import annotations + +import hashlib +import json +import math +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Any, Sequence + +import torch + +VIEW_NAMES = ("left", "global", "right") +CAMERA_PATHS = ( + "observation/left_camera/rgb", + "observation/head_camera/rgb", + "observation/right_camera/rgb", +) +RAW_COMPONENT_PATHS = ( + "joint_action/left_arm", + "joint_action/left_gripper", + "joint_action/right_arm", + "joint_action/right_gripper", +) +RAW_VECTOR_PATH = "joint_action/vector" + +SOURCE_FPS = 30 +VIDEO_FPS = 20 +LATENT_FPS = 10 +CONTEXT_LATENTS = 10 +FUTURE_LATENTS = 10 +STATE_HISTORY = 20 +LATENT_CHANNELS = 32 +LATENT_HEIGHT = 9 +LATENT_WIDTH = 12 +JOINT_DIM = 14 + + +def sha256_text(value: str) -> str: + return hashlib.sha256(value.encode("utf-8")).hexdigest() + + +def sha256_file(path: str | Path, chunk_bytes: int = 8 * 1024 * 1024) -> str: + """Hash a file without materialising it in memory.""" + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + while chunk := handle.read(chunk_bytes): + digest.update(chunk) + return digest.hexdigest() + + +def half_up_source_indices( + n_source_frames: int, + *, + source_fps: int = SOURCE_FPS, + target_fps: int = VIDEO_FPS, +) -> torch.Tensor: + """Return every valid ``round-half-up(i * source_fps / target_fps)`` index.""" + if n_source_frames <= 0: + raise ValueError(f"n_source_frames must be positive, got {n_source_frames}") + if source_fps < target_fps: + raise ValueError("RoboTwin Stage-W does not permit video upsampling") + indices: list[int] = [] + i = 0 + while True: + source = math.floor(i * source_fps / target_fps + 0.5) + if source >= n_source_frames: + break + indices.append(source) + i += 1 + return torch.tensor(indices, dtype=torch.int32) + + +def reconstruct_joint_vector(components: Sequence[torch.Tensor]) -> torch.Tensor: + """Rebuild the raw 14D order ``left6, left_gripper, right6, right_gripper``.""" + if len(components) != 4: + raise ValueError(f"Expected four joint components, got {len(components)}") + left, left_gripper, right, right_gripper = components + if left.ndim != 2 or left.shape[-1] != 6 or right.ndim != 2 or right.shape[-1] != 6: + raise ValueError(f"Expected 6D arm matrices, got {left.shape=} and {right.shape=}") + left_gripper = left_gripper.reshape(-1, 1) + right_gripper = right_gripper.reshape(-1, 1) + lengths = {left.shape[0], left_gripper.shape[0], right.shape[0], right_gripper.shape[0]} + if len(lengths) != 1: + raise ValueError(f"Joint component lengths differ: {sorted(lengths)}") + return torch.cat([left, left_gripper, right, right_gripper], dim=-1) + + +def derive_target_state_and_action( + raw_joint_vector: torch.Tensor, + source_indices: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor]: + """Resample drive targets to 20 Hz and derive the next-target action convention. + + ``joint_target_state20[i]`` is the recorded drive target at the selected source frame and + ``action20[i] = joint_target_state20[i + 1]``. Stage W never loads ``action20`` into the + model; it is cached only to freeze the downstream interface. + """ + if raw_joint_vector.ndim != 2 or raw_joint_vector.shape[-1] != JOINT_DIM: + raise ValueError(f"Expected raw joint vector [T,{JOINT_DIM}], got {raw_joint_vector.shape}") + source_indices = source_indices.long() + if source_indices.numel() < 2 or int(source_indices[-1]) >= raw_joint_vector.shape[0]: + raise ValueError("Invalid source indices for the joint target sequence") + target_state = raw_joint_vector.index_select(0, source_indices).float().contiguous() + return target_state, target_state[1:].clone() + + +def world_window_slices(latent_start: int) -> dict[str, slice]: + """Exact Stage-W slices for one latent start index.""" + if latent_start < 0: + raise ValueError(f"latent_start must be non-negative, got {latent_start}") + state_start = 2 * latent_start + return { + "context": slice(latent_start, latent_start + CONTEXT_LATENTS), + "future": slice( + latent_start + CONTEXT_LATENTS, + latent_start + CONTEXT_LATENTS + FUTURE_LATENTS, + ), + "state_history": slice(state_start, state_start + STATE_HISTORY), + # The action-history start is handled specially at episode start (learned BOS). + "action_history": slice(max(0, state_start - 1), state_start + STATE_HISTORY - 1), + } + + +def valid_latent_starts(n_latents: int) -> range: + needed = CONTEXT_LATENTS + FUTURE_LATENTS + return range(max(0, n_latents - needed + 1)) + + +@dataclass(frozen=True) +class WAMEpisode: + """One audited raw episode and its frozen Stage-W provenance.""" + + archive: str + member: str + task: str + robot: str + domain: str + episode: int + n_source_frames: int + n_video20_frames: int + n_latents: int + instruction: str + instruction_sha256: str + episode_sha256: str + split: str + state_semantics: str = "simulator_drive_target_not_measured_qpos" + + @property + def key(self) -> str: + return f"{self.archive}::{self.member}" + + @classmethod + def from_dict(cls, value: dict[str, Any]) -> "WAMEpisode": + fields = {field.name for field in cls.__dataclass_fields__.values()} # type: ignore[attr-defined] + return cls(**{key: value[key] for key in fields}) + + def to_dict(self) -> dict[str, Any]: + return asdict(self) + + +@dataclass(frozen=True) +class CachedWAMEpisode(WAMEpisode): + cache_path: str = "" + text_cache_path: str = "" + codec_sha256: str = "" + cache_format_version: int = 1 + + +def read_jsonl(path: str | Path) -> list[dict[str, Any]]: + output: list[dict[str, Any]] = [] + with Path(path).open(encoding="utf-8") as handle: + for line_number, line in enumerate(handle, 1): + if not line.strip(): + continue + try: + value = json.loads(line) + except json.JSONDecodeError as exc: + raise ValueError(f"Invalid JSON at {path}:{line_number}") from exc + if not isinstance(value, dict): + raise ValueError(f"Expected object at {path}:{line_number}") + output.append(value) + return output + + +def write_jsonl_atomic(path: str | Path, rows: Sequence[dict[str, Any]]) -> None: + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + with temporary.open("w", encoding="utf-8") as handle: + for row in rows: + handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n") + temporary.replace(path) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/schema.py b/release-20261107/source/workspace_joint/mira/src/mira/data/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..092890d651d3429d25348910e6d0f46dd1bb9c0a --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/schema.py @@ -0,0 +1,90 @@ +"""Typed schema for the Rocket League WebDataset index (`index.json`). + +One WebDataset **sample = one (match, chunk)**: a ~4 s window of a match bundling all perspectives — +members `p{i}.mp4` / `p{i}.jsonl` per perspective (ordered by `player_id`) + `meta.json`; sample key +`{match_id}_c{chunk:05d}`. A clip is taken from within a single chunk. + +`index.json` holds one `MatchEntry` per match (the random-access map). Unknown fields are allowed so +the schema tolerates extra metadata (e.g. `content_id`). +""" + +from __future__ import annotations + +import json +from pathlib import Path + +from pydantic import BaseModel, ConfigDict, model_validator + + +class Anchor(BaseModel): + model_config = ConfigDict(extra="allow") + event_type: int + event_name: str + master_sec: float + + +class Perspective(BaseModel): + """One player's view of a match. Anchors are on the shared match clock (identical across + perspectives); `recording_offset_sec` places this view's frame 0 on that clock. `frames` / + `duration` are the per-perspective totals across all chunks.""" + + model_config = ConfigDict(extra="allow") + player_id: int + team: int + frames: int + duration: float + recording_offset_sec: float = 0.0 + anchors: list[Anchor] = [] + + +class MatchEntry(BaseModel): + """One match. `chunk_frames` are the frame counts of the ordered chunks (shared across + perspectives, since the POVs are frame-aligned); they sum to each perspective's `frames` and + define the chunk boundaries (each clip stays within one chunk; boundaries also map events). + `perspectives` are ordered by `player_id` (the p0..p3 axis). All of a match's chunk samples + live in `shard`. + + `chunk_indices[c]` is the ORIGINAL source chunk index of the c-th present chunk. A match's + present chunks can be non-contiguous (e.g. `[0,1,3,4,...]`); the sample key for the c-th chunk + is `{match_id}_c{chunk_indices[c]:05d}`, not + `_c{c:05d}`. When absent (contiguous datasets) it defaults to `range(len(chunk_frames))`.""" + + model_config = ConfigDict(extra="allow") + match_id: str + shard: str + n_players: int + chunk_frames: list[int] + chunk_indices: list[int] | None = None + arena: str | None = None + perspectives: list[Perspective] + + @model_validator(mode="after") + def _check_chunk_indices(self) -> "MatchEntry": + """`chunk_indices` must be a per-present-chunk map: one entry per `chunk_frames`, all + distinct. A length mismatch or a duplicate would make `chunk_id` map a chunk to the wrong + original index -- i.e. to the wrong `.mp4`/`.jsonl` member -- producing silently corrupt + samples, so it is rejected at parse time rather than surfacing as bad data downstream.""" + if self.chunk_indices is not None: + if len(self.chunk_indices) != len(self.chunk_frames): + raise ValueError( + f"{self.match_id}: chunk_indices has {len(self.chunk_indices)} entries but " + f"chunk_frames has {len(self.chunk_frames)}" + ) + if len(set(self.chunk_indices)) != len(self.chunk_indices): + raise ValueError(f"{self.match_id}: chunk_indices has duplicate entries") + return self + + def chunk_id(self, position: int) -> int: + """Original source chunk index of the `position`-th present chunk (for the sample key).""" + return self.chunk_indices[position] if self.chunk_indices is not None else position + + +class Index(BaseModel): + model_config = ConfigDict(extra="allow") + total_samples: int # number of matches (each match expands to len(chunk_frames) chunk samples) + entries: list[MatchEntry] + + @classmethod + def load(cls, index_path: str | Path) -> "Index": + with open(index_path, encoding="utf-8") as f: + return cls.model_validate(json.load(f)) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/state.py b/release-20261107/source/workspace_joint/mira/src/mira/data/state.py new file mode 100644 index 0000000000000000000000000000000000000000..e3890bb945f9c357349531e29adbae3cbdd5389a --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/state.py @@ -0,0 +1,92 @@ +"""Typed structure of the per-frame physics / game state attached to a clip. + +A clip's ``physics`` is ``list[list[FrameState]]`` — one list per selected perspective, each a +per-frame state frame-aligned 1:1 with the clip's frames / actions along the T axis. The runtime +objects are plain JSON dicts decoded from a chunk's physics track; these :class:`typing.TypedDict` +definitions document and type that structure without changing it, so there is no per-frame parsing +cost and dict access is unchanged. + +Coordinate system (standard Rocket League arena, Unreal units): x in ~[-4096, 4096] (side walls), +y in ~[-5120, 5120] (the goal-to-goal long axis), z in ~[0, 2044] (floor to ceiling). +""" + +from __future__ import annotations + +from typing import TypedDict + + +class Vec3(TypedDict): + """A 3D vector (location, velocity, or angular velocity) in Unreal units.""" + + x: float + y: float + z: float + + +class Quat(TypedDict): + """An orientation quaternion.""" + + x: float + y: float + z: float + w: float + + +class GameInfo(TypedDict): + """Match-wide state for one frame. + + ``time_remaining`` (regulation countdown, seconds) is populated **only on the local + perspective** — the recording player's own POV — and is ``0.0`` on the other three. Read it + from the ``is_local`` perspective (see ``perspective_has_clock``). It counts down from ~300 to + 0 and holds steady during replays/kickoffs. ``score_*`` and ``is_overtime`` are correct on + every perspective. + """ + + time_remaining: float # local-perspective-only; 0.0 on the others (see class docstring) + score_blue: int + score_orange: int + is_overtime: bool + + +class BallState(TypedDict): + location: Vec3 + velocity: Vec3 + rotation: Quat + angular_velocity: Vec3 + + +class _CarStateRequired(TypedDict): + player_id: int + team: int + location: Vec3 + velocity: Vec3 + attacker_player_id: int # the demolisher's player_id, -1 when none + + +class CarState(_CarStateRequired, total=False): + """One car in one frame. + + ``player_id``, ``team``, ``location``, ``velocity``, and ``attacker_player_id`` are always + present; the remaining fields are optional. Demolitions are not flagged by a boolean (the + source export never sets one) — a car being demolished is indicated by ``attacker_player_id`` + (the demolisher's player_id; ``-1`` otherwise). + """ + + is_local: bool + rotation: Quat + angular_velocity: Vec3 + boost_amount: float + is_on_ground: bool + is_supersonic: bool + + +class FrameState(TypedDict): + """One frame of game state: match clock/score, the ball, and all cars. + + All perspectives observe the same world state; it is kept per-perspective so it stays + frame-aligned with that perspective's frames and actions. + """ + + game: GameInfo + ball: BallState + cars: list[CarState] diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/training_loader.py b/release-20261107/source/workspace_joint/mira/src/mira/data/training_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..bff21b9496e9d759ffe90a657924278535d66b43 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/training_loader.py @@ -0,0 +1,333 @@ +"""A PyTorch ``DataLoader`` over the Rocket League dataset, yielding model-ready batches. + +This adapts :meth:`mira.data.RocketScienceDataset.iter_clips` (the streaming read path) into +the ``(VideoActionBatch, list[ClipMeta])`` batches the codec and world model consume. It does not +re-implement any reading, decoding, or action parsing — those live in :mod:`mira.data`. + +Multiplayer: ``iter_clips(perspective="all")`` yields one clip per ``(match, chunk)`` carrying all +``P`` perspectives as ``(P, T, C, H, W)``, ordered by ``player_id``. The perspectives are flattened +into the batch dimension. With ``n_players > 1`` the ``n_players`` perspectives of a match are kept +**contiguous and player_id-ordered** so a downstream wrapper can ``rearrange("(b p) ... -> b p ...")``; +with ``n_players == 1`` each perspective is an independent row. The loader's ``batch_size`` is +therefore multiplied by ``n_players`` so a batch holds ``batch_size`` whole groups. +""" + +from __future__ import annotations + +import copy +import random +from collections.abc import Iterator +from dataclasses import dataclass +from itertools import count +from pathlib import Path +from typing import Any + +import torch +from torch.utils.data import DataLoader, IterableDataset, get_worker_info + +from mira.world_model.actions_config import ActionConfig, ActionTensors, stack_action_tensors + +from .actions import DEFAULT_RL_KEYS, KeyVocab +from .batch import VideoActionBatch +from .dataset import RocketScienceDataset + + +@dataclass +class ClipMeta: + """Per-row provenance for one perspective of one clip (not read by the models). + + Attributes: + match_id: The match this clip belongs to. + perspective: Index of this perspective within the match's player_id-ordered perspectives. + player_id: The player_id of this perspective. + clip_id: Per-match running clip index (shared across the match's perspectives). + chunk_idx: Position of the source chunk this clip was taken from. + frame_indices: Chunk-local source-frame indices of the clip's steps. + """ + + match_id: str + perspective: int + player_id: int + clip_id: int + chunk_idx: int + frame_indices: list[int] + + +def _rank_and_world_size() -> tuple[int, int]: + """Distributed (rank, world_size), or (0, 1) when not running under ``torch.distributed``.""" + if torch.distributed.is_available() and torch.distributed.is_initialized(): + return torch.distributed.get_rank(), torch.distributed.get_world_size() + return 0, 1 + + +class _VideoActionIterable(IterableDataset): + """Streams per-perspective ``{"video", "actions", "metadata"}`` samples from the dataset. + + Sharding mirrors the source loader: shards are split across distributed ranks and then across + DataLoader workers, so each ``(rank, worker)`` reads a disjoint set of shards. A group-level + shuffle buffer mixes whole ``n_players`` groups while keeping each group's perspectives + contiguous. With ``infinite=True`` the stream loops forever (re-shuffling shard order each epoch). + """ + + def __init__( + self, + index_path: str | Path, + action_config: ActionConfig, + *, + clip_len: int, + target_fps: int, + n_players: int, + exclude_replays: bool, + frame_size: tuple[int, int] | None, + shuffle: bool, + infinite: bool, + shuffle_buffer_size: int, + seed: int, + action_fps: int | None = None, + ): + if n_players < 1: + raise ValueError(f"n_players must be >= 1, got {n_players}") + self.index_path = Path(index_path) + self.action_config = action_config + self.vocab = KeyVocab(tuple(action_config.valid_keys)) + self.clip_len = clip_len + self.target_fps = target_fps + self.action_fps = action_fps + self.n_players = n_players + self.exclude_replays = exclude_replays + self.frame_size = frame_size + self.shuffle = shuffle + self.infinite = infinite + self.shuffle_buffer_size = shuffle_buffer_size + self.seed = seed + + def _my_shards(self, dataset: RocketScienceDataset) -> list[str]: + """The shards this (rank, worker) is responsible for, split rank-first then worker-second.""" + rank, world_size = _rank_and_world_size() + info = get_worker_info() + worker_id, num_workers = (info.id, info.num_workers) if info is not None else (0, 1) + + all_shards = sorted({e.shard for e in dataset.index.entries}) + return all_shards[rank::world_size][worker_id::num_workers] + + def _plan_perspective(self, clip, p: int) -> dict[str, Any]: + """A lightweight buffered element for one perspective: an undecoded-clip reference plus the + perspective index. No pixels — decoding is deferred to ``_decode_sample`` at the yield point.""" + return {"clip": clip, "p": p} + + def _decode_sample(self, plan: dict[str, Any]) -> dict[str, Any]: + """Decode one buffered plan into a model-ready per-perspective sample (drops the clip ref).""" + clip, p = plan["clip"], plan["p"] + + actions = ActionTensors(config=self.action_config, batch_size=1) + actions.key_presses = clip.actions[p].unsqueeze(0).to(torch.int32) # (1, T, n_keys) + n_steps = actions.key_presses.shape[1] + actions.mouse_movements = torch.zeros((1, n_steps, 2), dtype=torch.float32) + # Keyboard-only data has no mouse sensitivity; NaN is the encoder's "unknown" signal. + actions.game_mouse_sensitivity = torch.full((1,), float("nan"), dtype=torch.float32) + + return { + "video": clip.decode_perspective(p, self.frame_size), # (T, C, H, W) uint8 + "actions": actions, + "metadata": ClipMeta( + match_id=clip.match_id, + perspective=p, + player_id=clip.player_ids[p], + clip_id=clip.clip_id, + chunk_idx=clip.chunk_idx, + frame_indices=list(clip.frame_indices), + ), + } + + def _shard_view(self, dataset: RocketScienceDataset, shard: str) -> RocketScienceDataset: + """A shard-scoped view of ``dataset``: same loaded match data, index restricted to one shard. + + ``iter_clips`` derives the shards it streams from ``index.entries``; the per-shard reading + uses ``matches``/``_chunk_pos``. The view is a shallow copy whose ``index`` carries only this + shard's entries, so the shared dataset (and its fully populated ``matches``) is left intact. + """ + view = copy.copy(dataset) + view.index = dataset.index.model_copy(update={"entries": self._entries_by_shard[shard]}) + return view + + def _groups(self, dataset: RocketScienceDataset, shard: str) -> Iterator[list[dict[str, Any]]]: + """Yield groups of ``n_players`` contiguous per-perspective samples from one shard's clips.""" + dataset = self._shard_view(dataset, shard) + for clip in dataset.iter_clips( + clip_len=self.clip_len, + target_fps=self.target_fps, + exclude_replays=self.exclude_replays, + decode=False, + perspective="all", + frame_size=self.frame_size, + seed=self.seed, + action_fps=self.action_fps, + carry_video=True, + ): + assert clip.video_bytes is not None, "iter_clips must carry video for the training loader" + p_data = len(clip.perspectives) + if p_data % self.n_players != 0: + raise ValueError( + f"clip has {p_data} perspectives, not divisible by n_players={self.n_players}" + ) + for g in range(0, p_data, self.n_players): + yield [self._plan_perspective(clip, p) for p in range(g, g + self.n_players)] + + def __iter__(self) -> Iterator[dict[str, Any]]: + rank, _ = _rank_and_world_size() + info = get_worker_info() + worker_id = info.id if info is not None else 0 + + dataset = RocketScienceDataset.from_local(self.index_path, vocab=self.vocab) + # Group entries by shard once so a single shard can be streamed at a time (for shard-order + # shuffling); _shard_view scopes iter_clips to one shard's entries. + self._entries_by_shard: dict[str, list] = {} + for e in dataset.index.entries: + self._entries_by_shard.setdefault(e.shard, []).append(e) + + my_shards = self._my_shards(dataset) + if not my_shards: + return # this (rank, worker) has no shards; finish cleanly rather than hang + + rng = random.Random(self.seed + rank * 1024 + worker_id) + buffer: list[list[dict[str, Any]]] = [] + + def drained(group: list[dict[str, Any]]) -> Iterator[dict[str, Any]]: + # Decode a group's perspectives here, on the yield path, so decode stays parallelized + # across workers; emit them contiguously so the DataLoader batches them together. + for plan in group: + yield self._decode_sample(plan) + + for _epoch in count() if self.infinite else range(1): + shard_order = list(my_shards) + if self.shuffle: + rng.shuffle(shard_order) + for shard in shard_order: + for group in self._groups(dataset, shard): + if not self.shuffle: + yield from drained(group) + continue + buffer.append(group) + if len(buffer) >= self.shuffle_buffer_size: + yield from drained(buffer.pop(rng.randrange(len(buffer)))) + + if self.shuffle: # drain whatever remains (only reached when not infinite) + rng.shuffle(buffer) + for group in buffer: + yield from drained(group) + + +def _collate(samples: list[dict[str, Any]]) -> tuple[VideoActionBatch, list[ClipMeta]]: + """Stack per-perspective samples into one ``VideoActionBatch`` plus its per-row metadata.""" + video = torch.stack([s["video"] for s in samples], dim=0) # (B, T, C, H, W) uint8 + actions = stack_action_tensors([s["actions"] for s in samples]) + metadata = [s["metadata"] for s in samples] + return VideoActionBatch(video=video, actions=actions), metadata + + +def create_loader( + index_path: str | Path, + *, + clip_len: int = 16, + target_fps: int = 10, + n_players: int = 1, + batch_size: int = 4, + num_workers: int = 0, + shuffle: bool = True, + infinite: bool = True, + shuffle_buffer_size: int = 100, + seed: int = 2025, + exclude_replays: bool = False, + frame_size: tuple[int, int] | None = None, + valid_keys: list[str] | None = None, + source_fps: int = 20, + action_fps: int | None = None, + action_config: ActionConfig | None = None, + prefetch_factor: int = 2, + pin_memory: bool | None = None, +) -> DataLoader: + """Build a ``DataLoader`` yielding ``(VideoActionBatch, list[ClipMeta])`` from a dataset index. + + The train/val split is selected by which index is passed (the dataset ships separate ``train/`` + and ``test/`` indices via ``from_hub(split=...)`` / ``from_local(dir)``); there is no random + split here. Set ``exclude_replays=True`` for evaluation. + + Args: + index_path: Path to a dataset directory or its ``index.json``. + clip_len: Number of time steps per clip. + target_fps: Frame rate the clips (and actions) are downsampled to. + n_players: Perspectives grouped contiguously per row-block. ``1`` treats every perspective + as an independent row; ``>1`` keeps that many perspectives of a match contiguous. + batch_size: Number of groups per batch; the loader uses ``batch_size * n_players`` rows. + num_workers: DataLoader worker processes. + shuffle: Shuffle shard order and groups (via a group-level shuffle buffer). + infinite: Loop the stream forever (typical for training). + shuffle_buffer_size: Number of groups buffered before one is emitted at random. + seed: Base RNG seed (offset per rank/worker). + exclude_replays: Drop clips overlapping a goal-replay span. + frame_size: Optional ``(H, W)`` to resize decoded frames to (native size if ``None``). + valid_keys: Key vocabulary; defaults to ``DEFAULT_RL_KEYS``. Ignored if ``action_config`` is + given. + source_fps: Nominal recording fps stored in the built ``ActionConfig`` (RL recordings are + ~20fps). This is metadata only: the authoritative action downsampling is done inside the + dataset using each match's measured fps, so the per-match factor may differ. Ignored if + ``action_config`` is given. + action_fps: Action sample rate, decoupled from the frame ``target_fps``. ``None`` (default) + keeps one action step per frame, the released default. When set to a multiple of + ``target_fps`` (e.g. ``2 * target_fps``) each clip yields ``action_fps // target_fps`` + action steps per video frame, so ``key_presses`` has ``action_fps // target_fps × T`` + steps. The built ``ActionConfig.target_fps`` follows ``action_fps`` so the stored action + rate matches the emitted steps. + action_config: Explicit ``ActionConfig``; built from ``valid_keys`` + fps when ``None``. + prefetch_factor: Per-worker prefetch (only used when ``num_workers > 0``). + pin_memory: Pin host memory; defaults to whether CUDA is available. + + Returns: + A ``DataLoader`` over the dataset. + """ + if action_config is None: + action_config = ActionConfig( + valid_keys=list(valid_keys) if valid_keys is not None else list(DEFAULT_RL_KEYS), + source_fps=source_fps, + # The stored action rate follows action_fps when decoupled, else the frame rate. + target_fps=action_fps if action_fps is not None else target_fps, + ) + + # Fail loudly up front if no clip in the dataset can satisfy `clip_len`: otherwise every match is + # skipped as "too long for its chunks" and, with `infinite=True`, the stream loops over an empty + # epoch forever (a silent hang). Some-but-not-all fitting is fine -- the short matches are skipped + # while streaming. This reads only index metadata (no video), so it is cheap to check once here. + probe = RocketScienceDataset.from_local(index_path, vocab=KeyVocab(tuple(action_config.valid_keys))) + longest = probe.max_clip_frames(target_fps) + if clip_len > longest: + raise ValueError( + f"Requested clip_len={clip_len} @ {target_fps}fps but the longest clip that fits any " + f"chunk in {index_path} is {longest} frames. Lower clip_len (for the world-model eval: " + f"world_model_metrics.num_unrolled_frames / n_context_frames) or use longer-chunked data." + ) + + dataset = _VideoActionIterable( + index_path, + action_config, + clip_len=clip_len, + target_fps=target_fps, + n_players=n_players, + exclude_replays=exclude_replays, + frame_size=frame_size, + shuffle=shuffle, + infinite=infinite, + shuffle_buffer_size=shuffle_buffer_size, + seed=seed, + action_fps=action_fps, + ) + + return DataLoader( + dataset, + # A batch holds the n_players aligned perspectives of `batch_size` groups, concatenated along + # the batch dim; a downstream wrapper chunks them back apart. + batch_size=batch_size * n_players, + num_workers=num_workers, + prefetch_factor=prefetch_factor if num_workers > 0 else None, + pin_memory=torch.cuda.is_available() if pin_memory is None else pin_memory, + collate_fn=_collate, + ) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/viz.py b/release-20261107/source/workspace_joint/mira/src/mira/data/viz.py new file mode 100644 index 0000000000000000000000000000000000000000..56d4eec79fd11d72cbba52d41ab38f14f4305652 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/viz.py @@ -0,0 +1,719 @@ +"""Rendering helpers for inspecting Rocket League clips — frames, key presses, and events. + +The primary renderer is :func:`clip_grid_video`: it tiles every perspective of a clip into a single, +frame-synchronised MP4 with a live on-frame keyboard overlay and team-coloured framing. All +perspectives share one video, so playback is in lockstep. + +Pure functions; frames/actions may be torch tensors or numpy. Needs numpy + matplotlib + pillow +(the ``viz`` extra). Video encoding shells out to ``ffmpeg`` (provided by the ``pixi`` env). +""" + +from __future__ import annotations + +import functools +from typing import TYPE_CHECKING + +import numpy as np + +from .actions import DEFAULT_RL_KEYS + +if TYPE_CHECKING: + from PIL import ImageDraw, ImageFont + + from .state import FrameState + +# --- palette ------------------------------------------------------------------------------------ + +_BG = (13, 14, 18) # canvas behind tiles +_TEAM_COLORS = {0: (56, 135, 255), 1: (255, 146, 41)} # Rocket League blue / orange +_ACCENT = (60, 222, 152) # lit key +_KEY_IDLE = (255, 255, 255, 30) +_KEY_IDLE_EDGE = (255, 255, 255, 70) + +# 9-key cluster, laid out QWE / ASD / Shift-Space-Ctrl. +_KB_POS = { + "Q": (0, 0), "W": (0, 1), "E": (0, 2), + "A": (1, 0), "S": (1, 1), "D": (1, 2), + "LShiftKey": (2, 0), "Space": (2, 1), "LControlKey": (2, 2), +} # fmt: skip +_KB_LABEL = { + "Q": "Q", "W": "W", "E": "E", "A": "A", "S": "S", "D": "D", + "LShiftKey": "SHIFT", "Space": "SPACE", "LControlKey": "CTRL", +} # fmt: skip + + +# --- small utilities ---------------------------------------------------------------------------- + + +def _to_numpy(x) -> np.ndarray: + return x.detach().cpu().numpy() if hasattr(x, "detach") else np.asarray(x) + + +@functools.lru_cache(maxsize=64) +def _font(size: int, bold: bool = True) -> "ImageFont.FreeTypeFont": + """A crisp TrueType font (DejaVu Sans, bundled with matplotlib), cached by size/weight.""" + import matplotlib.font_manager as fm + from PIL import ImageFont + + path = fm.findfont(fm.FontProperties(family="DejaVu Sans", weight="bold" if bold else "normal")) + return ImageFont.truetype(path, size) + + +def _fit_font(draw: "ImageDraw.ImageDraw", text: str, max_w: float, max_h: float) -> "ImageFont.FreeTypeFont": + """Largest bold font for which `text` fits within (max_w, max_h).""" + for size in range(int(max_h), 6, -1): + if draw.textlength(text, font=_font(size)) <= max_w: + return _font(size) + return _font(7) + + +def _resize_even(img: np.ndarray, max_w: int) -> np.ndarray: + """Downscale (preserving aspect) to <= max_w and force even dims (libx264 needs even W,H).""" + from PIL import Image + + h, w = img.shape[:2] + nw, nh = (max_w, round(h * max_w / w)) if w > max_w else (w, h) + nw, nh = nw - nw % 2, nh - nh % 2 + if (nw, nh) != (w, h): + img = np.asarray(Image.fromarray(np.ascontiguousarray(img)).resize((nw, nh))) + return img + + +# --- on-frame overlay --------------------------------------------------------------------------- + + +def _draw_key(draw: "ImageDraw.ImageDraw", box: tuple[int, int, int, int], label: str, lit: bool) -> None: + x0, y0, x1, y1 = box + radius = max(3, (y1 - y0) // 5) + if lit: + draw.rounded_rectangle(box, radius, fill=(*_ACCENT, 240), outline=(255, 255, 255, 150), width=2) + text_color = (8, 16, 12, 255) + else: + draw.rounded_rectangle(box, radius, fill=_KEY_IDLE, outline=_KEY_IDLE_EDGE, width=1) + text_color = (228, 230, 236, 210) + font = _fit_font(draw, label, (x1 - x0) * 0.82, (y1 - y0) * 0.62) + tw = draw.textlength(label, font=font) + ascent, descent = font.getmetrics() + draw.text( + (x0 + (x1 - x0 - tw) / 2, y0 + (y1 - y0 - ascent - descent) / 2), label, font=font, fill=text_color + ) + + +def _draw_keyboard(draw: "ImageDraw.ImageDraw", x: int, y: int, unit: int, pressed: set[str]) -> None: + """Draw the 3×3 key cluster with its top-left at (x, y); lit keys filled with the accent colour.""" + gap = max(2, unit // 7) + pad = gap + 1 + extent = 3 * unit + 2 * gap + draw.rounded_rectangle( + [x - pad, y - pad, x + extent + pad, y + extent + pad], radius=unit // 3, fill=(12, 14, 20, 150) + ) + for key, (r, c) in _KB_POS.items(): + bx, by = x + c * (unit + gap), y + r * (unit + gap) + _draw_key(draw, (bx, by, bx + unit, by + unit), _KB_LABEL[key], key in pressed) + + +def _draw_pill( + draw: "ImageDraw.ImageDraw", x: int, y: int, text: str, color: tuple[int, int, int], h: int +) -> None: + font = _font(int(h * 0.6)) + tw = draw.textlength(text, font=font) + padx = int(h * 0.42) + draw.rounded_rectangle([x, y, x + tw + 2 * padx, y + h], radius=h // 2, fill=(*color, 240)) + ascent, descent = font.getmetrics() + draw.text((x + padx, y + (h - ascent - descent) / 2), text, font=font, fill=(255, 255, 255, 255)) + + +def decorate_frame( + img_hwc: np.ndarray, act_vec, *, label: str | None = None, team: int = 0, keys=DEFAULT_RL_KEYS +) -> np.ndarray: + """Composite a live keyboard widget (lit = pressed) and an optional label pill onto one RGB frame.""" + from PIL import Image, ImageDraw + + base = Image.fromarray(np.ascontiguousarray(img_hwc)).convert("RGBA") + overlay = Image.new("RGBA", base.size, (0, 0, 0, 0)) + draw = ImageDraw.Draw(overlay) + w, h = base.size + + pressed = {k for k, v in zip(keys, list(act_vec)) if v} + unit = max(14, int(0.072 * w)) + margin = max(6, int(0.022 * w)) + kb_extent = 3 * unit + 2 * max(2, unit // 7) + _draw_keyboard(draw, margin, h - kb_extent - margin, unit, pressed) + + if label: + _draw_pill(draw, margin, margin, label, _TEAM_COLORS.get(team, (90, 90, 90)), int(0.07 * w)) + + return np.asarray(Image.alpha_composite(base, overlay).convert("RGB")) + + +# --- grid composition + encoding ---------------------------------------------------------------- + + +def _player_display_numbers(teams: list[int]) -> list[int]: + """Per-perspective 1-based display number in team-grouped order (blue team first), so tiles and + the HUD both read P1..P4 with the blue players first.""" + order = sorted(range(len(teams)), key=lambda i: teams[i]) + nums = [0] * len(teams) + for rank, pi in enumerate(order): + nums[pi] = rank + 1 + return nums + + +def _compose_grid_frame( + tiles: list[np.ndarray], teams: list[int], cols: int, gutter: int, border: int +) -> np.ndarray: + """Lay tiles (same HxW) on a dark canvas with gutters and team-coloured borders. Tiles are + grouped by team so blue (team 0) fills the top row(s) and orange (team 1) the bottom.""" + order = sorted(range(len(tiles)), key=lambda i: teams[i]) # stable: blue (0) before orange (1) + tiles = [tiles[i] for i in order] + teams = [teams[i] for i in order] + h, w = tiles[0].shape[:2] # all perspectives share one camera resolution, so tiles[0] sizes them all + rows = -(-len(tiles) // cols) + bh, bw = h + 2 * border, w + 2 * border + canvas = np.full((rows * bh + (rows + 1) * gutter, cols * bw + (cols + 1) * gutter, 3), _BG, np.uint8) + for i, (tile, team) in enumerate(zip(tiles, teams)): + r, c = divmod(i, cols) + y, x = gutter + r * (bh + gutter), gutter + c * (bw + gutter) + canvas[y : y + bh, x : x + bw] = _TEAM_COLORS.get(team, (90, 90, 90)) + canvas[y + border : y + border + h, x + border : x + border + w] = tile + return canvas + + +def _encode_mp4(video_thwc: np.ndarray, fps: int) -> bytes: + """Encode (T,H,W,3) uint8 RGB to MP4 bytes via the system ffmpeg (rawvideo pipe -> libx264).""" + import os + import shutil + import subprocess + import tempfile + + if shutil.which("ffmpeg") is None: + raise RuntimeError( + "The `ffmpeg` binary was not found on PATH, but video encoding requires it. " + "Install ffmpeg (e.g. via your system package manager or conda) and ensure it is on PATH." + ) + + v = np.ascontiguousarray(video_thwc, dtype=np.uint8) + _, h, w, _ = v.shape + with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as f: + path = f.name + try: + cmd = [ + "ffmpeg", "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", + "-s", f"{w}x{h}", "-r", str(fps), "-i", "-", "-c:v", "libx264", "-crf", "20", + "-pix_fmt", "yuv420p", "-movflags", "+faststart", path, + ] # fmt: skip + proc = subprocess.run(cmd, input=v.tobytes(), capture_output=True) + if proc.returncode != 0: + raise RuntimeError(f"ffmpeg failed: {proc.stderr.decode()[-1500:]}") + with open(path, "rb") as fh: + return fh.read() + finally: + os.remove(path) + + +def clip_grid_video( + clip, + *, + fps: int | None = None, + keyboard: bool = True, + cols: int = 2, + max_tile_w: int = 460, + gutter: int = 8, + border: int = 3, +) -> bytes: + """Render a clip's perspectives as one frame-synced grid MP4 (bytes), ready to embed. + + Tiles are grouped by team (blue on top, orange on the bottom), framed in their team colour, and + (by default) carry a live keyboard overlay. Single-perspective clips render as a single framed tile. + """ + if clip.frames is None: + raise ValueError("clip has no frames; load it with decode=True") + frames = np.transpose(_to_numpy(clip.frames), (0, 1, 3, 4, 2)) # P,T,H,W,C + acts = _to_numpy(clip.actions) # P,T,K + p, t = frames.shape[0], frames.shape[1] + fps = int(fps or clip.target_fps) + cols = min(cols, p) + pnums = _player_display_numbers(list(clip.teams)) + + decorated = np.empty((p,) + (t,) + _resize_even(frames[0, 0], max_tile_w).shape, np.uint8) + for pi in range(p): + label = f"P{pnums[pi]}" + for ti in range(t): + tile = _resize_even(frames[pi, ti], max_tile_w) + decorated[pi, ti] = ( + decorate_frame(tile, acts[pi, ti], label=label, team=clip.teams[pi]) if keyboard else tile + ) + + video = np.stack( + [_compose_grid_frame(list(decorated[:, ti]), clip.teams, cols, gutter, border) for ti in range(t)] + ) + return _encode_mp4(video, fps) + + +# --- physics minimap (top-down arena radar) ----------------------------------------------------- +# +# The physics view is a top-down radar: ball + 4 cars +# as dots on the arena floor, team-coloured, with a short velocity arrow and a boost ring. Rendered +# per physics frame and animated in lockstep with the clip video. World +# coords -> image: x spans the side walls (left/right), y the goal-to-goal axis (we draw +y up so +# blue's goal sits at the bottom), z is dropped (top-down). See mira.data.physics for the ranges. + +_MINIMAP_BG = (18, 20, 26) +_FIELD_FILL = (28, 32, 42) +_FIELD_LINE = (70, 78, 96) +_BALL_COLOR = (236, 238, 244) + + +def _world_to_img(x: float, y: float, w: int, h: int, pad: int) -> tuple[float, float]: + """Map an arena (x, y) in uu to pixel (col, row). y is drawn upward; x rightward.""" + from .physics import FIELD_X, FIELD_Y + + fx = (x + FIELD_X) / (2 * FIELD_X) # 0..1 left->right + fy = (y + FIELD_Y) / (2 * FIELD_Y) # 0..1 bottom->top + col = pad + fx * (w - 2 * pad) + row = pad + (1 - fy) * (h - 2 * pad) # invert: +y is up on screen + return col, row + + +def _draw_field(draw: "ImageDraw.ImageDraw", w: int, h: int, pad: int) -> None: + """Pitch outline, halfway line, centre circle, and the two goal mouths.""" + from .physics import FIELD_X, FIELD_Y + + x0, y0 = _world_to_img(-FIELD_X, -FIELD_Y, w, h, pad) # bottom-left corner (screen) + x1, y1 = _world_to_img(FIELD_X, FIELD_Y, w, h, pad) # top-right corner (screen) + draw.rectangle([x0, y1, x1, y0], fill=_FIELD_FILL, outline=_FIELD_LINE, width=2) + # halfway line + ml, mr = _world_to_img(-FIELD_X, 0, w, h, pad), _world_to_img(FIELD_X, 0, w, h, pad) + draw.line([ml, mr], fill=_FIELD_LINE, width=1) + # centre circle + cx, cy = _world_to_img(0, 0, w, h, pad) + r = 0.10 * (x1 - x0) + draw.ellipse([cx - r, cy - r, cx + r, cy + r], outline=_FIELD_LINE, width=1) + # goal mouths (goal is ~1786 uu wide, centred on x=0, at y = +/- 5120) + gw = 893.0 + for team, gy in ((0, -5120.0), (1, 5120.0)): + gl, _ = _world_to_img(-gw, gy, w, h, pad) + gr, gyr = _world_to_img(gw, gy, w, h, pad) + draw.line([(gl, gyr), (gr, gyr)], fill=(*_TEAM_COLORS[team], 255), width=4) + + +def _draw_dot( + draw: "ImageDraw.ImageDraw", cx: float, cy: float, r: float, fill, outline=None, width: int = 1 +) -> None: + draw.ellipse([cx - r, cy - r, cx + r, cy + r], fill=fill, outline=outline, width=width) + + +def minimap_frame(physics_frame: "FrameState", *, size: int = 420, vel_arrows: bool = True) -> np.ndarray: + """Render one physics frame as a top-down arena radar (RGB uint8, HxWx3). + + Ball is white; cars are their team colour; the local car gets a white ring. Optional short + velocity arrows hint at heading/speed. Pure given the frame dict (numpy/pillow only).""" + from PIL import Image, ImageDraw + + from .physics import FIELD_X, FIELD_Y, local_car + + w = size + h = round(size * (2 * FIELD_Y) / (2 * FIELD_X)) # keep arena aspect (taller than wide) + pad = max(8, size // 24) + img = Image.new("RGB", (w, h), _MINIMAP_BG) + draw = ImageDraw.Draw(img, "RGBA") + _draw_field(draw, w, h, pad) + + vel_scale = (w - 2 * pad) / (2 * FIELD_X) * 0.45 # uu/s -> px + + def _arrow(px: float, py: float, vx: float, vy: float, color) -> None: + ex, ey = px + vx * vel_scale, py - vy * vel_scale # +y up on screen + draw.line([(px, py), (ex, ey)], fill=(*color, 220), width=2) + + # ball — dot radius grows with height (z), plus a tiny vertical z-bar that gauges aerial height. + from .physics import FIELD_Z + + bx, by, bz = (physics_frame["ball"]["location"][k] for k in ("x", "y", "z")) + pbx, pby = _world_to_img(bx, by, w, h, pad) + if vel_arrows: + bv = physics_frame["ball"]["velocity"] + _arrow(pbx, pby, bv["x"], bv["y"], _BALL_COLOR) + z_frac = max(0.0, min(1.0, bz / FIELD_Z)) + base_r = max(4, size // 70) + _draw_dot(draw, pbx, pby, base_r * (1 + z_frac), _BALL_COLOR, outline=(0, 0, 0, 180), width=1) + # z-bar: a short gauge just right of the ball; fill height tracks z. + zbx = pbx + base_r * 2.4 + zb_h = max(10, size // 12) + zb_top, zb_bot = pby - zb_h / 2, pby + zb_h / 2 + draw.line([(zbx, zb_top), (zbx, zb_bot)], fill=(*_FIELD_LINE, 200), width=2) + draw.line([(zbx, zb_bot), (zbx, zb_bot - z_frac * zb_h)], fill=(*_BALL_COLOR, 230), width=3) + + local_id = local_car(physics_frame)["player_id"] + for car in physics_frame["cars"]: + loc = car["location"] + px, py = _world_to_img(loc["x"], loc["y"], w, h, pad) + color = _TEAM_COLORS.get(car["team"], (140, 140, 140)) + if car.get("attacker_player_id", -1) != -1: # -> demolished + color = (90, 90, 96) + if vel_arrows: + cv = car["velocity"] + _arrow(px, py, cv["x"], cv["y"], color) + r = max(5, size // 56) + is_local = car["player_id"] == local_id + outline = (255, 255, 255, 255) if is_local else (0, 0, 0, 160) + _draw_dot(draw, px, py, r, (*color, 255), outline=outline, width=3 if is_local else 1) + if car.get("is_supersonic"): # speed flames -> thin bright ring + _draw_dot(draw, px, py, r + 3, None, outline=(255, 255, 255, 200), width=1) + return np.asarray(img) + + +def minimap_video(clip, *, perspective: int = 0, fps: int | None = None, size: int = 420) -> bytes: + """Animate the arena radar across a clip, one frame per physics step (MP4 bytes). + + Plays in lockstep with the clip's grid video. Uses one perspective's physics — all perspectives + share the world state.""" + if clip.physics is None: + raise ValueError("clip has no physics; load a dataset that carries physics") + frames = [minimap_frame(fr, size=size) for fr in clip.physics[perspective]] + fps = int(fps or clip.target_fps) + return _encode_mp4(np.stack([_resize_even(f, size) for f in frames]), fps) + + +# --- live HUD + combined grid|radar video ------------------------------------------------------- +# +# A compact HUD (score, clock, per-car boost bars + flags) baked into the radar panel so it +# animates frame-by-frame, and a single composited [grid | radar+HUD] video so the gameplay tiles +# and the physics view are locked together in one mp4. + +_HUD_BG = (12, 14, 20) +_HUD_TEXT = (228, 230, 236) +_HUD_MUTED = (150, 156, 170) +_BOOST_COLOR = (255, 209, 102) # amber boost fill +_BOOST_TRACK = (44, 48, 60) + + +def _draw_boost_bar(draw: "ImageDraw.ImageDraw", box: tuple[int, int, int, int], frac: float, color) -> None: + """A rounded 0..1 boost gauge filling left-to-right (`frac` is the boost_amount, already 0..1).""" + x0, y0, x1, y1 = box + r = (y1 - y0) // 2 + draw.rounded_rectangle(box, r, fill=_BOOST_TRACK) + fw = max(0.0, min(1.0, frac)) * (x1 - x0) + if fw >= 2 * r: # only draw a fill wide enough to round cleanly + draw.rounded_rectangle([x0, y0, x0 + fw, y1], r, fill=(*color, 255)) + + +def _draw_hud( + draw: "ImageDraw.ImageDraw", + x: int, + y: int, + w: int, + h: int, + frame: "FrameState", + has_clock: bool, + player_labels: dict[int, str] | None = None, +) -> None: + """Bake a live game-state HUD into the rectangle (x, y, w, h): a score/clock header line, then + one row per car with a team dot, label, a boost bar, and flag glyphs. With ``player_labels`` + (player_id -> "P1".."P4") the rows are ordered and labelled by it; otherwise rows use the raw + player id and mark the local car with ``<``.""" + from .physics import local_car + + g = frame["game"] + cars = frame["cars"] + if player_labels is not None: + cars = sorted(cars, key=lambda c: player_labels.get(c["player_id"], f"P{c['player_id']}")) + local_id = local_car(frame)["player_id"] + known_ids = {c["player_id"] for c in cars} + + line_h = max(14, h // (len(cars) + 2)) + pad = max(4, line_h // 4) + + # Header: score + clock (+ overtime). + tr = g.get("time_remaining", 0.0) + clock = f"{int(tr) // 60}:{int(tr) % 60:02d}" if has_clock else "—" + head = f"BLUE {g.get('score_blue', 0)} - {g.get('score_orange', 0)} ORANGE {clock}" + if g.get("is_overtime"): + head += " OT" + hf = _font(max(7, int(line_h * 0.62))) + draw.text((x, y), head, font=hf, fill=_HUD_TEXT) + + row_y = y + line_h + pad + label_w = int(w * 0.30) + bar_x0 = x + label_w + bar_x1 = x + int(w * 0.74) + flag_x = bar_x1 + pad * 2 + cf = _font(max(7, int(line_h * 0.55))) + for c in cars: + cy = row_y + line_h // 2 + team_color = _TEAM_COLORS.get(c["team"], (140, 140, 140)) + dot_r = max(3, line_h // 6) + draw.ellipse([x, cy - dot_r, x + 2 * dot_r, cy + dot_r], fill=(*team_color, 255)) + if player_labels is not None: + plabel = player_labels.get(c["player_id"], f"P{c['player_id']}") + else: + plabel = f"P{c['player_id']}" + ("<" if c["player_id"] == local_id else "") + draw.text((x + 3 * dot_r, row_y + line_h * 0.12), plabel, font=cf, fill=_HUD_TEXT) + bh = max(6, int(line_h * 0.42)) + _draw_boost_bar( + draw, (bar_x0, cy - bh // 2, bar_x1, cy + bh // 2), c.get("boost_amount", 0.0), _BOOST_COLOR + ) + flags = "" + if not c.get("is_on_ground", True): + flags += "air " + if c.get("is_supersonic"): + flags += "SS " + atk = c.get("attacker_player_id", -1) + if atk != -1: # -> demolished + if player_labels is not None and atk in player_labels: + flags += f"DEMO by {player_labels[atk]}" + elif atk in known_ids: + flags += f"DEMO by P{atk}" + else: + flags += "DEMO" + draw.text((flag_x, row_y + line_h * 0.12), flags.strip(), font=cf, fill=_HUD_MUTED) + row_y += line_h + + +# Badge colours + pill text by code: LIVE green, KICKOFF amber, the frozen reasons +# orange/violet/grey. The pill text is ASCII (the baked DejaVu font has no ⏸ glyph; the pause is +# drawn as an icon in the frozen note below the pill). +_BADGE_COLOR = { + "LIVE": (60, 222, 152), + "KICKOFF": (255, 209, 102), + "PAUSE": (255, 146, 41), + "REPLAY": (180, 150, 255), + "FROZEN": (150, 156, 170), +} +_BADGE_PILL = { + "LIVE": "● LIVE", + "KICKOFF": "KICKOFF", + "PAUSE": "GOAL PAUSE", + "REPLAY": "REPLAY", + "FROZEN": "FROZEN", +} + + +def _draw_pause_icon(draw: "ImageDraw.ImageDraw", x: float, y: float, h: float, color) -> float: + """Two small bars (a pause glyph) at (x, y); returns the x just past the icon.""" + bw = max(2, h / 5) + gap = bw + draw.rectangle([x, y, x + bw, y + h], fill=(*color, 255)) + draw.rectangle([x + bw + gap, y, x + 2 * bw + gap, y + h], fill=(*color, 255)) + return x + 2 * bw + gap + + +def _draw_badge(draw: "ImageDraw.ImageDraw", x: int, y: int, w: int, badge) -> None: + """Render one step's :class:`physics.Badge` top-left of the radar: a coloured pill with the + phase name, and (when frozen) a pause-icon + 'physics frozen' note on the line below.""" + color = _BADGE_COLOR.get(badge.code, _BADGE_COLOR["LIVE"]) + name = _BADGE_PILL.get(badge.code, "● LIVE") # ASCII-safe pill text + h = max(16, w // 16) + f = _font(max(8, int(h * 0.58))) + tw = draw.textlength(name, font=f) + padx = int(h * 0.4) + draw.rounded_rectangle([x, y, x + tw + 2 * padx, y + h], radius=h // 3, fill=(10, 12, 18, 220)) + asc, desc = f.getmetrics() + draw.text((x + padx, y + (h - asc - desc) / 2), name, font=f, fill=(*color, 255)) + + if badge.frozen: + nf = _font(max(7, int(h * 0.42))) + iy = y + h + 3 + ih = max(7, int(h * 0.42)) + tx = _draw_pause_icon(draw, x + 1, iy, ih, color) + max(3, ih // 2) + draw.text((tx, iy - 1), "physics frozen", font=nf, fill=(*color, 220)) + + +def radar_panel_frame( + physics_frame: "FrameState", + *, + panel_h: int, + has_clock: bool = True, + radar_size: int = 360, + badge=None, + player_labels: dict[int, str] | None = None, +) -> np.ndarray: + """Compose one fixed-height panel: arena radar (with a motion-authoritative phase badge) on top, + live HUD below (RGB uint8, panel_h tall). + + Sized to a target height so it can sit flush beside a gameplay grid in a combined frame. `badge` + is a :class:`physics.Badge` (defaults to a plain ``● LIVE`` badge when omitted).""" + from PIL import Image, ImageDraw + + from .physics import Badge + + if badge is None: + badge = Badge("LIVE", "● LIVE", False) + radar = minimap_frame(physics_frame, size=radar_size) + rh, rw = radar.shape[:2] + max_radar_h = panel_h - panel_h // 4 # reserve the lower quarter for the HUD + if rh > max_radar_h: # scale the radar down (preserve aspect) so the HUD always fits + new_w = max(2, round(rw * max_radar_h / rh)) + radar = np.asarray(Image.fromarray(np.ascontiguousarray(radar)).resize((new_w, max_radar_h))) + rh, rw = radar.shape[:2] + + panel = Image.new("RGB", (rw, panel_h), _HUD_BG) + panel.paste(Image.fromarray(np.ascontiguousarray(radar)), (0, 0)) + draw = ImageDraw.Draw(panel, "RGBA") + _draw_badge(draw, max(4, rw // 40), max(4, rh // 40), rw, badge) + hud_y = rh + max(6, panel_h // 60) + _draw_hud( + draw, + max(4, rw // 40), + hud_y, + rw - max(8, rw // 20), + panel_h - hud_y - 4, + physics_frame, + has_clock, + player_labels, + ) + return np.asarray(panel) + + +def clip_grid_with_radar_video( + clip, + *, + perspective: int = 0, + fps: int | None = None, + keyboard: bool = True, + cols: int = 2, + max_tile_w: int = 420, + gutter: int = 8, + border: int = 3, + radar_size: int = 380, +) -> bytes: + """One locked MP4 per clip: each frame is [ 4-POV gameplay grid | arena radar + live HUD ]. + + The gameplay tiles, radar, and HUD share a single video and stay in sync.""" + if clip.frames is None: + raise ValueError("clip has no frames; load it with decode=True") + if clip.physics is None: + raise ValueError("clip has no physics; load a dataset that carries physics") + from .physics import perspective_has_clock, step_badges + + frames = np.transpose(_to_numpy(clip.frames), (0, 1, 3, 4, 2)) # P,T,H,W,C + acts = _to_numpy(clip.actions) + p, t = frames.shape[0], frames.shape[1] + fps = int(fps or clip.target_fps) + cols = min(cols, p) + has_clock = perspective_has_clock(clip.physics[perspective]) + badges = step_badges(clip, perspective) + pnums = _player_display_numbers(list(clip.teams)) + player_labels = {clip.player_ids[pi]: f"P{pnums[pi]}" for pi in range(p)} + + decorated = np.empty((p,) + (t,) + _resize_even(frames[0, 0], max_tile_w).shape, np.uint8) + for pi in range(p): + label = f"P{pnums[pi]}" + for ti in range(t): + tile = _resize_even(frames[pi, ti], max_tile_w) + decorated[pi, ti] = ( + decorate_frame(tile, acts[pi, ti], label=label, team=clip.teams[pi]) if keyboard else tile + ) + + out = [] + for ti in range(t): + grid = _compose_grid_frame(list(decorated[:, ti]), clip.teams, cols, gutter, border) + gh = grid.shape[0] + panel = radar_panel_frame( + clip.physics[perspective][ti], + panel_h=gh, + has_clock=has_clock, + radar_size=radar_size, + badge=badges[ti], + player_labels=player_labels, + ) + canvas = np.full((gh, grid.shape[1] + gutter + panel.shape[1], 3), _BG, np.uint8) + canvas[:, : grid.shape[1]] = grid + canvas[: panel.shape[0], grid.shape[1] + gutter :] = panel + out.append(_resize_even(canvas, canvas.shape[1])) # ensure even W/H for libx264 + return _encode_mp4(np.stack(out), fps) + + +def game_state_md(clip, *, frame: int = 0, perspective: int = 0) -> str: + """A compact markdown readout of one physics frame: game phase, score, clock (shown on the + perspective that carries it), overtime, ball height, and per-car boost / flags / attacker.""" + from .physics import local_car, perspective_has_clock, step_badges + + fr = clip.physics[perspective][frame] + g = fr["game"] + has_clock = perspective_has_clock(clip.physics[perspective]) + tr = g.get("time_remaining", 0.0) + clock = f"{int(tr) // 60}:{int(tr) % 60:02d}" if has_clock else "—" + ot = " · 🔴 **OVERTIME**" if g.get("is_overtime") else "" + local_id = local_car(fr)["player_id"] + known_ids = {c["player_id"] for c in fr["cars"]} + badge = step_badges(clip, perspective)[frame] + note = " — _physics frozen_" if badge.frozen else "" + bz = fr["ball"]["location"]["z"] + rows = [ + f"**Phase** `{badge.code}`{note}", + "", + f"**Score** 🔵 {g.get('score_blue', 0)} — {g.get('score_orange', 0)} 🟠 · " + f"**Clock** {clock}{ot} · **Ball z** {bz:.0f} uu", + "", + "| car | team | boost | flags |", + "|---|---|---|---|", + ] + for c in fr["cars"]: + tag = "🔵" if c["team"] == 0 else "🟠" + me = " ⬅︎you" if c["player_id"] == local_id else "" + flags = [] + if not c.get("is_on_ground", True): + flags.append("air") + if c.get("is_supersonic"): + flags.append("supersonic") + atk = c.get("attacker_player_id", -1) + if atk != -1: # -> demolished + flags.append(f"💥 demo by P{atk}" if atk in known_ids else "💥 demo") + rows.append( + f"| P{c['player_id']}{me} | {tag} | {round(100 * c.get('boost_amount', 0.0))}% | {', '.join(flags) or '—'} |" + ) + return "\n".join(rows) + + +# --- static matplotlib views (no ffmpeg) -------------------------------------------------------- + + +def keystroke_timeline(clip, perspective: int = 0, keys: tuple[str, ...] = DEFAULT_RL_KEYS): + """A colour-coded timeline of key-press intervals for one perspective, with event markers.""" + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + act = _to_numpy(clip.actions[perspective]) # (T, K) + t, k = act.shape + fig, ax = plt.subplots(figsize=(11, 0.32 * k + 1.1)) + fig.patch.set_facecolor("white") + cmap = plt.get_cmap("tab10") + for ki in range(k): + runs, start = [], None + for i, on in enumerate(act[:, ki] > 0): + if on and start is None: + start = i + elif not on and start is not None: + runs.append((start, i - start)) + start = None + if start is not None: + runs.append((start, t - start)) + ax.broken_barh(runs, (ki - 0.38, 0.76), facecolors=cmap(ki % 10), edgecolor="none") + + ax.set_yticks(range(k)) + ax.set_yticklabels(keys, fontsize=8) + ax.set_ylim(-0.6, k - 0.4) + ax.invert_yaxis() + ax.set_xlim(0, t) + ax.set_xlabel(f"clip step ({clip.target_fps} fps, {t} steps)") + ax.set_title(f"key presses — player {clip.player_ids[perspective]} (team {clip.teams[perspective]})", + fontsize=10, loc="left") # fmt: skip + ax.grid(axis="x", color="0.9", lw=0.6) + for spine in ("top", "right"): + ax.spines[spine].set_visible(False) + + # Events as dashed verticals, named in a top-right legend (no label/title collision). + fps_src = clip.src_fps # exact source fps, so markers line up with the loader's frame mapping + f0 = clip.frame_indices[0] + seen: set[str] = set() + for e in clip.events: + x = (e.frame_index(fps_src, clip.recording_offsets[perspective]) - f0) / clip.stride + if 0 <= x < t: + ax.axvline(x, color="0.2", lw=1.1, ls="--", label=None if e.event_name in seen else e.event_name) + seen.add(e.event_name) + if seen: + ax.legend(loc="upper right", fontsize=7, framealpha=0.9, handlelength=1.4) + fig.tight_layout() + return fig diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/world_v10.py b/release-20261107/source/workspace_joint/mira/src/mira/data/world_v10.py new file mode 100644 index 0000000000000000000000000000000000000000..92b5cae0904770a387bb6b60bc01a2d9496cfcd2 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/world_v10.py @@ -0,0 +1,105 @@ +"""Exact 50% episode-start H1 sampling for World-v10 fine-tuning.""" + +from __future__ import annotations + +import random +from typing import Iterator + +from torch.utils.data import Sampler + +from mira.data.world_v7 import WorldV7Dataset + + +class WorldV10PrioritySampler(Sampler[int]): + """Allocate 50% H1 per global step and evenly rotate H3/H6/H10. + + With the audited 8 ranks x 5 local samples, interleaved global positions + form each 40-sample optimizer batch. Even slots are H1 (exactly 20); odd + slots rotate across H3/H6/H10. Across every three optimizer steps the + remaining 60 samples are exactly 20/20/20. + """ + + _GLOBAL_BATCH = 40 + + def __init__( + self, + dataset: WorldV7Dataset, + *, + seed: int, + rank: int = 0, + world_size: int = 1, + clean_probability: float = 0.5, + h1_episode_start_only: bool = True, + supplemental_expanded_index: int | None = None, + supplemental_every_steps: int = 0, + start_index: int = 0, + ) -> None: + if world_size != 8: + raise ValueError("World-v10 sampler requires eight ranks") + if not h1_episode_start_only: + raise ValueError("World-v10 H1 samples must be episode-start") + self.dataset = dataset + self.seed = seed + self.rank = rank + self.world_size = world_size + self.clean_probability = clean_probability + self.h1_episode_start_only = h1_episode_start_only + self.supplemental_expanded_index = supplemental_expanded_index + self.supplemental_every_steps = supplemental_every_steps + if (supplemental_expanded_index is None) != (supplemental_every_steps == 0): + raise ValueError( + "Supplemental replay requires both an expanded index and a positive interval" + ) + self.consumed = start_index + + def __len__(self) -> int: + return 2**31 + + @classmethod + def history_index(cls, global_position: int) -> int: + local_position, rank = divmod(global_position, 8) + optimizer_step, local_slot = divmod(local_position, 5) + if (local_slot + rank) % 2 == 0: + return 0 + other_ordinal = local_slot * 4 + rank // 2 + return 1 + ((other_ordinal + optimizer_step * 20) % 3) + + def __iter__(self) -> Iterator[int]: + position = self.consumed + while True: + global_position = position * self.world_size + self.rank + local_position, global_rank = divmod(global_position, self.world_size) + optimizer_step, local_slot = divmod(local_position, 5) + if ( + self.supplemental_expanded_index is not None + and optimizer_step % self.supplemental_every_steps == 0 + and local_slot == 0 + and global_rank == 0 + ): + # Replace an existing H1 slot so the exact 50% H1 contract is + # unchanged while the selected task gets deterministic replay. + yield self.supplemental_expanded_index + position += 1 + continue + rng = random.Random(self.seed + global_position * 1_000_003) + task = self.dataset.tasks[rng.randrange(len(self.dataset.tasks))] + desired = "clean" if rng.random() < self.clean_probability else "randomized" + domains = self.dataset.task_domain_episodes[task] + domain = desired if desired in domains else sorted(domains)[rng.randrange(len(domains))] + episodes = domains[domain] + episode = episodes[rng.randrange(len(episodes))] + history_index = self.history_index(global_position) + latent_start = ( + 0 if history_index == 0 else rng.randrange(self.dataset.base_counts[episode]) + ) + yield self.dataset.expanded_index(episode, latent_start, history_index) + position += 1 + + def mark_consumed(self, samples: int) -> None: + self.consumed += samples + + def state_dict(self) -> dict[str, int]: + return {"consumed": self.consumed} + + def load_state_dict(self, value: dict[str, int]) -> None: + self.consumed = int(value["consumed"]) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/world_v12.py b/release-20261107/source/workspace_joint/mira/src/mira/data/world_v12.py new file mode 100644 index 0000000000000000000000000000000000000000..fec3d05fe68edc1d164d415240ba085b96d51c2d --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/world_v12.py @@ -0,0 +1,155 @@ +"""Eval-aligned growing-prefix sampling for World-v12 fine-tuning. + +The deployed controller grows one episode context until ten latent frames are +available, then switches to a sliding ten-frame window. Consequently H1, H3, +and H6 are legal only at episode start; H10 covers every legal start. +""" + +from __future__ import annotations + +import math +import random +from typing import Iterator + +from torch.utils.data import Sampler + +from mira.data.world_v7 import WorldV7Dataset + + +class WorldV12EvalAlignedSampler(Sampler[int]): + """Exact 25% H1/H3/H6/H10 with deterministic no-replacement sweeps. + + Every global optimizer batch contains exactly one quarter of every history. + H1/H3/H6 sweep the episode list at ``latent_start=0``. H10 sweeps all + legal base windows. Smaller prefix strata repeat across one H10 epoch, but + each repeat uses a new deterministic permutation. + """ + + _SUPPORTED_WORLD_SIZES = (4, 8) + def __init__( + self, + dataset: WorldV7Dataset, + *, + seed: int, + rank: int = 0, + world_size: int = 8, + clean_probability: float = 0.5, + h1_episode_start_only: bool = True, + start_index: int = 0, + local_batch_size: int = 5, + stratum_start_ordinal: int = 0, + ) -> None: + if world_size not in self._SUPPORTED_WORLD_SIZES: + raise ValueError("World-v12 sampler requires four or eight ranks") + if not h1_episode_start_only: + raise ValueError("World-v12 requires episode-start H1") + if len(dataset.source_rows) <= 0 or dataset.base_windows <= 0: + raise ValueError("World-v12 requires non-empty episode and H10 strata") + self.dataset = dataset + self.seed = int(seed) + self.rank = int(rank) + self.world_size = int(world_size) + # Retained in the signature for compatibility with the shared trainer. + # Natural full-coverage sweeps intentionally do not task/domain reweight. + self.clean_probability = float(clean_probability) + self.h1_episode_start_only = bool(h1_episode_start_only) + if local_batch_size <= 0: + raise ValueError("World-v12 local batch size must be positive") + if stratum_start_ordinal < 0: + raise ValueError("World-v12 stratum ordinal must be non-negative") + self.local_batch_size = int(local_batch_size) + self.stratum_start_ordinal = int(stratum_start_ordinal) + self.consumed = int(start_index) + self._affine_cache: dict[tuple[int, int], tuple[int, int]] = {} + + def __len__(self) -> int: + return 2**31 + + @classmethod + def layout( + cls, global_position: int, local_batch_size: int = 5, world_size: int = 8 + ) -> tuple[int, int, int, int]: + """Return optimizer step, local slot, rank, and history index.""" + + if world_size not in cls._SUPPORTED_WORLD_SIZES: + raise ValueError("World-v12 layout requires four or eight ranks") + local_position, rank = divmod(global_position, world_size) + optimizer_step, local_slot = divmod(local_position, local_batch_size) + history_index = (local_slot + rank + optimizer_step) % 4 + return optimizer_step, local_slot, rank, history_index + + @classmethod + def history_ordinal( + cls, global_position: int, local_batch_size: int = 5, world_size: int = 8 + ) -> tuple[int, int]: + """Return history index and zero-based draw ordinal within that stratum.""" + + optimizer_step, local_slot, rank, history_index = cls.layout( + global_position, local_batch_size, world_size + ) + preceding = 0 + for previous_slot in range(local_slot + 1): + rank_limit = rank if previous_slot == local_slot else world_size + for previous_rank in range(rank_limit): + previous_history = (previous_slot + previous_rank + optimizer_step) % 4 + preceding += int(previous_history == history_index) + rows_per_history = world_size * local_batch_size // 4 + return history_index, optimizer_step * rows_per_history + preceding + + def _affine_parameters(self, history_index: int, epoch: int, size: int) -> tuple[int, int]: + key = (history_index, epoch) + if key in self._affine_cache: + return self._affine_cache[key] + rng = random.Random( + self.seed + + history_index * 1_000_003 + + epoch * 10_000_019 + + size * 97 + ) + multiplier = rng.randrange(1, size + 1) + while math.gcd(multiplier, size) != 1: + multiplier = 1 if multiplier == size else multiplier + 1 + offset = rng.randrange(size) + self._affine_cache[key] = (multiplier, offset) + return multiplier, offset + + def _permuted(self, history_index: int, ordinal: int, size: int) -> int: + epoch, position = divmod(ordinal, size) + multiplier, offset = self._affine_parameters(history_index, epoch, size) + return (multiplier * position + offset) % size + + def __iter__(self) -> Iterator[int]: + position = self.consumed + episode_count = len(self.dataset.source_rows) + while True: + global_position = position * self.world_size + self.rank + history_index, ordinal = self.history_ordinal( + global_position, self.local_batch_size, self.world_size + ) + ordinal += self.stratum_start_ordinal + if history_index < 3: + episode = self._permuted(history_index, ordinal, episode_count) + yield self.dataset.expanded_index(episode, 0, history_index) + else: + base_global = self._permuted( + history_index, ordinal, self.dataset.base_windows + ) + yield base_global * 4 + history_index + position += 1 + + def mark_consumed(self, samples: int) -> None: + self.consumed += int(samples) + + def state_dict(self) -> dict[str, int]: + return { + "consumed": self.consumed, + "local_batch_size": self.local_batch_size, + "stratum_start_ordinal": self.stratum_start_ordinal, + } + + def load_state_dict(self, value: dict[str, int]) -> None: + if int(value.get("local_batch_size", self.local_batch_size)) != self.local_batch_size: + raise ValueError("World-v12 sampler local batch changed across strict resume") + if int(value.get("stratum_start_ordinal", self.stratum_start_ordinal)) != self.stratum_start_ordinal: + raise ValueError("World-v12 sampler stratum start changed across strict resume") + self.consumed = int(value["consumed"]) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/world_v6.py b/release-20261107/source/workspace_joint/mira/src/mira/data/world_v6.py new file mode 100644 index 0000000000000000000000000000000000000000..f1acc8d3d1355cd5b6b531078c4362dfbd8434fc --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/world_v6.py @@ -0,0 +1,491 @@ +"""Scalable World v6 window join over the immutable episode-level latent cache.""" + +from __future__ import annotations + +import bisect +import ctypes +import hashlib +import io +import json +import os +import random +import zipfile +from collections import OrderedDict, defaultdict +from dataclasses import dataclass, fields +from pathlib import Path +from typing import Any, Iterator + +import h5py +import torch +import torch.nn.functional as F +from safetensors.torch import load_file +from torch import Tensor +from torch.utils.data import Dataset, Sampler +from torchvision.io import ImageReadMode, decode_jpeg + +from .robotwin_wam_schema import read_jsonl, sha256_file + +VIEW_NAMES = ("left", "global", "right") +CAMERA_PATHS = ( + "observation/left_camera/rgb", + "observation/head_camera/rgb", + "observation/right_camera/rgb", +) +ANCHOR_SHARDS = 8 +ANCHOR_SHAPE = (3, 8, 512) +ANCHOR_ELEMENTS = 3 * 8 * 512 +QWEN_RGB_SIZE = (288, 384) +RGB_PREPROCESS_IDENTITY = { + "version": "robotwin-qwen-rgb-v1", + "decode": "torchvision.decode_jpeg.rgb", + "source_layout": "CHW_uint8", + "resize": "pytorch.interpolate.bilinear.align_corners_false.antialias_true.round_uint8", + "target_height": QWEN_RGB_SIZE[0], + "target_width": QWEN_RGB_SIZE[1], + "crop": "none", + "letterbox": "none", +} + + +def window_id(episode_sha256: str, latent_start: int) -> str: + return hashlib.sha256(f"{episode_sha256}:{latent_start}".encode()).hexdigest() + + +def anchor_shard(identifier: str) -> int: + return int.from_bytes(hashlib.sha256(identifier.encode()).digest()[:8], "big") % ANCHOR_SHARDS + + +def qwen_frame_indices(latent_start: int) -> tuple[int, int]: + rgb20 = 2 * latent_start + 19 + source30 = int(rgb20 * 30 / 20 + 0.5) + return rgb20, source30 + + +def preprocess_qwen_rgb(value: Tensor) -> Tensor: + """Apply the frozen RGB/layout/resize contract to three source camera frames.""" + if value.ndim != 4 or value.shape[:2] != (3, 3) or value.dtype != torch.uint8: + raise RuntimeError(f"Unexpected source RGB tensor {tuple(value.shape)} {value.dtype}") + if tuple(value.shape[-2:]) != QWEN_RGB_SIZE: + value = F.interpolate( + value.float(), + size=QWEN_RGB_SIZE, + mode="bilinear", + align_corners=False, + antialias=True, + ).round().clamp_(0, 255).to(torch.uint8) + if value.shape != (3, 3, *QWEN_RGB_SIZE): + raise RuntimeError(f"Unexpected Qwen RGB tensor {tuple(value.shape)} {value.dtype}") + return value + + +@dataclass +class WorldV6Batch: + z_context_raw: Tensor + z_future_raw: Tensor + state_history: Tensor + history_valid: Tensor + future_valid: Tensor + view_valid: Tensor + anchors: Tensor | None = None + obs_last_lgr: Tensor | None = None + + def to(self, *args: Any, **kwargs: Any) -> "WorldV6Batch": + values = {} + for field in fields(self): + value = getattr(self, field.name) + values[field.name] = value.to(*args, **kwargs) if isinstance(value, Tensor) else value + return WorldV6Batch(**values) + + +class RGBCurrentFrameReader: + """Read exact original JPEG frames, optionally reusing an extracted HDF5 member cache.""" + + def __init__( + self, + dataset_root: str | Path, + *, + extracted_episode_root: str | Path | None = None, + payload_cache_size: int = 2, + ) -> None: + self.dataset_root = Path(dataset_root).expanduser().resolve() + self.extracted_root = ( + Path(extracted_episode_root).expanduser().resolve() + if extracted_episode_root is not None + else None + ) + self.payload_cache_size = max(1, payload_cache_size) + self.payload_cache: OrderedDict[str, bytes] = OrderedDict() + + def _payload(self, row: dict[str, Any]) -> bytes: + key = str(row["episode_sha256"]) + if key in self.payload_cache: + value = self.payload_cache.pop(key) + self.payload_cache[key] = value + return value + extracted = self.extracted_root / key[:2] / f"{key}.hdf5" if self.extracted_root else None + if extracted is not None and extracted.is_file(): + value = extracted.read_bytes() + else: + with zipfile.ZipFile(self.dataset_root / row["archive"]) as handle: + value = handle.read(row["member"]) + if extracted is not None: + extracted.parent.mkdir(parents=True, exist_ok=True) + temporary = extracted.with_name(f".{extracted.name}.{os.getpid()}.tmp") + temporary.write_bytes(value) + try: + os.replace(temporary, extracted) + except OSError: + temporary.unlink(missing_ok=True) + self.payload_cache[key] = value + while len(self.payload_cache) > self.payload_cache_size: + self.payload_cache.popitem(last=False) + return value + + def read_source_frame(self, row: dict[str, Any], source_index: int) -> Tensor: + """Decode one explicitly selected 30 Hz source frame for all three views. + + World v7 uses the last *real* context latent as the Qwen frame. Exposing + this primitive keeps the immutable v6 window mapping intact while letting + the v7 cache validate and read current frames at history lengths 1/3/6/10. + """ + if source_index >= int(row["n_source_frames"]): + raise RuntimeError("Qwen current frame crosses the episode boundary") + if source_index < 0: + raise RuntimeError("Qwen current frame index must be non-negative") + with h5py.File(io.BytesIO(self._payload(row)), "r") as episode: + encoded = [] + for path in CAMERA_PATHS: + if path not in episode: + raise RuntimeError(f"Missing v6 camera {path}") + encoded.append( + torch.frombuffer(bytearray(bytes(episode[path][source_index])), dtype=torch.uint8) + ) + images = decode_jpeg(encoded, mode=ImageReadMode.RGB) + if not isinstance(images, list): + raise RuntimeError("Batched JPEG decoder returned an unexpected value") + value = torch.stack(images) + # The delivered RoboTwin JPEGs are 240x320 while the v6 Qwen contract is + # 288x384. Both are 4:3, so this is a deterministic resize without crop + # or letterbox and matches the codec's antialiased bilinear convention. + return preprocess_qwen_rgb(value) + + def __call__( + self, + row: dict[str, Any], + latent_start: int, + *, + source_index: int | None = None, + ) -> Tensor: + _, derived_source_index = qwen_frame_indices(latent_start) + if source_index is None: + source_index = derived_source_index + elif source_index != derived_source_index: + raise RuntimeError( + "Latent-cache source index differs from the pinned v6 half-up frame mapping" + ) + return self.read_source_frame(row, source_index) + + +class AnchorCacheReader: + def __init__( + self, + root: str | Path, + split: str, + *, + expected_windows: int, + expected_window_manifest_sha256: str, + ) -> None: + self.root = Path(root).expanduser().resolve() + identity = json.loads((self.root / "anchor_cache_identity.json").read_text(encoding="utf-8")) + split_identity = identity["splits"][split] + if int(split_identity["windows"]) != expected_windows: + raise ValueError("Anchor cache row count differs from the v6 window manifest") + if split_identity["window_manifest_sha256"] != expected_window_manifest_sha256: + raise ValueError("Anchor cache was built from a different v6 window manifest") + split_root = self.root / split + if not (split_root / "COMPLETE.json").is_file(): + raise ValueError(f"Incomplete anchor cache split: {split}") + self.locators = torch.from_file( + str(split_root / "locators.i64"), shared=False, size=expected_windows, dtype=torch.int64 + ) + self.shards: list[Tensor] = [] + for shard in range(ANCHOR_SHARDS): + rows = int(split_identity["shards"][str(shard)]["rows"]) + path = split_root / f"shard-{shard:02d}.bf16" + if rows: + tensor = torch.from_file( + str(path), shared=False, size=rows * ANCHOR_ELEMENTS, dtype=torch.bfloat16 + ).reshape(rows, *ANCHOR_SHAPE) + else: + tensor = torch.empty((0, *ANCHOR_SHAPE), dtype=torch.bfloat16) + self.shards.append(tensor) + + def __getitem__(self, index: int) -> Tensor: + locator = int(self.locators[index]) + shard, row = locator >> 56, locator & ((1 << 56) - 1) + if not 0 <= shard < ANCHOR_SHARDS or row >= len(self.shards[shard]): + raise RuntimeError("Invalid v6 anchor locator") + return self.shards[shard][row] + + +class WorldV6Dataset(Dataset[dict[str, Any]]): + """Use compact source indices; never materialise 1.5M Python manifest objects per rank.""" + + def __init__( + self, + *, + source_manifest: str | Path, + window_manifest: str | Path, + window_index: str | Path, + dataset_stats: str | Path, + dataset_root: str | Path, + anchors_root: str | Path | None = None, + need_rgb: bool = False, + extracted_episode_root: str | Path | None = None, + episode_cache_size: int = 2, + ) -> None: + self.source_manifest = Path(source_manifest).expanduser().resolve() + self.window_manifest = Path(window_manifest).expanduser().resolve() + self.source_rows = read_jsonl(self.source_manifest) + if not self.source_rows: + raise ValueError("Empty source latent manifest") + if any(row.get("state_semantics") != "simulator_drive_target_not_measured_qpos" for row in self.source_rows): + raise ValueError("World v6 refuses ambiguous state semantics") + self.source_window_counts = [int(row["n_latents"]) - 19 for row in self.source_rows] + self.source_cumulative = [0] + for count in self.source_window_counts: + if count <= 0: + raise ValueError("Source manifest contains an incomplete World window") + self.source_cumulative.append(self.source_cumulative[-1] + count) + index_path = Path(window_index).expanduser().resolve() + count = index_path.stat().st_size // 8 + self.source_indices = torch.from_file( + str(index_path), shared=False, size=count, dtype=torch.int64 + ) + self._episode_cache: OrderedDict[str, dict[str, Tensor]] = OrderedDict() + self.episode_cache_size = max(1, episode_cache_size) + self.need_rgb = need_rgb + self.rgb_reader = ( + RGBCurrentFrameReader( + dataset_root, + extracted_episode_root=extracted_episode_root, + payload_cache_size=episode_cache_size, + ) + if need_rgb + else None + ) + stats = json.loads(Path(dataset_stats).read_text(encoding="utf-8")) + self.state_mean = torch.tensor(stats["mean"], dtype=torch.float32) + self.state_std = torch.tensor(stats["std"], dtype=torch.float32).clamp_min( + float(stats.get("normalization_std_floor", 1.0e-2)) + ) + self.state_clip = float(stats.get("normalization_clip", 5.0)) + self.window_manifest_sha256 = sha256_file(self.window_manifest) + self.anchors = ( + AnchorCacheReader( + anchors_root, + self.window_manifest.stem, + expected_windows=len(self), + expected_window_manifest_sha256=self.window_manifest_sha256, + ) + if anchors_root is not None + else None + ) + self.tasks = sorted({str(row["task"]) for row in self.source_rows}) + self.task_domain_episodes: dict[str, dict[str, list[int]]] = defaultdict( + lambda: defaultdict(list) + ) + for episode, row in enumerate(self.source_rows): + self.task_domain_episodes[str(row["task"])][str(row["domain"])].append(episode) + self.full_identity_index = len(self) == self.source_cumulative[-1] and ( + len(self) == 0 + or (int(self.source_indices[0]) == 0 and int(self.source_indices[-1]) == len(self) - 1) + ) + self.subset_buckets: dict[tuple[str, str], list[int]] = defaultdict(list) + if not self.full_identity_index: + for local_index in range(len(self)): + episode, _ = self._locate_source(int(self.source_indices[local_index])) + row = self.source_rows[episode] + self.subset_buckets[(str(row["task"]), str(row["domain"]))].append(local_index) + # A debug/evaluation manifest can contain only a small, stratified subset of + # the source episodes. Sampling from the full source task vocabulary would + # therefore occasionally select a task with no local candidates. + self.tasks = sorted({task for task, _domain in self.subset_buckets}) + if not self.tasks: + raise ValueError("World v6 window index has no sampleable tasks") + + def __len__(self) -> int: + return self.source_indices.numel() + + def _locate_source(self, global_index: int) -> tuple[int, int]: + if not 0 <= global_index < self.source_cumulative[-1]: + raise IndexError(global_index) + episode = bisect.bisect_right(self.source_cumulative, global_index) - 1 + return episode, global_index - self.source_cumulative[episode] + + def source_window_index(self, episode: int, latent_start: int) -> int: + return self.source_cumulative[episode] + latent_start + + def _episode(self, path: str) -> dict[str, Tensor]: + if path in self._episode_cache: + value = self._episode_cache.pop(path) + self._episode_cache[path] = value + return value + value = load_file(path, device="cpu") + self._episode_cache[path] = value + while len(self._episode_cache) > self.episode_cache_size: + self._episode_cache.popitem(last=False) + return value + + def _normalize_state(self, value: Tensor) -> Tensor: + return ((value.float() - self.state_mean) / self.state_std).clamp( + -self.state_clip, self.state_clip + ) + + def __getitem__(self, index: int) -> dict[str, Any]: + source_index = int(self.source_indices[index]) + episode_index, latent_start = self._locate_source(source_index) + row = self.source_rows[episode_index] + episode = self._episode(str(row["cache_path"])) + latent = episode["world_latent_raw_bf16"] + context = latent[:, latent_start : latent_start + 10] + future = latent[:, latent_start + 10 : latent_start + 20] + state_start = 2 * latent_start + state = self._normalize_state( + episode["joint_target_state20_f32"][state_start : state_start + 20] + ).reshape(20, 2, 7) + if context.shape != (3, 10, 32, 9, 12) or future.shape != (3, 10, 32, 9, 12): + raise RuntimeError("Truncated World v6 latent window") + if state.shape != (20, 2, 7): + raise RuntimeError("Truncated World v6 state history") + identifier = window_id(str(row["episode_sha256"]), latent_start) + qwen_rgb20, qwen_source30 = qwen_frame_indices(latent_start) + source_indices = episode.get("source_index_i32") + if source_indices is None or qwen_rgb20 >= len(source_indices): + raise RuntimeError("Latent cache is missing the Qwen current-frame source index") + cached_source30 = int(source_indices[qwen_rgb20]) + if cached_source30 != qwen_source30: + raise RuntimeError("Latent cache and World v6 Qwen frame mappings disagree") + sample: dict[str, Any] = { + "z_context_raw": context, + "z_future_raw": future, + "state_history": state, + # Unlike the legacy action-history path, all 20 factual state targets are valid at k=0. + "history_valid": torch.ones(20, dtype=torch.bool), + "future_valid": torch.ones(10, dtype=torch.bool), + "view_valid": torch.ones(3, dtype=torch.bool), + "anchors": self.anchors[index] if self.anchors is not None else None, + "obs_last_lgr": ( + self.rgb_reader(row, latent_start, source_index=cached_source30) + if self.rgb_reader + else None + ), + "metadata": { + "window_id": identifier, + "source_index": source_index, + "episode_sha256": row["episode_sha256"], + "latent_start": latent_start, + "qwen_rgb20_index": qwen_rgb20, + "qwen_source_index_30hz": cached_source30, + "task": row["task"], + "domain": row["domain"], + "instruction": row["instruction"], + }, + } + return sample + + +def collate_world_v6(samples: list[dict[str, Any]]) -> tuple[WorldV6Batch, list[dict[str, Any]]]: + def optional_stack(name: str) -> Tensor | None: + values = [sample[name] for sample in samples] + if all(value is None for value in values): + return None + if any(value is None for value in values): + raise ValueError(f"Mixed optional values in batch field {name}") + return torch.stack(values) + + batch = WorldV6Batch( + z_context_raw=torch.stack([sample["z_context_raw"] for sample in samples]), + z_future_raw=torch.stack([sample["z_future_raw"] for sample in samples]), + state_history=torch.stack([sample["state_history"] for sample in samples]), + history_valid=torch.stack([sample["history_valid"] for sample in samples]), + future_valid=torch.stack([sample["future_valid"] for sample in samples]), + view_valid=torch.stack([sample["view_valid"] for sample in samples]), + anchors=optional_stack("anchors"), + obs_last_lgr=optional_stack("obs_last_lgr"), + ) + return batch, [sample["metadata"] for sample in samples] + + +class WorldV6BalancedSampler(Sampler[int]): + """Task-first/domain-balanced deterministic sampler with exact resumable cursor.""" + + def __init__( + self, + dataset: WorldV6Dataset, + *, + seed: int, + rank: int = 0, + world_size: int = 1, + clean_probability: float = 0.5, + start_index: int = 0, + ) -> None: + self.dataset = dataset + self.seed = seed + self.rank = rank + self.world_size = world_size + self.clean_probability = clean_probability + self.consumed = start_index + + def __len__(self) -> int: + return 2**31 + + def __iter__(self) -> Iterator[int]: + position = self.consumed + while True: + global_position = position * self.world_size + self.rank + rng = random.Random(self.seed + global_position * 1_000_003) + task = self.dataset.tasks[rng.randrange(len(self.dataset.tasks))] + desired = "clean" if rng.random() < self.clean_probability else "randomized" + if self.dataset.full_identity_index: + domains = self.dataset.task_domain_episodes[task] + domain = desired if desired in domains else sorted(domains)[rng.randrange(len(domains))] + episodes = domains[domain] + episode = episodes[rng.randrange(len(episodes))] + latent_start = rng.randrange(self.dataset.source_window_counts[episode]) + yield self.dataset.source_window_index(episode, latent_start) + else: + candidates = self.dataset.subset_buckets.get((task, desired)) + if not candidates: + available = [ + values for (candidate_task, _), values in self.dataset.subset_buckets.items() + if candidate_task == task + ] + if not available: + raise RuntimeError(f"No indexed World v6 windows for sampled task {task!r}") + candidates = available[rng.randrange(len(available))] + yield candidates[rng.randrange(len(candidates))] + position += 1 + + def mark_consumed(self, samples: int) -> None: + self.consumed += samples + + def state_dict(self) -> dict[str, int]: + return {"consumed": self.consumed} + + def load_state_dict(self, value: dict[str, int]) -> None: + self.consumed = int(value["consumed"]) + + +def set_world_v6_process_name(name: str) -> None: + prefix = os.environ.get("MIRA_V6_PROCESS_PREFIX") + if prefix and name.startswith("syncnet_v6"): + name = f"{prefix}{name.removeprefix('syncnet_v6')}" + try: + import setproctitle + + setproctitle.setproctitle(name) + except ImportError: + pass + value = name.encode()[:15] + ctypes.CDLL(None).prctl(15, value, 0, 0, 0) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/world_v7.py b/release-20261107/source/workspace_joint/mira/src/mira/data/world_v7.py new file mode 100644 index 0000000000000000000000000000000000000000..e9df08204f2caba2b7cd8ef136e8de838d134a48 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/world_v7.py @@ -0,0 +1,367 @@ +"""Short-history World v7 dataset joined to packed frozen-Qwen hidden tokens.""" + +from __future__ import annotations + +import bisect +import json +import random +from collections import OrderedDict, defaultdict +from dataclasses import dataclass, fields +from pathlib import Path +from typing import Any, Iterator + +import torch +from safetensors.torch import load_file +from torch import Tensor +from torch.utils.data import Dataset, Sampler + +from mira.data.robotwin_wam_schema import read_jsonl, sha256_file + +HISTORY_LENGTHS = (1, 3, 6, 10) +HIDDEN_WIDTH = 2048 +VIEWS = 3 + + +class PackedQwenHiddenCache: + """Memory-map deterministic variable-length cache chunks on demand.""" + + def __init__( + self, + root: str | Path, + split: str, + *, + expected_source_manifest: str | Path, + mapping_cache_size: int = 64, + ) -> None: + self.root = Path(root).expanduser().resolve() + identity_path = self.root / "qwen_hidden_cache_identity.json" + if not identity_path.is_file(): + raise ValueError("World v7 Qwen hidden cache identity is incomplete") + identity = json.loads(identity_path.read_text(encoding="utf-8")) + if identity.get("complete") is not True or identity.get("resampler_cached") is not False: + raise ValueError("World v7 requires a complete pre-Resampler Qwen hidden cache") + if identity.get("history_lengths") != list(HISTORY_LENGTHS): + raise ValueError("Qwen hidden cache history-length contract changed") + complete_path = self.root / split / "COMPLETE.json" + if not complete_path.is_file(): + raise ValueError(f"Incomplete World v7 cache split: {split}") + self.complete = json.loads(complete_path.read_text(encoding="utf-8")) + build = self.complete["build_identity"] + if build.get("bounded_unique_rows") is not False: + raise ValueError("Formal World v7 refuses a bounded Qwen hidden cache") + if build.get("source_manifest_sha256") != sha256_file(expected_source_manifest): + raise ValueError("Qwen hidden cache uses a different source manifest") + if build.get("valid_token_packing") != "strip_qwen_attention_mask_false": + raise ValueError("Unsupported Qwen hidden packing") + if build.get("dtype") != "bfloat16" or int(build.get("hidden_width", -1)) != HIDDEN_WIDTH: + raise ValueError("Qwen hidden cache dtype/width changed") + self.split_root = self.root / split + self.world_size = int(build["cache_world_size"]) + self.chunk_rows = int(build["chunk_rows"]) + if self.world_size != 8 or self.chunk_rows != 512: + raise ValueError("Formal World v7 cache topology must be 8 shards x 512 rows") + self.total_rows = int(self.complete["unique_current_rows"]) + self.mapping_cache_size = max(1, mapping_cache_size) + self._mappings: OrderedDict[tuple[int, int], tuple[Tensor, Tensor]] = OrderedDict() + + def _mapping(self, shard: int, chunk: int) -> tuple[Tensor, Tensor]: + key = (shard, chunk) + if key in self._mappings: + value = self._mappings.pop(key) + self._mappings[key] = value + return value + stem = self.split_root / f"shard-{shard:02d}" / f"chunk-{chunk:06d}" + metadata_path = stem.with_suffix(".json") + if not metadata_path.is_file(): + raise FileNotFoundError(f"Missing Qwen hidden cache chunk: {metadata_path}") + metadata = json.loads(metadata_path.read_text(encoding="utf-8")) + rows, tokens = int(metadata["rows"]), int(metadata["tokens"]) + lengths_path = stem.with_suffix(".lengths.i16") + hidden_path = stem.with_suffix(".bf16") + if lengths_path.stat().st_size != rows * VIEWS * 2: + raise ValueError(f"Qwen length file size changed: {lengths_path}") + if hidden_path.stat().st_size != tokens * HIDDEN_WIDTH * 2: + raise ValueError(f"Qwen hidden file size changed: {hidden_path}") + lengths = torch.from_file( + str(lengths_path), shared=False, size=rows * VIEWS, dtype=torch.int16 + ).reshape(rows, VIEWS) + hidden = torch.from_file( + str(hidden_path), + shared=False, + size=tokens * HIDDEN_WIDTH, + dtype=torch.bfloat16, + ).reshape(tokens, HIDDEN_WIDTH) + self._mappings[key] = (lengths, hidden) + while len(self._mappings) > self.mapping_cache_size: + self._mappings.popitem(last=False) + return lengths, hidden + + def __getitem__(self, unique_global: int) -> tuple[Tensor, Tensor, Tensor]: + if not 0 <= unique_global < self.total_rows: + raise IndexError(unique_global) + shard = unique_global % self.world_size + shard_row = unique_global // self.world_size + chunk, row = divmod(shard_row, self.chunk_rows) + lengths, hidden = self._mapping(shard, chunk) + if row >= lengths.shape[0]: + raise RuntimeError("Qwen cache locator crosses its final chunk") + offset = int(lengths[:row].to(torch.int64).sum()) + lane_lengths = lengths[row].to(torch.int64) + lanes = [] + for value in lane_lengths.tolist(): + lanes.append(hidden[offset : offset + value]) + offset += value + return lanes[0], lanes[1], lanes[2] + + +@dataclass +class WorldV7Batch: + z_context_raw: Tensor + z_future_raw: Tensor + state_history: Tensor + history_valid: Tensor + context_valid: Tensor + future_valid: Tensor + view_valid: Tensor + qwen_hidden: Tensor + qwen_mask: Tensor + history_length: Tensor + + def to(self, *args: Any, **kwargs: Any) -> "WorldV7Batch": + return WorldV7Batch( + **{ + field.name: getattr(self, field.name).to(*args, **kwargs) + for field in fields(self) + } + ) + + +class WorldV7Dataset(Dataset[dict[str, Any]]): + """Expand every legal 10+10 source window into h={1,3,6,10}.""" + + def __init__( + self, + *, + source_manifest: str | Path, + dataset_stats: str | Path, + qwen_cache_root: str | Path, + split: str, + episode_cache_size: int = 4, + mapping_cache_size: int = 64, + ) -> None: + self.source_manifest = Path(source_manifest).expanduser().resolve() + self.source_rows = read_jsonl(self.source_manifest) + if not self.source_rows: + raise ValueError("Empty World v7 source manifest") + if any( + row.get("state_semantics") != "simulator_drive_target_not_measured_qpos" + for row in self.source_rows + ): + raise ValueError("World v7 refuses ambiguous state semantics") + self.base_counts = [int(row["n_latents"]) - 19 for row in self.source_rows] + self.unique_counts = [int(row["n_latents"]) - 10 for row in self.source_rows] + self.base_cumulative = [0] + self.unique_cumulative = [0] + for base, unique in zip(self.base_counts, self.unique_counts): + if base <= 0: + raise ValueError("Source episode cannot provide 10+10 supervision") + self.base_cumulative.append(self.base_cumulative[-1] + base) + self.unique_cumulative.append(self.unique_cumulative[-1] + unique) + self.cache = PackedQwenHiddenCache( + qwen_cache_root, + split, + expected_source_manifest=self.source_manifest, + mapping_cache_size=mapping_cache_size, + ) + if self.cache.total_rows != self.unique_cumulative[-1]: + raise ValueError("Qwen cache unique-row count differs from source episodes") + complete = self.cache.complete + if int(complete["source_windows"]) != self.base_cumulative[-1]: + raise ValueError("Qwen cache source-window count differs from World v7") + if int(complete["expanded_supervision_rows"]) != len(self): + raise ValueError("Qwen cache expanded-row count differs from World v7") + stats = json.loads(Path(dataset_stats).read_text(encoding="utf-8")) + self.state_mean = torch.tensor(stats["mean"], dtype=torch.float32) + self.state_std = torch.tensor(stats["std"], dtype=torch.float32).clamp_min( + float(stats.get("normalization_std_floor", 1.0e-2)) + ) + self.state_clip = float(stats.get("normalization_clip", 5.0)) + self.episode_cache_size = max(1, episode_cache_size) + self._episodes: OrderedDict[str, dict[str, Tensor]] = OrderedDict() + self.tasks = sorted({str(row["task"]) for row in self.source_rows}) + self.task_domain_episodes: dict[str, dict[str, list[int]]] = defaultdict( + lambda: defaultdict(list) + ) + for episode, row in enumerate(self.source_rows): + self.task_domain_episodes[str(row["task"])][str(row["domain"])].append(episode) + + def __len__(self) -> int: + return self.base_cumulative[-1] * len(HISTORY_LENGTHS) + + @property + def base_windows(self) -> int: + return self.base_cumulative[-1] + + def _locate_base(self, base_global: int) -> tuple[int, int]: + if not 0 <= base_global < self.base_windows: + raise IndexError(base_global) + episode = bisect.bisect_right(self.base_cumulative, base_global) - 1 + return episode, base_global - self.base_cumulative[episode] + + def expanded_index(self, episode: int, latent_start: int, history_index: int) -> int: + if history_index not in range(len(HISTORY_LENGTHS)): + raise IndexError(history_index) + return (self.base_cumulative[episode] + latent_start) * len(HISTORY_LENGTHS) + history_index + + def _episode(self, path: str) -> dict[str, Tensor]: + if path in self._episodes: + value = self._episodes.pop(path) + self._episodes[path] = value + return value + value = load_file(path, device="cpu") + self._episodes[path] = value + while len(self._episodes) > self.episode_cache_size: + self._episodes.popitem(last=False) + return value + + def _normalize_state(self, value: Tensor) -> Tensor: + return ((value.float() - self.state_mean) / self.state_std).clamp( + -self.state_clip, self.state_clip + ) + + def __getitem__(self, index: int) -> dict[str, Any]: + base_global, history_index = divmod(index, len(HISTORY_LENGTHS)) + episode_index, latent_start = self._locate_base(base_global) + history_length = HISTORY_LENGTHS[history_index] + row = self.source_rows[episode_index] + episode = self._episode(str(row["cache_path"])) + latent = episode["world_latent_raw_bf16"] + real_context = latent[:, latent_start : latent_start + history_length] + context_padding = real_context[:, :1].expand(-1, 10 - history_length, -1, -1, -1) + context = torch.cat([context_padding, real_context], dim=1) + future_start = latent_start + history_length + future = latent[:, future_start : future_start + 10] + state_start = 2 * latent_start + real_state = episode["joint_target_state20_f32"][ + state_start : state_start + 2 * history_length + ] + # The latent cache stores the two 7-DoF arms flattened as [time, 14], + # matching the v6 normalization statistics. Reshape only after padding + # and normalization, exactly as the source pipeline does. + state_padding = real_state[:1].expand(20 - 2 * history_length, -1) + state = self._normalize_state(torch.cat([state_padding, real_state], dim=0)).reshape( + 20, 2, 7 + ) + context_valid = torch.zeros(10, dtype=torch.bool) + context_valid[10 - history_length :] = True + history_valid = torch.zeros(20, dtype=torch.bool) + history_valid[20 - 2 * history_length :] = True + if context.shape != (3, 10, 32, 9, 12) or future.shape != (3, 10, 32, 9, 12): + raise RuntimeError("Truncated World v7 latent window") + if state.shape != (20, 2, 7): + raise RuntimeError("Truncated World v7 state window") + current_latent = latent_start + history_length - 1 + unique_global = self.unique_cumulative[episode_index] + current_latent + lanes = self.cache[unique_global] + return { + "z_context_raw": context, + "z_future_raw": future, + "state_history": state, + "history_valid": history_valid, + "context_valid": context_valid, + "future_valid": torch.ones(10, dtype=torch.bool), + "view_valid": torch.ones(3, dtype=torch.bool), + "qwen_lanes": lanes, + "history_length": history_length, + "metadata": { + "expanded_index": index, + "base_global": base_global, + "episode_sha256": row["episode_sha256"], + "episode_index": episode_index, + "latent_start": latent_start, + "history_length": history_length, + "current_latent": current_latent, + "future_start_latent": future_start, + "qwen_unique_global": unique_global, + "task": row["task"], + "domain": row["domain"], + "instruction": row["instruction"], + }, + } + + +def collate_world_v7( + samples: list[dict[str, Any]], +) -> tuple[WorldV7Batch, list[dict[str, Any]]]: + max_length = max(lane.shape[0] for sample in samples for lane in sample["qwen_lanes"]) + hidden = torch.zeros(len(samples), VIEWS, max_length, HIDDEN_WIDTH, dtype=torch.bfloat16) + mask = torch.zeros(len(samples), VIEWS, max_length, dtype=torch.bool) + for sample_index, sample in enumerate(samples): + for view, lane in enumerate(sample["qwen_lanes"]): + hidden[sample_index, view, : lane.shape[0]] = lane + mask[sample_index, view, : lane.shape[0]] = True + batch = WorldV7Batch( + z_context_raw=torch.stack([sample["z_context_raw"] for sample in samples]), + z_future_raw=torch.stack([sample["z_future_raw"] for sample in samples]), + state_history=torch.stack([sample["state_history"] for sample in samples]), + history_valid=torch.stack([sample["history_valid"] for sample in samples]), + context_valid=torch.stack([sample["context_valid"] for sample in samples]), + future_valid=torch.stack([sample["future_valid"] for sample in samples]), + view_valid=torch.stack([sample["view_valid"] for sample in samples]), + qwen_hidden=hidden, + qwen_mask=mask, + history_length=torch.tensor( + [sample["history_length"] for sample in samples], dtype=torch.int64 + ), + ) + return batch, [sample["metadata"] for sample in samples] + + +class WorldV7BalancedSampler(Sampler[int]): + """Task/domain-balanced sampler with exact 1/3/6/10 rotation per rank.""" + + def __init__( + self, + dataset: WorldV7Dataset, + *, + seed: int, + rank: int = 0, + world_size: int = 1, + clean_probability: float = 0.5, + start_index: int = 0, + ) -> None: + self.dataset = dataset + self.seed = seed + self.rank = rank + self.world_size = world_size + self.clean_probability = clean_probability + self.consumed = start_index + + def __len__(self) -> int: + return 2**31 + + def __iter__(self) -> Iterator[int]: + position = self.consumed + while True: + global_position = position * self.world_size + self.rank + rng = random.Random(self.seed + global_position * 1_000_003) + task = self.dataset.tasks[rng.randrange(len(self.dataset.tasks))] + desired = "clean" if rng.random() < self.clean_probability else "randomized" + domains = self.dataset.task_domain_episodes[task] + domain = desired if desired in domains else sorted(domains)[rng.randrange(len(domains))] + episodes = domains[domain] + episode = episodes[rng.randrange(len(episodes))] + latent_start = rng.randrange(self.dataset.base_counts[episode]) + # Per-device batches of four contain every history length exactly once. + history_index = (position + self.rank) % len(HISTORY_LENGTHS) + yield self.dataset.expanded_index(episode, latent_start, history_index) + position += 1 + + def mark_consumed(self, samples: int) -> None: + self.consumed += samples + + def state_dict(self) -> dict[str, int]: + return {"consumed": self.consumed} + + def load_state_dict(self, value: dict[str, int]) -> None: + self.consumed = int(value["consumed"]) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/data/world_v8.py b/release-20261107/source/workspace_joint/mira/src/mira/data/world_v8.py new file mode 100644 index 0000000000000000000000000000000000000000..1b17d33204ee6c10782e07e41b3eabd03337eac7 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/data/world_v8.py @@ -0,0 +1,74 @@ +"""H1-priority sampling for Online-only World v8 fine-tuning.""" + +from __future__ import annotations + +import random +from typing import Iterator + +from torch.utils.data import Sampler + +from mira.data.world_v7 import WorldV7Dataset + +HISTORY_LENGTHS = (1, 3, 6, 10) +HISTORY_CYCLE = (0, 0, 1, 2, 3) + + +class WorldV8PrioritySampler(Sampler[int]): + """Task/domain-balanced sampler with exact 40/20/20/20 history allocation. + + Every consecutive local batch of five contains two h1 samples and one each + of h3, h6, and h10. Rank-dependent rotation avoids aligning the same + history length at the same micro-position on every device while preserving + the exact global mixture at every optimizer step. + """ + + def __init__( + self, + dataset: WorldV7Dataset, + *, + seed: int, + rank: int = 0, + world_size: int = 1, + clean_probability: float = 0.5, + h1_episode_start_only: bool = False, + start_index: int = 0, + ) -> None: + self.dataset = dataset + self.seed = seed + self.rank = rank + self.world_size = world_size + self.clean_probability = clean_probability + self.h1_episode_start_only = h1_episode_start_only + self.consumed = start_index + + def __len__(self) -> int: + return 2**31 + + def __iter__(self) -> Iterator[int]: + position = self.consumed + while True: + global_position = position * self.world_size + self.rank + rng = random.Random(self.seed + global_position * 1_000_003) + task = self.dataset.tasks[rng.randrange(len(self.dataset.tasks))] + desired = "clean" if rng.random() < self.clean_probability else "randomized" + domains = self.dataset.task_domain_episodes[task] + domain = desired if desired in domains else sorted(domains)[rng.randrange(len(domains))] + episodes = domains[domain] + episode = episodes[rng.randrange(len(episodes))] + history_index = HISTORY_CYCLE[(position + self.rank) % len(HISTORY_CYCLE)] + latent_start = ( + 0 + if history_index == 0 and self.h1_episode_start_only + else rng.randrange(self.dataset.base_counts[episode]) + ) + yield self.dataset.expanded_index(episode, latent_start, history_index) + position += 1 + + def mark_consumed(self, samples: int) -> None: + self.consumed += samples + + def state_dict(self) -> dict[str, int]: + return {"consumed": self.consumed} + + def load_state_dict(self, value: dict[str, int]) -> None: + self.consumed = int(value["consumed"]) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/inference/__init__.py b/release-20261107/source/workspace_joint/mira/src/mira/inference/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..01a9fea77bf61a0ad1818dcfcbe5ee21c4f141d6 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/inference/__init__.py @@ -0,0 +1,21 @@ +"""mira.inference: offline autoregressive rollout and checkpoint loading. + +Public API: + rollout — autoregressive denoising of a clip into latents, without the final decode + measure_rollout_speed — time :func:`rollout` over a fixed number of latent frames + load_world_model — instantiate the right world-model class from a checkpoint dir +""" + +from __future__ import annotations + +from .bihub_world_rollout import latent_rollout_metrics, sample_bihub_rollout +from .loading import load_world_model +from .rollout import measure_rollout_speed, rollout + +__all__ = [ + "load_world_model", + "latent_rollout_metrics", + "measure_rollout_speed", + "rollout", + "sample_bihub_rollout", +] diff --git a/release-20261107/source/workspace_joint/mira/src/mira/inference/bihub_world_rollout.py b/release-20261107/source/workspace_joint/mira/src/mira/inference/bihub_world_rollout.py new file mode 100644 index 0000000000000000000000000000000000000000..0ab5871a1c00ff595a956aed2268284f444f7d40 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/inference/bihub_world_rollout.py @@ -0,0 +1,93 @@ +"""Reproducible BiHub Stage-W rollout diagnostics and frozen-codec rendering.""" + +from __future__ import annotations + +from typing import Any + +import torch +from torch import Tensor, nn + +from mira.data.robotwin_wam_loader import RoboTwinWorldBatch + +VIEW_NAMES = ("left", "global", "right") + + +@torch.inference_mode() +def sample_bihub_rollout( + model: nn.Module, + batch: RoboTwinWorldBatch, + *, + steps: int, + seed: int, +) -> Tensor: + """Sample through ``forward`` so FSDP2's root unshard hook is never bypassed.""" + device = batch.world_future_raw.device + generator = torch.Generator(device=device).manual_seed(seed) + noise = torch.randn(batch.world_future_raw.shape, generator=generator, device=device) + output = model(batch, sample_steps=steps, noise=noise) + return output["sample_future_raw"] + + +def latent_rollout_metrics(context: Tensor, target: Tensor, prediction: Tensor) -> dict[str, float]: + """Compare a rollout with both ground truth and the last-context persistence baseline.""" + expected = (3, 10, 32, 9, 12) + if tuple(context.shape) != expected or tuple(target.shape) != expected or tuple(prediction.shape) != expected: + raise ValueError(f"Expected three [3,10,32,9,12] tensors, got {context.shape=}, {target.shape=}, {prediction.shape=}") + target = target.float() + prediction = prediction.float() + persistence = context[:, -1:].float().expand_as(target) + prediction_sq = (prediction - target).square() + persistence_sq = (persistence - target).square() + metrics: dict[str, float] = { + "latent_mse": float(prediction_sq.mean()), + "persistence_mse": float(persistence_sq.mean()), + } + metrics["persistence_skill"] = 1.0 - metrics["latent_mse"] / max(metrics["persistence_mse"], 1.0e-12) + for view, name in enumerate(VIEW_NAMES): + metrics[f"latent_mse/{name}"] = float(prediction_sq[view].mean()) + metrics[f"persistence_mse/{name}"] = float(persistence_sq[view].mean()) + for horizon in (0, 4, 9): + metrics[f"latent_mse/h{horizon + 1}"] = float(prediction_sq[:, horizon].mean()) + metrics[f"persistence_mse/h{horizon + 1}"] = float(persistence_sq[:, horizon].mean()) + return metrics + + +@torch.inference_mode() +def decode_comparison_video( + decoder: nn.Module, + context: Tensor, + target: Tensor, + prediction: Tensor, + *, + device: torch.device, +) -> Tensor: + """Return 40 RGB frames with view rows and GT/prediction columns in [0,1].""" + rows: list[Tensor] = [] + for view in range(3): + ground_truth = torch.cat([context[view], target[view]], dim=0)[None].to(device) + predicted = torch.cat([context[view], prediction[view]], dim=0)[None].to(device) + with torch.autocast( + device_type=device.type, + dtype=torch.bfloat16, + enabled=device.type == "cuda", + ): + ground_truth_rgb = decoder(ground_truth)[0] + predicted_rgb = decoder(predicted)[0] + row = torch.cat([ground_truth_rgb, predicted_rgb], dim=-1) + rows.append((row.float() * 0.5 + 0.5).clamp(0, 1).cpu()) + return torch.cat(rows, dim=-2) + + +def summarize_rollout_metrics(rows: list[dict[str, Any]]) -> dict[str, Any]: + if not rows: + raise ValueError("No rollout metrics to summarize") + keys = sorted( + key + for key, value in rows[0].items() + if isinstance(value, (int, float)) + and (key.startswith("latent_mse") or key.startswith("persistence_")) + ) + return { + "cases": len(rows), + "mean": {key: sum(float(row[key]) for row in rows) / len(rows) for key in keys}, + } diff --git a/release-20261107/source/workspace_joint/mira/src/mira/inference/loading.py b/release-20261107/source/workspace_joint/mira/src/mira/inference/loading.py new file mode 100644 index 0000000000000000000000000000000000000000..bb10404d191fa00234a983de58c3aa0084b946d3 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/inference/loading.py @@ -0,0 +1,41 @@ +"""Load the right world-model class from a checkpoint directory (used by the offline tools).""" + +from __future__ import annotations + +from pathlib import Path +from typing import TYPE_CHECKING, Any, cast + +if TYPE_CHECKING: + import torch + + from mira.world_model.latent_world_model import LatentWorldModel + + +def load_world_model(checkpoint_path: Path, device: str | torch.device) -> tuple[LatentWorldModel, Any]: + """Load the right world-model class from a checkpoint dir. + + Dispatches on ``model.architecture._target_`` in the saved ``world_model_config.yaml`` and calls + that class's ``load_from_checkpoint`` (single-player or 4-player), so the saved config goes + through the same ``_target_``/removed-field cleaning the dedicated loaders apply. Falls back to + :class:`LatentWorldModel` for older checkpoints without a ``_target_``. Returns ``(model, run_config)``. + """ + from omegaconf import OmegaConf # noqa: PLC0415 -- optional dep, used only on the real path + + from mira.world_model.latent_world_model import LatentWorldModel # noqa: PLC0415 + from mira.world_model.multi_wrapper_world_model import MultiWrapperWorldModel # noqa: PLC0415 + + config_path = LatentWorldModel._find_config(checkpoint_path) + if config_path is None: + raise FileNotFoundError( + f"Could not find '{LatentWorldModel.CONFIG_FILENAME}' in parent directories of {checkpoint_path}." + ) + + cfg = OmegaConf.load(config_path) + arch_target = OmegaConf.select(cfg, "model.architecture._target_") + model_cls = ( + MultiWrapperWorldModel + if arch_target is not None and str(arch_target).endswith("MultiWrapperWorldModel") + else LatentWorldModel + ) + # Both variants share the LatentWorldModel surface (duck-typed); annotate as such. + return cast("LatentWorldModel", model_cls.load_from_checkpoint(checkpoint_path, device=device)), cfg diff --git a/release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_action_policy.py b/release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_action_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..a872cb3f308db3ff6e6732b5de8f2cf331d4390b --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_action_policy.py @@ -0,0 +1,388 @@ +"""Factual-memory RoboTwin policy core for World + Action deployment.""" + +from __future__ import annotations + +import json +import os +import time +from collections import deque +from dataclasses import dataclass +from pathlib import Path +from typing import Callable + +import numpy as np +import torch +import torch.nn.functional as F +from torch import Tensor + +VIEW_ORDER = ("left", "global", "right") + + +@dataclass(frozen=True) +class ActionPolicyProfile: + world_steps: int + action_steps: int = 10 + execute_prefix: int = 10 + future_mode: str = "predicted" + + @classmethod + def quality(cls) -> "ActionPolicyProfile": + return cls(world_steps=10) + + @classmethod + def fast_world(cls) -> "ActionPolicyProfile": + return cls(world_steps=4) + + @classmethod + def current_only(cls) -> "ActionPolicyProfile": + return cls(world_steps=0, future_mode="null") + + def __post_init__(self) -> None: + if self.future_mode not in {"predicted", "null"}: + raise ValueError(f"Unknown future mode: {self.future_mode}") + if self.future_mode == "predicted" and self.world_steps < 1: + raise ValueError("Predicted-future policy requires at least one World step") + if self.action_steps < 1 or not 1 <= self.execute_prefix <= 20: + raise ValueError("Invalid Action sampling/execute-prefix setting") + + +class FactualObservationBuffer: + """Twenty executed observations; imagined latents have no insertion API.""" + + def __init__(self) -> None: + self.rgb: dict[str, deque[Tensor]] = { + view: deque(maxlen=20) for view in VIEW_ORDER + } + self.drive_targets: deque[Tensor] = deque(maxlen=20) + self.executed_observations = 0 + self.cold_start = True + + def reset(self, rgb: dict[str, Tensor], drive_target: Tensor) -> None: + self._validate(rgb, drive_target) + for view in VIEW_ORDER: + self.rgb[view] = deque( + [rgb[view].detach().cpu().clone() for _ in range(20)], + maxlen=20, + ) + self.drive_targets = deque( + [drive_target.detach().float().cpu().clone() for _ in range(20)], + maxlen=20, + ) + self.executed_observations = 0 + self.cold_start = True + + def append_executed(self, rgb: dict[str, Tensor], returned_drive_target: Tensor) -> None: + self._validate(rgb, returned_drive_target) + if not self.drive_targets: + raise RuntimeError("Observation buffer must be reset at episode start") + for view in VIEW_ORDER: + self.rgb[view].append(rgb[view].detach().cpu().clone()) + self.drive_targets.append(returned_drive_target.detach().float().cpu().clone()) + self.executed_observations += 1 + self.cold_start = self.executed_observations < 20 + + @staticmethod + def _validate(rgb: dict[str, Tensor], drive_target: Tensor) -> None: + if set(rgb) != set(VIEW_ORDER): + raise ValueError(f"RGB views must be exactly {VIEW_ORDER}") + shapes = {tuple(value.shape) for value in rgb.values()} + if len(shapes) != 1 or any(value.ndim != 3 for value in rgb.values()): + raise ValueError("All RGB observations must share a [C,H,W] shape") + if drive_target.shape != (14,) or not torch.isfinite(drive_target).all(): + raise ValueError("Returned drive target must be finite [14]") + + def snapshot(self) -> tuple[Tensor, Tensor]: + if len(self.drive_targets) != 20: + raise RuntimeError("Observation buffer is not initialized") + rgb = torch.stack( + [torch.stack(list(self.rgb[view])) for view in VIEW_ORDER] + ) + state = torch.stack(list(self.drive_targets)) + return rgb, state + + +class ActionPostprocessor: + def __init__( + self, + stats: str | Path | dict, + *, + joint_lower: Tensor | None = None, + joint_upper: Tensor | None = None, + ) -> None: + value = ( + json.loads(Path(stats).read_text(encoding="utf-8")) + if isinstance(stats, (str, Path)) + else stats + ) + self.mean = torch.tensor(value["mean"], dtype=torch.float32) + self.std = torch.tensor(value["std"], dtype=torch.float32) + self.minimum = torch.tensor(value["minimum"], dtype=torch.float32) + self.maximum = torch.tensor(value["maximum"], dtype=torch.float32) + self.gripper = value["gripper"] + self.joint_lower = joint_lower + self.joint_upper = joint_upper + if self.mean.shape != (14,) or bool((self.std <= 0).any()): + raise ValueError("Invalid 14D Action statistics") + if (joint_lower is None) != (joint_upper is None): + raise ValueError("Joint limits must provide both lower and upper tensors") + if joint_lower is not None and ( + joint_lower.shape != (12,) or joint_upper is None or joint_upper.shape != (12,) + ): + raise ValueError("Arm joint limits must have 12 dimensions") + + def __call__(self, normalized: Tensor) -> tuple[Tensor, dict[str, float]]: + if normalized.shape != (20, 14) or not torch.isfinite(normalized).all(): + raise FloatingPointError("Action sampler returned non-finite or wrong-shape output") + raw = normalized.detach().float().cpu() * self.std + self.mean + before = raw.clone() + arm_indices = torch.tensor([*range(6), *range(7, 13)]) + if self.joint_lower is not None and self.joint_upper is not None: + raw[:, arm_indices] = torch.maximum( + torch.minimum(raw[:, arm_indices], self.joint_upper), + self.joint_lower, + ) + else: + raw[:, arm_indices] = torch.maximum( + torch.minimum(raw[:, arm_indices], self.maximum[arm_indices]), + self.minimum[arm_indices], + ) + for dimension, name in ((6, "left"), (13, "right")): + rule = self.gripper[name] + if rule["mode"] == "binary": + raw[:, dimension] = torch.where( + raw[:, dimension] >= float(rule["threshold"]), + float(rule["high"]), + float(rule["low"]), + ) + else: + raw[:, dimension].clamp_( + float(self.minimum[dimension]), + float(self.maximum[dimension]), + ) + if not torch.isfinite(raw).all(): + raise FloatingPointError("Non-finite Action after denormalization/safety") + changed = (raw != before).float() + return raw, { + "pre_clamp_violation_ratio": float(changed.mean()), + "max_single_step_change": float((raw[1:] - raw[:-1]).abs().max()), + } + + +class RoboTwinActionPolicyCore: + """Dependency-injected replan/queue core that enforces factual memory.""" + + def __init__( + self, + *, + codec_encode: Callable[[Tensor], Tensor], + text_encode: Callable[[str], tuple[Tensor, Tensor]], + world_sample: Callable[..., Tensor], + action_sample: Callable[..., Tensor], + postprocess: ActionPostprocessor, + profile: ActionPolicyProfile | None = None, + latent_mean: float = 0.024823864160431405, + latent_std: float = 1.9595992324017892, + seed: int = 2026, + failure_dir: str | Path | None = None, + ) -> None: + self.codec_encode = codec_encode + self.text_encode = text_encode + self.world_sample = world_sample + self.action_sample = action_sample + self.postprocess = postprocess + self.profile = profile or ActionPolicyProfile.quality() + self.latent_mean = float(latent_mean) + self.latent_std = float(latent_std) + self.seed = int(seed) + self.failure_dir = Path(failure_dir).expanduser().resolve() if failure_dir else None + self.buffer = FactualObservationBuffer() + self.queue: deque[Tensor] = deque() + self.instruction = "" + self.text_cache: tuple[Tensor, Tensor] | None = None + self.replans = 0 + self.awaiting_observation = False + self.last_plan_tail: Tensor | None = None + self.latency_rows: list[dict[str, float | bool]] = [] + + def reset( + self, + *, + rgb: dict[str, Tensor], + returned_drive_target: Tensor, + instruction: str, + ) -> None: + self.buffer.reset(rgb, returned_drive_target) + self.queue.clear() + self.instruction = instruction + self.text_cache = None + self.replans = 0 + self.awaiting_observation = False + self.last_plan_tail = None + self.latency_rows.clear() + + def next_action(self) -> Tensor: + if self.awaiting_observation: + raise RuntimeError( + "The executed waypoint's real observation must be recorded before requesting another" + ) + if not self.queue: + self._replan() + action = self.queue.popleft().clone() + self.awaiting_observation = True + return action + + def record_execution( + self, + *, + rgb: dict[str, Tensor], + returned_drive_target: Tensor, + ) -> None: + if not self.awaiting_observation: + raise RuntimeError("No pending executed waypoint to attach this observation to") + self.buffer.append_executed(rgb, returned_drive_target) + self.awaiting_observation = False + + def _replan(self) -> None: + rgb, state = self.buffer.snapshot() + started = time.perf_counter() + codec_started = time.perf_counter() + context_raw = self.codec_encode(rgb) + codec_seconds = time.perf_counter() - codec_started + if context_raw.shape != (3, 10, 32, 9, 12) or not torch.isfinite( + context_raw + ).all(): + self._dump_failure( + "codec returned invalid context", + rgb=rgb, + state=state, + context_raw=context_raw, + ) + raise ValueError( + "Exact codec encoder must return finite [3,10,32,9,12], " + f"got {context_raw.shape}" + ) + text_started = time.perf_counter() + if self.text_cache is None: + self.text_cache = self.text_encode(self.instruction) + text_cache_hit = False + else: + text_cache_hit = True + text_seconds = time.perf_counter() - text_started + text_hidden, text_mask = self.text_cache + world_started = time.perf_counter() + if self.profile.future_mode == "predicted": + future_raw = self.world_sample( + context_raw=context_raw, + state_history=state, + text_hidden=text_hidden, + text_mask=text_mask, + steps=self.profile.world_steps, + seed=self.seed + 2 * self.replans, + ) + if future_raw.shape != (3, 10, 32, 9, 12) or not torch.isfinite( + future_raw + ).all(): + self._dump_failure( + "World returned invalid future", + rgb=rgb, + state=state, + context_raw=context_raw, + future_raw=future_raw, + ) + raise ValueError("World sampler must return finite [3,10,32,9,12]") + future = (future_raw.float() - self.latent_mean) / self.latent_std + future = F.adaptive_avg_pool2d( + future.reshape(30, 32, 9, 12), (3, 4) + ).reshape(3, 10, 32, 3, 4) + future_drop = False + else: + future = torch.zeros(3, 10, 32, 3, 4) + future_drop = True + world_seconds = time.perf_counter() - world_started + current = (context_raw[:, -1].float() - self.latent_mean) / self.latent_std + action_started = time.perf_counter() + normalized = self.action_sample( + current_latent=current, + future_latent=future, + future_drop=future_drop, + state_history=state, + text_hidden=text_hidden, + text_mask=text_mask, + steps=self.profile.action_steps, + seed=self.seed + 2 * self.replans + 1, + ) + action_seconds = time.perf_counter() - action_started + safety_started = time.perf_counter() + try: + plan, safety = self.postprocess(normalized) + except (FloatingPointError, ValueError) as error: + self._dump_failure( + str(error), + rgb=rgb, + state=state, + context_raw=context_raw, + future=future, + normalized_action=normalized, + ) + raise + safety_seconds = time.perf_counter() - safety_started + prefix = self.profile.execute_prefix + self.queue.extend(plan[:prefix]) + self.last_plan_tail = plan[prefix:].clone() + self.latency_rows.append( + { + "cold_start": self.buffer.cold_start, + "codec_encode": codec_seconds, + "text_encode": text_seconds, + "text_cache_hit": text_cache_hit, + "world_sample": world_seconds, + "action_sample": action_seconds, + "denormalize_safety": safety_seconds, + "replan_total": time.perf_counter() - started, + **safety, + } + ) + self.replans += 1 + + def _dump_failure(self, reason: str, **tensors: Tensor) -> None: + if self.failure_dir is None: + return + self.failure_dir.mkdir(parents=True, exist_ok=True) + final = self.failure_dir / f"episode-failure-replan-{self.replans:05d}.pt" + temporary = final.with_suffix(".pt.tmp") + torch.save( + { + "reason": reason, + "instruction": self.instruction, + "replan": self.replans, + "profile": self.profile.__dict__, + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state() if torch.cuda.is_available() else None, + "tensors": { + name: value.detach().cpu() if isinstance(value, Tensor) else value + for name, value in tensors.items() + }, + }, + temporary, + ) + os.replace(temporary, final) + + def latency_summary(self) -> dict[str, dict[str, float]]: + numeric_keys = ( + "codec_encode", + "text_encode", + "world_sample", + "action_sample", + "denormalize_safety", + "replan_total", + ) + output = {} + for key in numeric_keys: + values = np.asarray([float(row[key]) for row in self.latency_rows]) + if len(values): + output[key] = { + "mean": float(values.mean()), + "p50": float(np.quantile(values, 0.5)), + "p95": float(np.quantile(values, 0.95)), + } + return output diff --git a/release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_joint_runtime.py b/release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_joint_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..6577f0c0d1d236be311bedd804a6d2b18775f170 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_joint_runtime.py @@ -0,0 +1,159 @@ +"""Joint checkpoint runtime, using the EXACT saved rollout count and normalization.""" +import json +import math +import os +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import torch +from safetensors.torch import load_file +from mira.action_v6.model import BiHubWAMActionStage +from mira.codec.codec_model import VideoCodec +from mira.data.robotwin_wam_schema import sha256_file +from mira.inference.robotwin_v6_runtime import _empty_codec_batch +from mira.inference.robotwin_v10_runtime import BiHubWAMV10Runtime, RuntimeProvenance, VIEW_ORDER +from mira.joint.image_contract import checkpoint_image_contract, codec_needs_bgr +from mira.joint.paths import workspace_path +from mira.world_v6.config import WorldV6ModelConfig +from mira.world_v6.model import WorldV6System +from mira.world_v6.state_encoder import StateEncoderV6 +from mira.world_v6.qwen_current_anchor import FrozenQwenCurrentLanes + + +class BiHubJointRuntime(BiHubWAMV10Runtime): + def __init__(self, *, action_checkpoint: str | Path, device: str = 'cuda'): + self.device = torch.device(device) + root = Path(action_checkpoint).resolve() + meta = json.loads((root / 'deployment.json').read_text()) + if meta['architecture'] != 'bihub-joint-world-action-anchor-v2': + raise ValueError('Expected a paired joint anchor-v2 export') + for name, digest in meta['sha256'].items(): + if sha256_file(root / name) != digest: + raise ValueError(f'Export SHA mismatch: {name}') + cfg = meta['resolved_config'] + if meta['artifact_identity']['world_schedule'] != 'linear_quadratic': + raise ValueError('Unsupported rollout schedule') + self.world = WorldV6System(WorldV6ModelConfig.model_validate(cfg['world_model'])) + self.world.load_state_dict(load_file(root / 'world.safetensors'), strict=True) + self.world.to(self.device).eval().requires_grad_(False) + self.action = BiHubWAMActionStage(state_encoder=StateEncoderV6(), + delta_scale=torch.ones(3, 10, 32), action_mean=torch.zeros(14), action_std=torch.ones(14), + loss_mode=cfg['action_loss']) + self.action.load_state_dict(load_file(root / 'action.safetensors'), strict=True) + self.action.to(self.device).eval().requires_grad_(False) + # Guard against accidentally pairing the trained world with the old frozen state copy. + for key, value in self.world.state_encoder.state_dict().items(): + if not torch.equal(value, self.action.state_encoder.state_dict()[key]): + raise ValueError('World/Action state encoder mismatch') + codec = workspace_path(cfg['resolved_paths']['codec']) + if sha256_file(codec) != meta['artifact_identity']['codec_checkpoint_sha256']: + raise ValueError('Codec mismatch') + self.codec = VideoCodec.load_from_checkpoint(codec, device=self.device).eval().requires_grad_(False) + qwen = workspace_path(cfg['resolved_paths']['qwen']) + self.qwen = FrozenQwenCurrentLanes(qwen, { + 'local_root': str(qwen), 'prompt_version': 'bihub-v6-role-v1', + 'attention_implementation': 'sdpa'}, device=self.device).eval() + stats = cfg['state_stats'] + self.state_mean = torch.tensor(stats['mean'], device=self.device) + self.state_std = torch.tensor(stats['std'], device=self.device).clamp_min(stats.get('normalization_std_floor', 1e-2)) + self.state_clip = stats.get('normalization_clip', 5.0) + self.physical_min = torch.tensor(cfg['action_stats']['physical_min'], device=self.device).reshape(2, 7) + self.physical_max = torch.tensor(cfg['action_stats']['physical_max'], device=self.device).reshape(2, 7) + self.config = SimpleNamespace( + world_inference=SimpleNamespace(steps=cfg['world_rollout_steps'], + latent_mean=self.world.config.latent_mean, latent_std=self.world.config.latent_std), + action=SimpleNamespace(**cfg['action_inference'])) + # The adapter delivers frames in the contract's model input order; a split contract + # reverses channels for the codec branch only (Qwen keeps true RGB). + self.codec_reverse_channels = codec_needs_bgr(checkpoint_image_contract(meta)) + # Opt-in evaluation switches; both are recorded in provenance and every plan. + self.codec_incremental = os.environ.get('BIHUB_CODEC_INCREMENTAL', '0') == '1' + self.codec_incremental_verify = os.environ.get('BIHUB_CODEC_INCREMENTAL_VERIFY', '0') == '1' + clip = os.environ.get('BIHUB_ACTION_CLIP_SIGMA') + if clip: + value = float(clip) + if not math.isfinite(value) or value <= 0: + raise ValueError('BIHUB_ACTION_CLIP_SIGMA must be a positive finite number') + self.config.action.normalized_action_clip = value + self._codec_cache = None + self._plan_key = None + self._codec_reused_frames = 0 + self._codec_verify_abs_max = None + self.provenance = RuntimeProvenance( + action_checkpoint=str(root), action_step=meta['completed_steps'], action_branch='joint', + action_checkpoint_fingerprint=meta['joint_checkpoint_fingerprint'], + world_checkpoint=str(root), world_step=meta['completed_steps'], world_branch='joint', + world_checkpoint_fingerprint=meta['joint_checkpoint_fingerprint'], + codec_sha256=meta['artifact_identity']['codec_checkpoint_sha256'], view_order=VIEW_ORDER, + world_steps=cfg['world_rollout_steps'], action_steps=self.config.action.sampling_steps, + execute_steps=self.config.action.execute_steps, + short_history_contract=meta['artifact_identity']['history_contract'], + codec_channels='reversed' if self.codec_reverse_channels else 'as_received', + codec_incremental=self.codec_incremental, + action_clip_sigma=float(self.config.action.normalized_action_clip)) + + def _encode_frames(self, value: np.ndarray) -> torch.Tensor: + """Codec latents for [3, T, H, W, 3] uint8 frames in codec channel order, T even.""" + video = torch.from_numpy(value).permute(0, 1, 4, 2, 3).to(self.device) + batch = _empty_codec_batch(video) + self.codec.preprocess_batch(batch) + with torch.autocast('cuda', dtype=torch.bfloat16): + _, output = self.codec.encode(batch.video, trim_video=False) + expected = (3, value.shape[1] // 2, 32, 9, 12) + if tuple(output.z.shape) != expected: + raise RuntimeError(f'codec returned {tuple(output.z.shape)}, expected {expected}') + return output.z + + def _reusable_frames(self, value: np.ndarray) -> int: + """New frames since the previous plan of this episode, if its latents can be reused. + + The LingBot backbone and preprocessing act per frame and the temporal bottleneck pairs + frames (2k, 2k+1) without overlap, so latent k depends only on its two frames. Any even + shift whose overlap matches frame-for-frame therefore yields the same latents. + """ + if self._codec_cache is None or self._plan_key is None: + return 0 + key, frames, _ = self._codec_cache + if key[:3] != self._plan_key[:3] or key[3] + 1 != self._plan_key[3]: + return 0 + for shift in range(2, 20, 2): + if np.array_equal(frames[:, shift:], value[:, :20 - shift]): + return shift + return 0 + + @torch.inference_mode() + def encode_history(self, rgb_history: np.ndarray) -> torch.Tensor: + value = np.asarray(rgb_history) + if value.ndim != 5 or value.shape[:2] != (3, 20) or value.shape[-1] != 3: + raise ValueError(f'RGB history must be [3,20,H,W,3], got {value.shape}') + value = np.clip(value, 0, 255).astype(np.uint8, copy=False) + if self.codec_reverse_channels: + value = value[..., ::-1] + value = np.ascontiguousarray(value) + shift = self._reusable_frames(value) if self.codec_incremental else 0 + if shift: + reused = self._codec_cache[2][:, shift // 2:] + latents = torch.cat([reused, self._encode_frames(value[:, 20 - shift:])], dim=1) + else: + latents = self._encode_frames(value) + self._codec_reused_frames = 20 - shift if shift else 0 + self._codec_verify_abs_max = None + if shift and self.codec_incremental_verify: + full = self._encode_frames(value) + self._codec_verify_abs_max = float((full.float() - latents.float()).abs().max()) + if self.codec_incremental and self._plan_key is not None: + self._codec_cache = (self._plan_key, value, latents) + return latents + + def plan(self, *, task: str, domain: str, environment_seed: int, replan_index: int, **kwargs): + self._plan_key = (str(task), str(domain), int(environment_seed), int(replan_index)) + chunk, diagnostics = super().plan( + task=task, domain=domain, environment_seed=environment_seed, + replan_index=replan_index, **kwargs) + diagnostics['codec_channels'] = self.provenance.codec_channels + if self.codec_incremental: + diagnostics['codec_reused_frames'] = self._codec_reused_frames + if self._codec_verify_abs_max is not None: + diagnostics['codec_incremental_abs_max'] = self._codec_verify_abs_max + return chunk, diagnostics diff --git a/release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_v10_runtime.py b/release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_v10_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..18088fa596a8583a0ca2f44837ac5a5355bf2ddf --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_v10_runtime.py @@ -0,0 +1,276 @@ +"""Online-only World-v10 + Action-v10 runtime for official RoboTwin evaluation.""" + +from __future__ import annotations + +import hashlib +import json +import os +import time +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import torch.distributed.checkpoint as dcp +from torch import Tensor + +from mira.codec.codec_model import VideoCodec +from mira.data.batch import VideoActionBatch +from mira.data.world_v6 import preprocess_qwen_rgb +from mira.inference.robotwin_v6_runtime import _empty_codec_batch, _seed +from mira.training.action_v6.config import ActionV6RunConfig +from mira.training.action_v6.factory import build_action_stage +from mira.training.world_v8.checkpoint import checkpoint_fingerprint, load_online_source +from mira.training.world_v8.config import load_config as load_world_config +from mira.world_v6.model import WorldV6System +from mira.world_v6.qwen_current_anchor import FrozenQwenCurrentLanes + + +VIEW_ORDER = ("left", "global", "right") + + +def _load_online_model(model: torch.nn.Module, checkpoint: Path) -> dict[str, Any]: + state = {"model": model.state_dict()} + dcp.load(state, checkpoint_id=checkpoint / "distributed") + model.load_state_dict(state["model"], strict=True) + if not all(bool(torch.isfinite(value).all()) for value in model.parameters()): + raise FloatingPointError(f"non-finite parameter after loading {checkpoint}") + return {"checkpoint_fingerprint": checkpoint_fingerprint(checkpoint)} + + +@dataclass(frozen=True) +class RuntimeProvenance: + action_checkpoint: str + action_step: int + action_branch: str + action_checkpoint_fingerprint: str + world_checkpoint: str + world_step: int + world_branch: str + world_checkpoint_fingerprint: str + codec_sha256: str + view_order: tuple[str, str, str] + world_steps: int + action_steps: int + execute_steps: int + short_history_contract: str + input_color_order: str = "rgb" + # Joint runtimes only: channel handling inside the codec branch and evaluation switches. + codec_channels: str = "as_received" + codec_incremental: bool = False + action_clip_sigma: float | None = None + state_source: str = "command" + + +class BiHubWAMV10Runtime: + """Exact V10 online branch: codec -> masked World -> masked Action.""" + + def __init__(self, *, action_checkpoint: str | Path, device: str = "cuda") -> None: + self.device = torch.device(device) + if self.device.type != "cuda" or not torch.cuda.is_available(): + raise RuntimeError("formal V10 RoboTwin evaluation requires CUDA") + self.action_checkpoint = Path(action_checkpoint).expanduser().resolve() + action_meta = json.loads((self.action_checkpoint / "trainer_state.json").read_text()) + self.config = ActionV6RunConfig.model_validate(action_meta["resolved_config"]) + action_step = int(action_meta["completed_steps"]) + if action_meta.get("architecture") != "bihub-wam-v10-action-h1-50": + raise ValueError("checkpoint is not Action-v10 H1-50") + if action_step != 10_000: + raise ValueError(f"audited V10 deployment selection is step 10000, got {action_step}") + if self.config.training.protocol != "h1_50_gt10k_pred20k": + raise ValueError("unexpected Action-v10 training protocol") + if self.config.data.view_order != list(VIEW_ORDER): + raise ValueError("V10 checkpoint view order differs from official adapter") + + self.action = build_action_stage(self.config).to(self.device).eval().requires_grad_(False) + action_load = _load_online_model(self.action, self.action_checkpoint) + + world_cfg = load_world_config(self.config.artifacts.world_config) + self.world = WorldV6System(world_cfg.model) + world_checkpoint = Path(self.config.artifacts.world_checkpoint).expanduser().resolve() + world_load = load_online_source(self.world, world_checkpoint, expected_step=20_000) + if world_load["checkpoint_fingerprint"] != self.config.artifacts.world_checkpoint_sha256: + raise ValueError("World-v10 checkpoint fingerprint differs from Action binding") + self.world = self.world.to(self.device).eval().requires_grad_(False) + + self.codec = VideoCodec.load_from_checkpoint( + self.config.artifacts.codec_checkpoint, device=self.device + ).eval().requires_grad_(False) + qwen_identity_path = Path(world_cfg.artifacts.qwen_identity) + qwen_identity = json.loads(qwen_identity_path.read_text()) + qwen_root = qwen_identity.get("local_root") + if not qwen_root: + raise ValueError("Qwen identity does not bind a local model root") + self.qwen = FrozenQwenCurrentLanes( + qwen_root, qwen_identity_path, device=self.device + ).eval() + + stats = json.loads(Path(self.config.artifacts.state_stats).read_text()) + self.state_mean = torch.tensor(stats["mean"], device=self.device) + self.state_std = torch.tensor(stats["std"], device=self.device).clamp_min( + float(stats.get("normalization_std_floor", 1.0e-2)) + ) + self.state_clip = float(stats.get("normalization_clip", 5.0)) + action_stats = json.loads(Path(self.config.data.action_stats).read_text()) + self.physical_min = torch.tensor(action_stats["physical_min"], device=self.device).reshape(2, 7) + self.physical_max = torch.tensor(action_stats["physical_max"], device=self.device).reshape(2, 7) + self.provenance = RuntimeProvenance( + action_checkpoint=str(self.action_checkpoint), + action_step=action_step, + action_branch="online", + action_checkpoint_fingerprint=action_load["checkpoint_fingerprint"], + world_checkpoint=str(world_checkpoint), + world_step=20_000, + world_branch="online", + world_checkpoint_fingerprint=world_load["checkpoint_fingerprint"], + codec_sha256=self.config.artifacts.codec_sha256, + view_order=VIEW_ORDER, + world_steps=self.config.world_inference.steps, + action_steps=self.config.action.sampling_steps, + execute_steps=self.config.action.execute_steps, + short_history_contract="right-padded-repeat; context=ceil(state/2); cold-start=1-latent/2-state", + ) + + def provenance_dict(self) -> dict[str, Any]: + return asdict(self.provenance) + + def _normalize_state(self, value: Tensor) -> Tensor: + return ((value.float() - self.state_mean) / self.state_std).clamp( + -self.state_clip, self.state_clip + ) + + @torch.inference_mode() + def encode_history(self, rgb_history: np.ndarray) -> Tensor: + value = np.asarray(rgb_history) + if value.ndim != 5 or value.shape[:2] != (3, 20) or value.shape[-1] != 3: + raise ValueError(f"RGB history must be [3,20,H,W,3], got {value.shape}") + value = np.clip(value, 0, 255).astype(np.uint8, copy=False) + video = torch.from_numpy(value).permute(0, 1, 4, 2, 3).to(self.device) + batch: VideoActionBatch = _empty_codec_batch(video) + self.codec.preprocess_batch(batch) + with torch.autocast("cuda", dtype=torch.bfloat16): + _, output = self.codec.encode(batch.video, trim_video=False) + if output.z.shape != (3, 10, 32, 9, 12): + raise RuntimeError(f"codec returned {tuple(output.z.shape)}") + return output.z + + @torch.inference_mode() + def plan( + self, + *, + rgb_history: np.ndarray, + state_history: np.ndarray, + state_valid: np.ndarray, + instruction: str, + task: str, + domain: str, + environment_seed: int, + replan_index: int, + capture_world: bool = False, + ) -> tuple[np.ndarray, dict[str, Any]]: + started = time.perf_counter() + # Opt-in per-stage latency; synchronizing is the only side effect. + stage_seconds: dict[str, float] | None = {} if os.environ.get("BIHUB_STAGE_TIMING") == "1" else None + stage_mark = [started] + + def mark(stage: str) -> None: + if stage_seconds is not None: + torch.cuda.synchronize(self.device) + now = time.perf_counter() + stage_seconds[stage] = now - stage_mark[0] + stage_mark[0] = now + + context_raw = self.encode_history(rgb_history)[None] + mark("codec") + raw_state = torch.as_tensor(state_history, dtype=torch.float32, device=self.device) + state_mask = torch.as_tensor(state_valid, dtype=torch.bool, device=self.device).reshape(1, 20) + if raw_state.shape != (20, 14) or not 2 <= int(state_mask.sum()) <= 20: + raise ValueError("V10 state history must be [20,14] with 2..20 valid steps") + context_count = min(10, max(1, (int(state_mask.sum()) + 1) // 2)) + context_mask = torch.zeros((1, 10), dtype=torch.bool, device=self.device) + context_mask[:, -context_count:] = True + state = self._normalize_state(raw_state).reshape(1, 20, 2, 7) + + current_rgb = torch.from_numpy(np.asarray(rgb_history)[:, -1]).permute(0, 3, 1, 2) + current_rgb = preprocess_qwen_rgb(current_rgb.to(torch.uint8))[None] + with torch.autocast("cuda", dtype=torch.bfloat16): + qwen_hidden, qwen_mask = self.qwen(current_rgb, [instruction]) + self.qwen.assert_frozen() + mark("qwen") + + world_seed = _seed(task, domain, environment_seed, replan_index, + self.provenance.world_checkpoint_fingerprint, "world") + noise = torch.randn( + (1, 3, 10, 32, 9, 12), + generator=torch.Generator(device=self.device).manual_seed(world_seed), + device=self.device, + ) + with torch.autocast("cuda", dtype=torch.bfloat16): + future_raw = self.world( + z_context_raw=context_raw, + z_future_raw=torch.empty_like(context_raw), + state_history=state, + history_valid=state_mask, + context_valid=context_mask, + future_valid=torch.ones((1, 10), dtype=torch.bool, device=self.device), + view_valid=torch.ones((1, 3), dtype=torch.bool, device=self.device), + qwen_hidden=qwen_hidden, + qwen_mask=qwen_mask, + sample_steps=self.config.world_inference.steps, + sample_noise=noise, + )["sample_future_raw"] + mark("world") + + mean, std = self.config.world_inference.latent_mean, self.config.world_inference.latent_std + current = (context_raw[:, :, -1:] - mean) / std + future = (future_raw - mean) / std + action_seed = _seed(task, domain, environment_seed, replan_index, + self.provenance.action_checkpoint_fingerprint, "action") + action_noise = torch.randn( + (1, 20, 2, 7), + generator=torch.Generator(device=self.device).manual_seed(action_seed), + device=self.device, + ) + with torch.autocast("cuda", dtype=torch.bfloat16): + transitions = self.action.transition_conditioner(current, future) + state_lgr = self.action.state_conditions(state, state_mask) + sampled_normalized = self.action.action_flow.sample( + action_noise, + state_lgr, + transitions, + steps=self.config.action.sampling_steps, + action_valid_mask=torch.ones((1, 20), dtype=torch.bool, device=self.device), + ).float() + mark("action") + normalized = sampled_normalized.clamp(-self.config.action.normalized_action_clip, + self.config.action.normalized_action_clip) + unclamped = self.action.denormalize_action(normalized) + action = unclamped.clamp(self.physical_min, self.physical_max) + if action.shape != (1, 20, 2, 7) or not bool(torch.isfinite(action).all()): + raise FloatingPointError("Action-v10 produced invalid action chunk") + flat = action[0].reshape(20, 14) + execute = int(self.config.action.execute_steps) + normalized_clipped = sampled_normalized != normalized + physical_clipped = unclamped != action + diagnostics = { + "normalized_clip_coordinates": int(normalized_clipped.sum()), + "normalized_clip_execute_coordinates": int(normalized_clipped[:, :execute].sum()), + "physical_clip_coordinates": int(physical_clipped.sum()), + "physical_clip_execute_coordinates": int(physical_clipped[:, :execute].sum()), + "sampled_normalized_abs_max": float(sampled_normalized.abs().max()), + "world_noise_seed": world_seed, + "action_noise_seed": action_seed, + "input_color_order": self.provenance.input_color_order, + "latency_s": time.perf_counter() - started, + "state_valid_count": int(state_mask.sum()), + "context_valid_count": context_count, + "future_delta_rms": float((future_raw - context_raw[:, :, -1:]).square().mean().sqrt()), + "first_action_delta_abs_per_dim": (flat[0] - raw_state[-1]).abs().cpu().tolist(), + } + if stage_seconds is not None: + diagnostics["stage_seconds"] = stage_seconds + if capture_world: + diagnostics["_world_context_raw"] = context_raw[0].float().cpu() + diagnostics["_world_prediction_raw"] = future_raw[0].float().cpu() + return flat.cpu().numpy(), diagnostics diff --git a/release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_v11_runtime.py b/release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_v11_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..1f04f5dc6c23e24d0613b2b97444ffb2b5e74378 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_v11_runtime.py @@ -0,0 +1,120 @@ +"""Online-only World-v11 + Action-v11 runtime for official RoboTwin evaluation.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import torch + +from mira.codec.codec_model import VideoCodec +from mira.data.world_v6 import preprocess_qwen_rgb # re-exported for provenance clarity +from mira.inference.robotwin_v10_runtime import ( + VIEW_ORDER, + BiHubWAMV10Runtime, + RuntimeProvenance, + _load_online_model, +) +from mira.training.action_v6.config import ActionV6RunConfig +from mira.training.action_v6.factory import build_action_stage +from mira.training.world_v8.checkpoint import load_online_source +from mira.training.world_v8.config import load_config as load_world_config +from mira.world_v6.model import WorldV6System +from mira.world_v6.qwen_current_anchor import FrozenQwenCurrentLanes + + +ACTION_ARCHITECTURE = "bihub-wam-v11-action-h1-50-pred8k" +ACTION_PROTOCOL = "h1_50_pred8k_world_v11" +ACTION_STEP = 8_000 +WORLD_ARCHITECTURE = "bihub-world-v11-h1-50-liftpot-continuation-online" +WORLD_STEP = 50_000 + + +class BiHubWAMV11Runtime(BiHubWAMV10Runtime): + """Exact V11 online branch: codec -> masked World-50k -> Action-8k.""" + + def __init__(self, *, action_checkpoint: str | Path, device: str = "cuda") -> None: + self.device = torch.device(device) + if self.device.type != "cuda" or not torch.cuda.is_available(): + raise RuntimeError("formal V11 RoboTwin evaluation requires CUDA") + + self.action_checkpoint = Path(action_checkpoint).expanduser().resolve() + action_meta = json.loads( + (self.action_checkpoint / "trainer_state.json").read_text(encoding="utf-8") + ) + self.config = ActionV6RunConfig.model_validate(action_meta["resolved_config"]) + action_step = int(action_meta["completed_steps"]) + if action_meta.get("architecture") != ACTION_ARCHITECTURE: + raise ValueError(f"checkpoint is not {ACTION_ARCHITECTURE}") + if action_step != ACTION_STEP: + raise ValueError(f"audited V11 deployment selection is step {ACTION_STEP}, got {action_step}") + if self.config.training.protocol != ACTION_PROTOCOL: + raise ValueError("unexpected Action-v11 training protocol") + if self.config.data.view_order != list(VIEW_ORDER): + raise ValueError("V11 checkpoint view order differs from official adapter") + if self.config.artifacts.world_branch != "online": + raise ValueError("V11 deployment requires the online world branch") + + self.action = build_action_stage(self.config).to(self.device).eval().requires_grad_(False) + action_load = _load_online_model(self.action, self.action_checkpoint) + + world_checkpoint = Path(self.config.artifacts.world_checkpoint).expanduser().resolve() + world_meta = json.loads( + (world_checkpoint / "trainer_state.json").read_text(encoding="utf-8") + ) + if world_meta.get("architecture") != WORLD_ARCHITECTURE: + raise ValueError(f"bound world checkpoint is not {WORLD_ARCHITECTURE}") + if int(world_meta.get("completed_steps", -1)) != WORLD_STEP: + raise ValueError("bound V11 world checkpoint is not step 50000") + + world_cfg = load_world_config(self.config.artifacts.world_config) + self.world = WorldV6System(world_cfg.model) + world_load = load_online_source(self.world, world_checkpoint, expected_step=WORLD_STEP) + if world_load["checkpoint_fingerprint"] != self.config.artifacts.world_checkpoint_sha256: + raise ValueError("World-v11 checkpoint fingerprint differs from Action binding") + self.world = self.world.to(self.device).eval().requires_grad_(False) + + self.codec = VideoCodec.load_from_checkpoint( + self.config.artifacts.codec_checkpoint, device=self.device + ).eval().requires_grad_(False) + qwen_identity_path = Path(world_cfg.artifacts.qwen_identity) + qwen_identity = json.loads(qwen_identity_path.read_text(encoding="utf-8")) + qwen_root = qwen_identity.get("local_root") + if not qwen_root: + raise ValueError("Qwen identity does not bind a local model root") + self.qwen = FrozenQwenCurrentLanes( + qwen_root, qwen_identity_path, device=self.device + ).eval() + + stats = json.loads(Path(self.config.artifacts.state_stats).read_text(encoding="utf-8")) + self.state_mean = torch.tensor(stats["mean"], device=self.device) + self.state_std = torch.tensor(stats["std"], device=self.device).clamp_min( + float(stats.get("normalization_std_floor", 1.0e-2)) + ) + self.state_clip = float(stats.get("normalization_clip", 5.0)) + action_stats = json.loads(Path(self.config.data.action_stats).read_text(encoding="utf-8")) + self.physical_min = torch.tensor( + action_stats["physical_min"], device=self.device + ).reshape(2, 7) + self.physical_max = torch.tensor( + action_stats["physical_max"], device=self.device + ).reshape(2, 7) + + self.provenance = RuntimeProvenance( + action_checkpoint=str(self.action_checkpoint), + action_step=action_step, + action_branch="online", + action_checkpoint_fingerprint=action_load["checkpoint_fingerprint"], + world_checkpoint=str(world_checkpoint), + world_step=WORLD_STEP, + world_branch="online", + world_checkpoint_fingerprint=world_load["checkpoint_fingerprint"], + codec_sha256=self.config.artifacts.codec_sha256, + view_order=VIEW_ORDER, + world_steps=self.config.world_inference.steps, + action_steps=self.config.action.sampling_steps, + execute_steps=self.config.action.execute_steps, + short_history_contract=( + "right-padded-repeat; context=ceil(state/2); cold-start=1-latent/2-state" + ), + ) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_v12_runtime.py b/release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_v12_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..74da56a15e08bfaadbcc07b8304bf1034210b86f --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_v12_runtime.py @@ -0,0 +1,146 @@ +"""Online-only World-v12 + Action-v12 runtime for official RoboTwin evaluation.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import torch + +from mira.codec.codec_model import VideoCodec +from mira.inference.robotwin_v10_runtime import ( + VIEW_ORDER, + BiHubWAMV10Runtime, + RuntimeProvenance, + _load_online_model, +) +from mira.training.action_v6.config import ActionV6RunConfig +from mira.training.world_v8.checkpoint import load_online_source +from mira.world_v6.model import WorldV6System +from mira.world_v6.qwen_current_anchor import FrozenQwenCurrentLanes +from mira.joint.paths import workspace_path +from mira.action_v6.model import BiHubWAMActionStage +from mira.world_v6.config import WorldV6ModelConfig +from mira.world_v6.state_encoder import StateEncoderV6 + + +ACTION_CONTRACTS = { + "eval_aligned_epoch_world_v12": ( + "bihub-wam-v12-action-eval-aligned-epoch", + 5_754, + ), + "eval_aligned_continue4_world_v12": ( + "bihub-wam-v13-action-eval-aligned-continue4epoch", + 23_016, + ), +} +WORLD_ARCHITECTURE = "bihub-world-v12-largebatch-remaining-online" +WORLD_STEP = 25_066 + + +class BiHubWAMV12Runtime(BiHubWAMV10Runtime): + """Exact V12 online branch selected and bound by the completed Action-v12 epoch.""" + + def __init__(self, *, action_checkpoint: str | Path, device: str = "cuda", research: bool = False) -> None: + self.device = torch.device(device) + if self.device.type != "cuda" or not torch.cuda.is_available(): + raise RuntimeError("formal V12 RoboTwin evaluation requires CUDA") + + self.action_checkpoint = Path(action_checkpoint).expanduser().resolve() + action_meta = json.loads( + (self.action_checkpoint / "trainer_state.json").read_text(encoding="utf-8") + ) + self.config = ActionV6RunConfig.model_validate(action_meta["resolved_config"]) + action_step = int(action_meta["completed_steps"]) + action_protocol = self.config.training.protocol + if action_protocol not in ACTION_CONTRACTS: + raise ValueError("unexpected eval-aligned Action training protocol") + action_architecture, expected_action_step = ACTION_CONTRACTS[action_protocol] + if action_meta.get("architecture") != action_architecture: + raise ValueError(f"checkpoint is not {action_architecture}") + if not research and (action_step != expected_action_step or action_step != self.config.training.steps): + raise ValueError( + "audited eval-aligned deployment requires completed step " + f"{expected_action_step}, got {action_step}" + ) + if self.config.data.view_order != list(VIEW_ORDER): + raise ValueError("V12 checkpoint view order differs from official adapter") + if self.config.artifacts.world_branch != "online": + raise ValueError("V12 deployment requires the online world branch") + + self.action = BiHubWAMActionStage( + state_encoder=StateEncoderV6(), delta_scale=torch.ones(3, 10, 32), + action_mean=torch.zeros(14), action_std=torch.ones(14), + loss_mode=self.config.action.loss, + ).to(self.device).eval().requires_grad_(False) + action_load = _load_online_model(self.action, self.action_checkpoint) + + world_checkpoint = workspace_path(self.config.artifacts.world_checkpoint) + world_meta = json.loads( + (world_checkpoint / "trainer_state.json").read_text(encoding="utf-8") + ) + if world_meta.get("architecture") != WORLD_ARCHITECTURE: + raise ValueError(f"bound world checkpoint is not {WORLD_ARCHITECTURE}") + if int(world_meta.get("completed_steps", -1)) != WORLD_STEP: + raise ValueError(f"bound V12 world checkpoint is not step {WORLD_STEP}") + + world_cfg = world_meta["resolved_config"] + self.world = WorldV6System(WorldV6ModelConfig.model_validate(world_cfg["model"])) + world_load = load_online_source(self.world, world_checkpoint, expected_step=WORLD_STEP) + if world_load["checkpoint_fingerprint"] != self.config.artifacts.world_checkpoint_sha256: + raise ValueError("World-v12 checkpoint fingerprint differs from Action binding") + self.world = self.world.to(self.device).eval().requires_grad_(False) + + self.codec = VideoCodec.load_from_checkpoint( + workspace_path(self.config.artifacts.codec_checkpoint), device=self.device + ).eval().requires_grad_(False) + qwen_identity_path = workspace_path(world_cfg["artifacts"]["qwen_identity"]) + qwen_identity = json.loads(qwen_identity_path.read_text(encoding="utf-8")) + qwen_root = qwen_identity.get("local_root") + if not qwen_root: + raise ValueError("Qwen identity does not bind a local model root") + qwen_root = workspace_path(qwen_root) + qwen_identity["local_root"] = str(qwen_root) + self.qwen = FrozenQwenCurrentLanes( + qwen_root, qwen_identity, device=self.device + ).eval() + + stats = json.loads(workspace_path(self.config.artifacts.state_stats).read_text(encoding="utf-8")) + self.state_mean = torch.tensor(stats["mean"], device=self.device) + self.state_std = torch.tensor(stats["std"], device=self.device).clamp_min( + float(stats.get("normalization_std_floor", 1.0e-2)) + ) + self.state_clip = float(stats.get("normalization_clip", 5.0)) + action_stats = json.loads(workspace_path(self.config.data.action_stats).read_text(encoding="utf-8")) + self.physical_min = torch.tensor( + action_stats["physical_min"], device=self.device + ).reshape(2, 7) + self.physical_max = torch.tensor( + action_stats["physical_max"], device=self.device + ).reshape(2, 7) + + self.provenance = RuntimeProvenance( + action_checkpoint=str(self.action_checkpoint), + action_step=action_step, + action_branch="online", + action_checkpoint_fingerprint=action_load["checkpoint_fingerprint"], + world_checkpoint=str(world_checkpoint), + world_step=WORLD_STEP, + world_branch="online", + world_checkpoint_fingerprint=world_load["checkpoint_fingerprint"], + codec_sha256=self.config.artifacts.codec_sha256, + view_order=VIEW_ORDER, + world_steps=self.config.world_inference.steps, + action_steps=self.config.action.sampling_steps, + execute_steps=self.config.action.execute_steps, + short_history_contract=( + "right-padded-repeat; context=ceil(state/2); cold-start=1-latent/2-state" + ), + ) + + +class BiHubWAMV12ResearchRuntime(BiHubWAMV12Runtime): + """Explicit research selection; release architecture and World binding remain checked.""" + + def __init__(self, *, action_checkpoint: str | Path, device: str = "cuda") -> None: + super().__init__(action_checkpoint=action_checkpoint, device=device, research=True) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_v6_runtime.py b/release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_v6_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..1d314f58ecc5cf8612f2e86a2c4acef0e71cf8a7 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/inference/robotwin_v6_runtime.py @@ -0,0 +1,374 @@ +"""Single-GPU EMA runtime for official RoboTwin/XPolicyLab evaluation. + +The training checkpoints are eight-way FSDP2/DCP directories. This module +restores their canonical model state plus EMA trainable state into ordinary +single-process modules without modifying either checkpoint. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import torch.distributed.checkpoint as dcp +from torch import Tensor + +from mira.codec.codec_model import VideoCodec +from mira.data.batch import VideoActionBatch +from mira.data.world_v6 import preprocess_qwen_rgb +from mira.training.action_v6.config import ActionV6RunConfig +from mira.training.action_v6.factory import build_action_stage +from mira.training.world_v6.config import load_config as load_world_config +from mira.training.world_v6.train import _load_resampler_selection +from mira.world_model.actions_config import ActionConfig, ActionTensors +from mira.world_v6.migration import load_migrated_system +from mira.world_v6.qwen_current_anchor import FrozenQwenCurrentLanes + + +VIEW_ORDER = ("left", "global", "right") + + +def _sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + while chunk := handle.read(8 << 20): + digest.update(chunk) + return digest.hexdigest() + + +def _checkpoint_fingerprint(checkpoint: Path) -> str: + digest = hashlib.sha256() + for relative in ("trainer_state.json", "distributed/.metadata"): + path = checkpoint / relative + if not path.is_file(): + raise FileNotFoundError(f"incomplete checkpoint: {path}") + digest.update(relative.encode()) + digest.update(_sha256_file(path).encode()) + return digest.hexdigest() + + +def _load_model_and_ema(model: torch.nn.Module, checkpoint: Path) -> dict[str, Any]: + """Load canonical model tensors and EMA tensors whose saved names contain wrappers.""" + + reader = dcp.FileSystemReader(checkpoint / "distributed") + metadata = reader.read_metadata() + parameters = dict(model.named_parameters()) + ema_state: dict[str, Tensor] = {} + for key in metadata.state_dict_metadata: + if not key.startswith("ema.state."): + continue + checkpoint_name = key.removeprefix("ema.state.") + canonical_name = checkpoint_name.replace("._checkpoint_wrapped_module.", ".") + if canonical_name not in parameters: + raise KeyError(f"EMA checkpoint parameter is absent from runtime: {canonical_name}") + ema_state[checkpoint_name] = torch.empty_like(parameters[canonical_name]) + + state: dict[str, Any] = { + "model": model.state_dict(), + "ema": {"state": ema_state, "count": 0.0}, + } + dcp.load(state, checkpoint_id=checkpoint / "distributed") + model.load_state_dict(state["model"], strict=True) + for checkpoint_name, value in state["ema"]["state"].items(): + canonical_name = checkpoint_name.replace("._checkpoint_wrapped_module.", ".") + parameters[canonical_name].data.copy_(value) + if not all(bool(torch.isfinite(parameter).all()) for parameter in model.parameters()): + raise FloatingPointError(f"non-finite parameter after loading {checkpoint}") + return { + "checkpoint_fingerprint": _checkpoint_fingerprint(checkpoint), + "ema_parameter_tensors": len(ema_state), + } + + +def _empty_codec_batch(video: Tensor) -> VideoActionBatch: + action_config = ActionConfig(valid_keys=[], source_fps=20, target_fps=20) + actions = ActionTensors(action_config, batch_size=video.shape[0]) + actions.key_presses = torch.zeros(video.shape[0], video.shape[1], 0, dtype=torch.int32) + actions.mouse_movements = torch.zeros(video.shape[0], video.shape[1], 2) + return VideoActionBatch(video=video, actions=actions) + + +def _seed(task: str, domain: str, environment_seed: int, replan: int, sha: str, role: str) -> int: + payload = f"{task}\0{domain}\0{environment_seed}\0{replan}\0{sha}\0{role}" + return int.from_bytes(hashlib.sha256(payload.encode()).digest()[:8], "big") % (2**63 - 1) + + +@dataclass(frozen=True) +class RuntimeProvenance: + action_checkpoint: str + action_step: int + action_branch: str + action_artifact_sha256: str + action_checkpoint_fingerprint: str + world_checkpoint: str + world_step: int + world_branch: str + world_artifact_sha256: str + world_checkpoint_fingerprint: str + codec_sha256: str + view_order: tuple[str, str, str] + world_steps: int + action_steps: int + execute_steps: int + + +class BiHubWAMRuntime: + """Exact 3-view codec -> World EMA -> Action EMA inference pipeline.""" + + def __init__( + self, + *, + action_checkpoint: str | Path, + device: str | torch.device = "cuda", + ) -> None: + self.device = torch.device(device) + if self.device.type != "cuda" or not torch.cuda.is_available(): + raise RuntimeError("formal BiHub-WAM RoboTwin evaluation requires CUDA") + self.action_checkpoint = Path(action_checkpoint).expanduser().resolve() + action_metadata = json.loads( + (self.action_checkpoint / "trainer_state.json").read_text(encoding="utf-8") + ) + action_step = int(action_metadata["completed_steps"]) + self.config = ActionV6RunConfig.model_validate(action_metadata["resolved_config"]) + action_protocol = self.config.training.protocol + if action_protocol == "compressed_22k": + if action_step != 22000: + raise ValueError("compressed_22k evaluation requires terminal step 22000") + elif action_protocol == "continuation_100k": + if not (22000 < action_step <= self.config.training.steps): + raise ValueError( + "continuation_100k evaluation requires a checkpoint after step 22000 " + f"and no later than {self.config.training.steps}, got {action_step}" + ) + if self.config.training.continuation_resume_step != 22000: + raise ValueError("continuation_100k must descend from the audited step-22000 branch") + elif action_protocol == "corrective_v7_round0": + if not (0 < action_step <= self.config.training.steps): + raise ValueError( + "corrective_v7_round0 evaluation requires a completed corrective checkpoint, " + f"got step {action_step}" + ) + if ( + self.config.checkpoint.initialize_from_ema is None + or Path(self.config.checkpoint.initialize_from_ema).name + != "action-checkpoint-60000" + ): + raise ValueError("corrective Action-v7 must descend from the audited step-60k EMA") + if action_metadata.get("architecture") != "bihub-wam-v7-action-corrective": + raise ValueError("corrective checkpoint architecture identity is missing") + else: + raise ValueError(f"unsupported formal Action protocol: {action_protocol}") + + self.action = build_action_stage(self.config).to(self.device).eval() + action_load = _load_model_and_ema(self.action, self.action_checkpoint) + + world_config = load_world_config(self.config.artifacts.world_config) + selection = json.loads(Path(world_config.artifacts.resampler_selection).read_text()) + self.world = load_migrated_system(selection["system_weights"], world_config.model) + _load_resampler_selection(self.world, world_config.artifacts.resampler_selection) + self.world = self.world.to(self.device).eval() + self.world_checkpoint = Path(self.config.artifacts.world_checkpoint).expanduser().resolve() + world_metadata = json.loads( + (self.world_checkpoint / "trainer_state.json").read_text(encoding="utf-8") + ) + if int(world_metadata["completed_steps"]) != 97314: + raise ValueError("formal evaluation is locked to World step 97314") + world_load = _load_model_and_ema(self.world, self.world_checkpoint) + + self.codec = VideoCodec.load_from_checkpoint( + self.config.artifacts.codec_checkpoint, device=self.device + ).eval() + self.qwen = FrozenQwenCurrentLanes( + world_config.artifacts.qwen_root, + world_config.artifacts.qwen_identity, + device=self.device, + ).eval() + + state_stats = json.loads(Path(self.config.artifacts.state_stats).read_text()) + self.state_mean = torch.tensor(state_stats["mean"], dtype=torch.float32, device=self.device) + self.state_std = torch.tensor(state_stats["std"], dtype=torch.float32, device=self.device).clamp_min( + float(state_stats.get("normalization_std_floor", 1.0e-2)) + ) + self.state_clip = float(state_stats.get("normalization_clip", 5.0)) + action_stats = json.loads(Path(self.config.data.action_stats).read_text()) + self.physical_min = torch.tensor( + action_stats["physical_min"], dtype=torch.float32, device=self.device + ).reshape(2, 7) + self.physical_max = torch.tensor( + action_stats["physical_max"], dtype=torch.float32, device=self.device + ).reshape(2, 7) + + self.provenance = RuntimeProvenance( + action_checkpoint=str(self.action_checkpoint), + action_step=action_step, + action_branch="ema", + action_artifact_sha256=str(action_metadata["artifact_identity_sha256"]), + action_checkpoint_fingerprint=str(action_load["checkpoint_fingerprint"]), + world_checkpoint=str(self.world_checkpoint), + world_step=97314, + world_branch="ema", + world_artifact_sha256=str(self.config.artifacts.world_checkpoint_sha256), + world_checkpoint_fingerprint=str(world_load["checkpoint_fingerprint"]), + codec_sha256=str(self.config.artifacts.codec_sha256), + view_order=VIEW_ORDER, + world_steps=10, + action_steps=10, + execute_steps=8, + ) + + def _normalize_state(self, state_history: Tensor) -> Tensor: + return ((state_history.float() - self.state_mean) / self.state_std).clamp( + -self.state_clip, self.state_clip + ) + + @torch.inference_mode() + def encode_history(self, rgb_history: np.ndarray) -> Tensor: + """Encode uint8 RGB history shaped [3,20,H,W,3] into raw latents.""" + + value = np.asarray(rgb_history) + if value.ndim != 5 or value.shape[:2] != (3, 20) or value.shape[-1] != 3: + raise ValueError(f"RGB history must be [3,20,H,W,3], got {value.shape}") + if value.dtype != np.uint8: + value = np.clip(value, 0, 255).astype(np.uint8) + video = torch.from_numpy(value).permute(0, 1, 4, 2, 3).to(self.device) + batch = _empty_codec_batch(video) + self.codec.preprocess_batch(batch) + with torch.autocast("cuda", dtype=torch.bfloat16): + _, output = self.codec.encode(batch.video, trim_video=False) + latent = output.z + if latent.shape != (3, 10, 32, 9, 12) or not bool(torch.isfinite(latent).all()): + raise RuntimeError(f"codec returned invalid latent shape {tuple(latent.shape)}") + return latent + + @torch.inference_mode() + def plan( + self, + *, + rgb_history: np.ndarray, + state_history: np.ndarray, + history_valid: np.ndarray, + instruction: str, + task: str, + domain: str, + environment_seed: int, + replan_index: int, + ) -> tuple[np.ndarray, dict[str, Any]]: + started = time.perf_counter() + context_raw = self.encode_history(rgb_history)[None] + state_raw = torch.as_tensor(state_history, dtype=torch.float32, device=self.device) + if state_raw.shape != (20, 14): + raise ValueError(f"state history must be [20,14], got {tuple(state_raw.shape)}") + state = self._normalize_state(state_raw).reshape(1, 20, 2, 7) + valid = torch.as_tensor(history_valid, dtype=torch.bool, device=self.device).reshape(1, 20) + + current_rgb = torch.from_numpy(np.asarray(rgb_history)[:, -1]).permute(0, 3, 1, 2) + current_rgb = preprocess_qwen_rgb(current_rgb.to(torch.uint8))[None] + with torch.autocast("cuda", dtype=torch.bfloat16): + qwen_hidden, qwen_mask = self.qwen(current_rgb, [instruction]) + self.qwen.assert_frozen() + + world_seed = _seed( + task, + domain, + int(environment_seed), + int(replan_index), + self.config.artifacts.world_checkpoint_sha256, + "world", + ) + world_generator = torch.Generator(device=self.device).manual_seed(world_seed) + world_noise = torch.randn( + (1, 3, 10, 32, 9, 12), generator=world_generator, device=self.device + ) + with torch.autocast("cuda", dtype=torch.bfloat16): + future_raw = self.world( + z_context_raw=context_raw, + z_future_raw=torch.empty_like(context_raw), + state_history=state, + history_valid=valid, + future_valid=torch.ones(1, 10, dtype=torch.bool, device=self.device), + view_valid=torch.ones(1, 3, dtype=torch.bool, device=self.device), + qwen_hidden=qwen_hidden, + qwen_mask=qwen_mask, + sample_steps=10, + sample_noise=world_noise, + )["sample_future_raw"] + if not bool(torch.isfinite(future_raw).all()): + raise FloatingPointError("World EMA produced non-finite future latents") + + latent_mean = float(self.config.world_inference.latent_mean) + latent_std = float(self.config.world_inference.latent_std) + current = (context_raw[:, :, -1:] - latent_mean) / latent_std + future = (future_raw - latent_mean) / latent_std + action_seed = _seed( + task, + domain, + int(environment_seed), + int(replan_index), + str(self.provenance.action_checkpoint_fingerprint), + "action", + ) + action_generator = torch.Generator(device=self.device).manual_seed(action_seed) + noise = torch.randn((1, 20, 2, 7), generator=action_generator, device=self.device) + with torch.autocast("cuda", dtype=torch.bfloat16): + transitions = self.action.transition_conditioner(current, future) + state_lgr = self.action.state_conditions(state, valid) + normalized = self.action.action_flow.sample( + noise, + state_lgr, + transitions, + steps=10, + action_valid_mask=torch.ones(1, 20, dtype=torch.bool, device=self.device), + ) + sampled_normalized = normalized.float() + normalized_limit = float(self.config.action.normalized_action_clip) + normalized = sampled_normalized.clamp( + -float(self.config.action.normalized_action_clip), + float(self.config.action.normalized_action_clip), + ) + action_unclamped = self.action.denormalize_action(normalized) + action = action_unclamped.clamp(self.physical_min, self.physical_max) + if action.shape != (1, 20, 2, 7) or not bool(torch.isfinite(action).all()): + raise FloatingPointError("Action EMA produced invalid action chunk") + normalized_flat = sampled_normalized[0].reshape(20, 14) + normalized_clipped = normalized_flat.abs() >= normalized_limit + physical_flat = action_unclamped[0].reshape(20, 14) + physical_clipped = (physical_flat < self.physical_min.reshape(14)) | ( + physical_flat > self.physical_max.reshape(14) + ) + action_flat = action[0].reshape(20, 14) + state_normalized = self._normalize_state(state_raw) + step_delta_abs = torch.diff(action_flat, dim=0).abs() + second_delta_abs = torch.diff(action_flat, n=2, dim=0).abs() + executed = action_flat[: self.config.action.execute_steps] + executed_step_delta_abs = torch.diff(executed, dim=0).abs() + return action_flat.cpu().numpy(), { + "latency_s": time.perf_counter() - started, + "future_delta_rms": float((future_raw - context_raw[:, :, -1:]).square().mean().sqrt()), + "state_valid_count": int(valid.sum()), + "state_normalized_abs_max": float(state_normalized.abs().max()), + "normalized_clip_rate": float(normalized_clipped.float().mean()), + "normalized_clip_rate_per_dim": normalized_clipped.float().mean(0).cpu().tolist(), + "physical_clip_rate": float(physical_clipped.float().mean()), + "physical_clip_rate_per_dim": physical_clipped.float().mean(0).cpu().tolist(), + "action_min_per_dim": action_flat.min(0).values.cpu().tolist(), + "action_max_per_dim": action_flat.max(0).values.cpu().tolist(), + "chunk_step_delta_abs_mean_per_dim": step_delta_abs.mean(0).cpu().tolist(), + "chunk_step_delta_abs_max_per_dim": step_delta_abs.max(0).values.cpu().tolist(), + "chunk_second_delta_abs_mean_per_dim": second_delta_abs.mean(0).cpu().tolist(), + "chunk_second_delta_abs_max_per_dim": second_delta_abs.max(0).values.cpu().tolist(), + "executed_step_delta_abs_mean_per_dim": ( + executed_step_delta_abs.mean(0).cpu().tolist() + ), + "executed_step_delta_abs_max_per_dim": ( + executed_step_delta_abs.max(0).values.cpu().tolist() + ), + "first_action_delta_abs_per_dim": ( + action_flat[0] - state_raw[-1] + ).abs().cpu().tolist(), + } diff --git a/release-20261107/source/workspace_joint/mira/src/mira/inference/rollout.py b/release-20261107/source/workspace_joint/mira/src/mira/inference/rollout.py new file mode 100644 index 0000000000000000000000000000000000000000..1ae566df6c787b5716b6cc265335c9c0a4dfa8ec --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/inference/rollout.py @@ -0,0 +1,168 @@ +"""Offline autoregressive rollout of the world model, without the final decode. + +:func:`rollout` reproduces the denoising loop of ``LatentWorldModel.inference`` (and its multiplayer +counterpart ``MultiWrapperWorldModel.inference``) but stops before decoding latents back to video. It +is the shared core of the latency benchmark (:mod:`scripts.bench_wm_speed`) and the offline-eval +denoise-speed measurement, and it is the determinism anchor the equality harness depends on: a fixed +seed + ``noise_level=0.0`` + a fixed schedule reproduces the generated latents exactly. + +The per-step action-offset arithmetic is *not* re-derived here -- it is read off the model so the two +model variants stay the single source of truth: + +* single-player (:class:`LatentWorldModel`): the action window starts at ``off = atd - 1``, and +* multiplayer (:class:`MultiWrapperWorldModel`): the window starts at offset ``0`` and the per-player + encoded actions are combined via the model's own ``_combine_player_actions``. + +This mirrors each model's ``inference`` method exactly; if those loops change, this helper must follow. +""" + +from __future__ import annotations + +import time +from typing import TYPE_CHECKING, cast + +import torch +from einops import rearrange +from torch import Tensor +from tqdm import tqdm + +from mira.data.batch import VideoActionBatch +from mira.world_model.config import WorldModelInferenceConfig + +if TYPE_CHECKING: + from mira.world_model.latent_world_model import LatentWorldModel + from mira.world_model.multi_wrapper_world_model import MultiWrapperWorldModel + + # Both variants present the surface ``rollout`` reads (config, codec, encode_video, + # denoise_streaming, action_encoder, device, ...); the wrapper adds tiling + action combination. + # They share no typed base, so the public type is their union and we cast for multi-only access. + WorldModelLike = LatentWorldModel | MultiWrapperWorldModel + + +def _is_multiplayer(model: WorldModelLike) -> bool: + """Whether ``model`` is the multiplayer wrapper (it alone owns an inner ``single_world_model``).""" + return hasattr(model, "single_world_model") + + +def _inner_model(model: WorldModelLike) -> LatentWorldModel: + """The single-player model that owns the codec / transformer (the wrapper's inner model, or itself).""" + if _is_multiplayer(model): + return cast("MultiWrapperWorldModel", model).single_world_model + return cast("LatentWorldModel", model) + + +def _encode_window_actions( + model: WorldModelLike, + inner: LatentWorldModel, + batch: VideoActionBatch, + start: int, + window_size: int, +) -> Tensor: + """Encode the action conditioning for the denoise window starting at latent index ``start``. + + Delegates the offset to the model variant: single-player applies the ``off = atd - 1`` shift, + multiplayer slices at offset ``0`` and combines the per-player streams. Returns ``(b, t_a, d)`` + conditioning ready for ``denoise_streaming``. + """ + atd = inner.action_temporal_downsampling + if _is_multiplayer(model): + action_start = start * atd + action_end = (start + window_size - 1) * atd + a_flat = inner.action_encoder(batch.actions.slice_time(action_start, action_end)).clone() + return cast("MultiWrapperWorldModel", model)._combine_player_actions(a_flat) + + off = atd - 1 + action_start = start * atd + off + action_end = (start + window_size - 1) * atd + off + # ``.clone()`` because the slice is a view and torch.compile dislikes aliasing the kv-cache inputs. + return inner.action_encoder(batch.actions.slice_time(action_start, action_end)).clone() + + +@torch.no_grad() +def rollout( + model: WorldModelLike, + batch: VideoActionBatch, + config: WorldModelInferenceConfig | None = None, + *, + n_frames: int | None = None, + progress_bar: bool = False, +) -> Tensor: + """Autoregressively denoise a clip into latents, skipping the decode step. + + Reproduces ``model.inference`` up to (but not including) ``decode_to_video``. Deterministic given + the global RNG seed, ``config.noise_level`` and ``config.schedule_type``. + + Args: + model: A :class:`LatentWorldModel` or :class:`MultiWrapperWorldModel`. + batch: The bootstrap clip; its first ``n_context_latents`` frames seed the rollout. + config: Sampling knobs; the model's defaults are used when ``None``. + n_frames: Cap the number of denoised latent frames (windows). ``None`` rolls the whole clip. + Used by the latency benchmark to time a fixed number of frames. + progress_bar: Show a tqdm progress bar over the rollout. + + Returns: + The generated latents. Single-player: ``(b, t, h, w, c)``. Multiplayer: the vertically tiled + ``(b, t, p*h, w, c)`` buffer the loop operates on (not split back per player). + """ + if config is None: + config = WorldModelInferenceConfig() + + multi = _is_multiplayer(model) + inner = _inner_model(model) + + inner.codec.preprocess_batch(batch) + batch = batch.to(model.device) + z = inner.encode_video(batch).clone() # clone because of torch.compile + if multi: + z = rearrange(z, "(b p) t h w c -> b t (p h) w c", p=cast("MultiWrapperWorldModel", model).n_players) + + z_t = torch.randn_like(z) + z_t[:, : inner.n_context_latents] = z[:, : inner.n_context_latents] + + window_size = inner.n_context_latents + 1 + n_iters = z.shape[1] - window_size + 1 + if n_frames is not None: + n_iters = min(n_iters, n_frames) + + streaming_kv_caches = None + for start in tqdm(range(n_iters), desc="Diffusion rollout", disable=not progress_bar): + current_a = _encode_window_actions(model, inner, batch, start, window_size) + z_t[:, start : start + window_size], streaming_kv_caches = inner.denoise_streaming( + z_t[:, start : start + window_size], + current_a, + n_diffusion_steps=config.n_diffusion_steps, + noise_level=config.noise_level, + streaming_kv_caches=streaming_kv_caches, + schedule_type=config.schedule_type, + ) + + return z_t + + +def measure_rollout_speed( + model: WorldModelLike, + batch: VideoActionBatch, + config: WorldModelInferenceConfig, + n_frames: int, +) -> dict[str, float]: + """Time :func:`rollout` over ``n_frames`` latent frames (batch size 1, no decode / metrics). + + This is the per-stream latency that matters for the interactive server, as opposed to end-to-end + eval throughput (which is dominated by decode and metric computation). The caller is expected to + size the clip so the rollout produces at least ``n_frames`` windows; the timing divides by + ``n_frames``. Run a warmup call first so compilation / cudnn autotune does not skew the result. + + Returns: + ``{"denoise_ms_per_latent_frame": ..., "denoise_latent_fps": ...}``. + """ + if torch.cuda.is_available(): + torch.cuda.synchronize() + t0 = time.perf_counter() + rollout(model, batch, config, n_frames=n_frames) + if torch.cuda.is_available(): + torch.cuda.synchronize() + s_per_frame = (time.perf_counter() - t0) / n_frames + return { + "denoise_ms_per_latent_frame": s_per_frame * 1000, + "denoise_latent_fps": 1 / s_per_frame, + } diff --git a/release-20261107/source/workspace_joint/mira/src/mira/joint/__init__.py b/release-20261107/source/workspace_joint/mira/src/mira/joint/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f1e98508e7abed3fa2233aa2c506e02de840e032 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/joint/__init__.py @@ -0,0 +1,5 @@ +"""End-to-end World + Action training without derived-data caches.""" + +from .model import JointWorldActionModel + +__all__ = ["JointWorldActionModel"] diff --git a/release-20261107/source/workspace_joint/mira/src/mira/joint/deployment.py b/release-20261107/source/workspace_joint/mira/src/mira/joint/deployment.py new file mode 100644 index 0000000000000000000000000000000000000000..2df8674b75beee72447870d328352e6365130a33 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/joint/deployment.py @@ -0,0 +1,53 @@ +"""Paired export: action MUST use the jointly updated World state encoder.""" +from pathlib import Path +import json + +import torch +from safetensors.torch import save_file + +from mira.action_v6.model import BiHubWAMActionStage +from mira.data.robotwin_wam_schema import sha256_file +from mira.joint.model import JointWorldActionModel +from mira.joint.image_contract import checkpoint_image_contract +from mira.world_v6.config import WorldV6ModelConfig +from mira.world_v6.model import WorldV6System +from mira.world_v6.state_encoder import StateEncoderV6 + + +def build_joint(config: dict) -> JointWorldActionModel: + world = WorldV6System(WorldV6ModelConfig.model_validate(config['world_model'])) + action = BiHubWAMActionStage( + state_encoder=StateEncoderV6(), delta_scale=torch.ones(3, 10, 32), + action_mean=torch.zeros(14), action_std=torch.ones(14), loss_mode=config['action_loss'], + ) + return JointWorldActionModel(world, action) + + +def paired_state_dicts(state: dict) -> tuple[dict, dict]: + world = {key.removeprefix('world.'): value for key, value in state.items() if key.startswith('world.')} + action = {key.removeprefix('action.'): value for key, value in state.items() if key.startswith('action.')} + live = {key: value for key, value in world.items() if key.startswith('state_encoder.')} + if not live: + raise ValueError('Joint export has no live World state encoder') + if any(key.startswith('state_encoder.') for key in action): + raise ValueError('Unexpected stale action state encoder in joint checkpoint') + action.update(live) + return world, action + + +def save_pair(state: dict, metadata: dict, output: Path, fingerprint: str) -> None: + contract = checkpoint_image_contract(metadata) + output.mkdir(parents=True, exist_ok=False) + world, action = paired_state_dicts(state) + for name, values in [('world', world), ('action', action)]: + save_file({key: value.detach().cpu().contiguous() for key, value in values.items()}, + output / f'{name}.safetensors') + deployment = { + 'format_version': 1, 'architecture': metadata['architecture'], + 'completed_steps': metadata['completed_steps'], 'joint_checkpoint_fingerprint': fingerprint, + 'resolved_config': metadata['resolved_config'], 'artifact_identity': metadata['artifact_identity'], + 'recommended_input_color_order': contract['model_input_color_order'] if contract else 'bgr', + 'exported_weights': metadata.get('exported_weights', 'model'), + 'sha256': {name: sha256_file(output / name) for name in ('world.safetensors', 'action.safetensors')}, + } + (output / 'deployment.json').write_text(json.dumps(deployment, indent=2) + '\n') diff --git a/release-20261107/source/workspace_joint/mira/src/mira/joint/image_contract.py b/release-20261107/source/workspace_joint/mira/src/mira/joint/image_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..34da499d2374585bc4f36ef163e97f0478570edf --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/joint/image_contract.py @@ -0,0 +1,87 @@ +"""Semantic image contract shared by training, export and deployment.""" + +RGB_IMAGE_CONTRACT = { + "version": "robotwin-official-rgb-v1", + "decoder": "XPolicyLab.utils.process_data.decode_image_bit", + "stored_formats": "legacy_unmarked_and_XPL-RGB1", + "model_input_color_order": "rgb", + "branches": ["codec", "qwen"], + "derived_feature_cache": "disabled", +} + + +# The frozen LingBot codec (step 125000) and the World latent space were fit on +# reversed-channel frames. Feeding the codec branch BGR keeps every historical +# latent bit-identical while Qwen receives true RGB. The policy interface stays RGB. +SPLIT_IMAGE_CONTRACT = { + "version": "robotwin-official-split-v1", + "decoder": "XPolicyLab.utils.process_data.decode_image_bit", + "stored_formats": "legacy_unmarked_and_XPL-RGB1", + "model_input_color_order": "rgb", + "branch_color_order": {"codec": "bgr", "qwen": "rgb"}, + "derived_feature_cache": "disabled", +} + +TRAINING_IMAGE_CONTRACTS = {"codec-bgr-qwen-rgb": SPLIT_IMAGE_CONTRACT, "rgb": RGB_IMAGE_CONTRACT} + + +def codec_needs_bgr(contract: dict | None) -> bool: + """Whether the codec branch must reverse channels of the contract's model input.""" + if contract is None: + return False # legacy exports: the adapter already reverses frames for both branches + branches = contract.get("branch_color_order") + if branches is None: + return False + if set(branches) != {"codec", "qwen"} or branches["qwen"] != contract["model_input_color_order"]: + raise ValueError(f"Unsupported image contract branches: {branches}") + if branches["codec"] not in {"rgb", "bgr"}: + raise ValueError(f"Unsupported codec color order: {branches['codec']}") + return branches["codec"] != contract["model_input_color_order"] + + +def require_resume_contract(metadata: dict, contract: dict) -> None: + if checkpoint_image_contract(metadata) != contract: + raise ValueError( + "Cannot resume optimizer/sampler state across an image contract change " + f"({checkpoint_image_contract(metadata)} -> {contract}). Use a new output directory " + "and --init-from-joint-checkpoint for weights-only adaptation." + ) + + +def checkpoint_image_contract(metadata: dict) -> dict | None: + config = metadata.get("resolved_config", {}).get("image_contract") + identity = metadata.get("artifact_identity", {}).get("image_contract") + if config is not None and identity is not None and config != identity: + raise ValueError("Checkpoint image contracts disagree") + return config if config is not None else identity + + +def require_rgb_resume(metadata: dict) -> None: + require_resume_contract(metadata, RGB_IMAGE_CONTRACT) + + +def validate_deployment_color(metadata: dict, requested: str) -> None: + if requested not in {"rgb", "bgr"}: + raise ValueError("input_color_order must be rgb or bgr") + contract = checkpoint_image_contract(metadata) + # Historical untagged exports remain usable by the ongoing RGB/BGR ablation. + if contract is not None and requested != contract["model_input_color_order"]: + raise ValueError( + f"Checkpoint requires {contract['model_input_color_order']} model input; " + f"requested {requested}. Do not apply legacy BGR compatibility to RGB-trained weights." + ) + + +def resolve_deployment_color(metadata: dict, requested: str = "auto") -> str: + """Resolve paired joint exports; explicit modes still support legacy ablations.""" + if requested == "auto": + contract = checkpoint_image_contract(metadata) + if contract is not None: + requested = contract["model_input_color_order"] + elif metadata.get("architecture") == "bihub-joint-world-action-anchor-v2": + # Historical joint trainer decoded the legacy corpus with torchvision. + requested = "bgr" + else: + raise ValueError("Cannot infer image color order for an unknown checkpoint") + validate_deployment_color(metadata, requested) + return requested diff --git a/release-20261107/source/workspace_joint/mira/src/mira/joint/model.py b/release-20261107/source/workspace_joint/mira/src/mira/joint/model.py new file mode 100644 index 0000000000000000000000000000000000000000..7674b394e40d9ab041822aa0a31eacd6a5f05084 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/joint/model.py @@ -0,0 +1,162 @@ +"""Differentiable coupling of the released World-v12 and Action-v13 models.""" + +from __future__ import annotations + +from contextlib import nullcontext + +import torch +from torch import Tensor, nn + +from mira.action_v6.model import ActionV6Batch, BiHubWAMActionStage +from mira.world_model.schedule import build_inference_schedule +from mira.world_v6.model import WorldV6System + + +class JointWorldActionModel(nn.Module): + """Train every World and Action parameter while sharing the predicted future. + + Qwen and the codec intentionally live outside this module. Their outputs enter as constants; + the frozen codec decoder is applied by the trainer after this module returns so pixel loss can + still differentiate through the decoded pixels into ``predicted_future_raw``. + """ + + def __init__(self, world: WorldV6System, action: BiHubWAMActionStage) -> None: + super().__init__() + self.world = world + self.action = action + # The released Action checkpoint contains a frozen copy of the World state encoder. Joint + # training uses the live World state encoder below, so keeping the duplicate wastes memory + # and would violate the requested full-finetune semantics. + self.action.state_encoder = nn.Identity() + for parameter in self.world.parameters(): + parameter.requires_grad_(True) + for parameter in self.action.transition_conditioner.parameters(): + parameter.requires_grad_(True) + for parameter in self.action.action_flow.parameters(): + parameter.requires_grad_(True) + + def differentiable_world_rollout( + self, + *, + z_context_raw: Tensor, + anchors: Tensor, + state_history: Tensor, + history_valid: Tensor, + context_valid: Tensor, + noise: Tensor, + steps: int, + grad_steps: int | None = None, + ) -> Tensor: + """Euler rollout without ``inference_mode`` so downstream losses train World. + + ``grad_steps`` keeps autograd only for the last Euler steps; earlier steps run under + ``no_grad``. The rollout values are identical, only the gradient path is truncated. + """ + + if not 1 <= steps <= 10: + raise ValueError("joint-training World rollout steps must be in [1, 10]") + if grad_steps is None: + grad_steps = steps + if not 1 <= grad_steps <= steps: + raise ValueError("rollout gradient steps must be in [1, rollout steps]") + context = self.world.normalize_latent(z_context_raw) + future = noise.float() + condition = self.world.condition_from_anchors(z_context_raw, anchors, context_valid) + schedule = build_inference_schedule( + steps, context.device, schedule_type="linear_quadratic" + ) + for index, (start, end) in enumerate(zip(schedule[:-1], schedule[1:])): + with torch.no_grad() if index < steps - grad_steps else nullcontext(): + tau = torch.full( + (context.shape[0], 10, 1, 1, 1), + start, + device=context.device, + dtype=torch.float32, + ) + velocity = self.world.forward_velocity( + z_context_raw, + future, + condition, + state_history, + tau, + history_valid, + context_valid, + ) + future = future + (end - start) * velocity.float() + return self.world.denormalize_latent(future) + + def forward( + self, + *, + z_context_raw: Tensor, + z_future_raw: Tensor, + state_history: Tensor, + history_valid: Tensor, + context_valid: Tensor, + action_gt: Tensor, + action_valid: Tensor, + future_valid: Tensor, + qwen_hidden: Tensor, + qwen_mask: Tensor, + rollout_noise: Tensor, + action_noise: Tensor, + rollout_steps: int, + rollout_grad_steps: int | None = None, + ) -> dict[str, Tensor]: + batch = z_context_raw.shape[0] + anchors = self.world.current_resampler(qwen_hidden, qwen_mask) + world_result = self.world.flow_objective( + z_context_raw=z_context_raw, + z_future_raw=z_future_raw, + anchors=anchors, + state_history=state_history, + history_valid=history_valid, + context_valid=context_valid, + future_valid=future_valid, + view_valid=torch.ones((batch, 3), dtype=torch.bool, device=z_context_raw.device), + allow_empty_future=True, + ) + predicted_future_raw = self.differentiable_world_rollout( + z_context_raw=z_context_raw, + anchors=anchors, + state_history=state_history, + history_valid=history_valid, + context_valid=context_valid, + noise=rollout_noise, + steps=rollout_steps, + grad_steps=rollout_grad_steps, + ) + predicted_future = self.world.normalize_latent(predicted_future_raw) + current = self.world.normalize_latent(z_context_raw[:, :, -1:]) + + encoded_state = self.world.state_encoder(state_history, history_valid) + state_lgr = torch.stack( + [encoded_state[name] for name in ("left", "global", "right")], dim=1 + ) + action_batch = ActionV6Batch( + z_current=current, + z_future_cond=predicted_future, + state_history=state_history, + state_valid_mask=history_valid, + action_gt=action_gt, + action_valid_mask=action_valid, + future_source=torch.ones(batch, dtype=torch.int64, device=z_context_raw.device), + ) + action_result = self.action( + action_batch, + noise=action_noise, + state_lgr=state_lgr, + ) + latent_error = (predicted_future_raw.float() - z_future_raw.float()).square() + mask = future_valid[:, None, :, None, None, None].expand_as(latent_error) + latent_loss = (latent_error * mask).sum() / mask.sum().clamp_min(1) + return { + "predicted_future_raw": predicted_future_raw, + "loss_world_flow": world_result["loss_world"], + "loss_world_latent": latent_loss, + "loss_action": action_result["loss"], + "loss_action_uniform": action_result["loss_uniform"], + "world_recovered_clean_mse": world_result["recovered_clean_mse"], + "action_velocity_pred": action_result["velocity_pred"], + "action_velocity_target": action_result["velocity_target"], + } diff --git a/release-20261107/source/workspace_joint/mira/src/mira/joint/paths.py b/release-20261107/source/workspace_joint/mira/src/mira/joint/paths.py new file mode 100644 index 0000000000000000000000000000000000000000..074b762fd8aa0fc500451f9c39d24a8df5bc54af --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/joint/paths.py @@ -0,0 +1,13 @@ +"""Resolve relocated assets in memory; never rewrite hash-bound release metadata.""" +from pathlib import Path + + +def workspace_path(value: str | Path, workspace: Path | None = None) -> Path: + workspace = workspace or Path(__file__).resolve().parents[4] + value = str(value) + for anchor in ("outputs", "artifacts", "models", "datasets", "mira", "lingbot-vision"): + marker = f"/{anchor}/" + if marker in value: + return workspace / anchor / value.split(marker, 1)[1] + path = Path(value).expanduser() + return path if path.is_absolute() else workspace / path diff --git a/release-20261107/source/workspace_joint/mira/src/mira/joint/training_utils.py b/release-20261107/source/workspace_joint/mira/src/mira/joint/training_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e93274987ab941ce0c92ba6bfe6a938835726a4b --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/joint/training_utils.py @@ -0,0 +1,97 @@ +"""Optimization helpers for joint World + Action runs: schedule, EMA and task weighting.""" + +from __future__ import annotations + +import hashlib +import json +import math +from pathlib import Path + +import torch +from torch import nn + +# Activation-checkpoint wrappers rename parameters; checkpoints and exports use the clean names. +_WRAPPER_PREFIX = "_checkpoint_wrapped_module." + + +def lr_scale(step: int, *, warmup_steps: int, total_steps: int, min_ratio: float) -> float: + """Linear warmup, then cosine decay from 1 to ``min_ratio`` at ``total_steps``.""" + if not 0.0 <= min_ratio <= 1.0: + raise ValueError("min_ratio must be in [0, 1]") + completed = step + 1 + if completed <= warmup_steps: + return completed / max(1, warmup_steps) + progress = (completed - warmup_steps) / max(1, total_steps - warmup_steps) + return min_ratio + (1.0 - min_ratio) * 0.5 * (1.0 + math.cos(math.pi * min(1.0, progress))) + + +def clean_parameter_name(name: str) -> str: + return name.replace(_WRAPPER_PREFIX, "") + + +class ParameterEMA: + """Exponential moving average of every trainable parameter, sharded like the parameter. + + Shadows are plain clones of (possibly FSDP2 DTensor) parameters, so they inherit the same + placement and are saved/loaded by torch.distributed.checkpoint under clean parameter names. + """ + + def __init__(self, model: nn.Module, decay: float, warmup: bool = True) -> None: + if not 0.0 < decay < 1.0: + raise ValueError("EMA decay must be in (0, 1)") + self.decay = float(decay) + self.warmup = bool(warmup) + self.parameters = { + clean_parameter_name(name): parameter + for name, parameter in model.named_parameters() if parameter.requires_grad + } + self.shadow = {name: parameter.detach().clone() for name, parameter in self.parameters.items()} + + def decay_at(self, completed_steps: int) -> float: + if not self.warmup: + return self.decay + return min(self.decay, (1.0 + completed_steps) / (10.0 + completed_steps)) + + @torch.no_grad() + def update(self, completed_steps: int) -> float: + decay = self.decay_at(completed_steps) + for name, parameter in self.parameters.items(): + self.shadow[name].mul_(decay).add_(parameter.detach(), alpha=1.0 - decay) + return decay + + @torch.no_grad() + def copy_from_model(self) -> None: + for name, parameter in self.parameters.items(): + self.shadow[name].copy_(parameter.detach()) + + def state_dict(self) -> dict[str, torch.Tensor]: + return self.shadow + + +def apply_ema_to_state(model_state: dict[str, torch.Tensor], ema_state: dict[str, torch.Tensor]) -> dict: + """Replace every EMA-tracked parameter in a clean model state dict; buffers stay live.""" + missing = sorted(set(ema_state) - set(model_state)) + if missing: + raise ValueError(f"EMA tracks parameters absent from the model: {missing[:5]}") + return {**model_state, **ema_state} + + +def load_task_weights(path: str | Path, tasks: list[str]) -> tuple[dict[str, float], str]: + """Validated task sampling weights and the SHA-256 of their canonical JSON. + + The file maps every training task to a non-negative weight; unlisted tasks are an error so a + typo cannot silently drop a task from training. + """ + raw = json.loads(Path(path).read_text(encoding="utf-8")) + weights = raw.get("weights", raw) + if not isinstance(weights, dict): + raise ValueError("task weights must be a JSON object") + unknown = sorted(set(weights) - set(tasks)) + missing = sorted(set(tasks) - set(weights)) + if unknown or missing: + raise ValueError(f"task weights must cover exactly the training tasks; unknown={unknown} missing={missing}") + result = {task: float(weights[task]) for task in tasks} + if any(not math.isfinite(value) or value < 0 for value in result.values()) or sum(result.values()) <= 0: + raise ValueError("task weights must be finite, non-negative and not all zero") + canonical = json.dumps(result, sort_keys=True, separators=(",", ":")) + return result, hashlib.sha256(canonical.encode()).hexdigest() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/ml/__init__.py b/release-20261107/source/workspace_joint/mira/src/mira/ml/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d6faab7c287e3c9b774d60a65c4dcefd9740827d --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/ml/__init__.py @@ -0,0 +1,33 @@ +"""mira.ml: shared model building blocks for the codec and world model. + +Public API: + ImageConfig — spatial/temporal shape of a video tensor + init_weights — type-dispatched in-place weight initialisation (pass to `nn.Module.apply`) + SelfAttention, SelfAttentionConfig — GQA self-attention with QK-norm and optional gating + AdaptiveLayerNorm, QKLayerNorm, QKRMSNorm — normalisation layers + apply_rotary_emb, local_causal_mask — RoPE application and local causal masking +""" + +from .attention import ( + AdaptiveLayerNorm, + QKLayerNorm, + QKRMSNorm, + SelfAttention, + SelfAttentionConfig, + apply_rotary_emb, + local_causal_mask, +) +from .image_config import ImageConfig +from .init import init_weights + +__all__ = [ + "ImageConfig", + "init_weights", + "SelfAttention", + "SelfAttentionConfig", + "AdaptiveLayerNorm", + "QKLayerNorm", + "QKRMSNorm", + "apply_rotary_emb", + "local_causal_mask", +] diff --git a/release-20261107/source/workspace_joint/mira/src/mira/ml/attention.py b/release-20261107/source/workspace_joint/mira/src/mira/ml/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..b8c55fa61407c38355c4cb77a5c82ce332776fdf --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/ml/attention.py @@ -0,0 +1,254 @@ +"""Self-attention building blocks: GQA self-attention with QK-norm, RoPE, and adaptive LayerNorm.""" + +from __future__ import annotations + +from typing import Literal + +import torch +import torch.nn as nn +from einops import rearrange +from pydantic import BaseModel, ConfigDict, model_validator +from torch import Tensor +from torch.nn import functional as F + + +def local_causal_mask(q_len: int, k_len: int, context: int | None, device: torch.device) -> Tensor: + """Create a local causal mask for attention. + + Args: + q_len: Length of the query sequence. + k_len: Length of the key sequence. + context: Size of the local context window, or None for an unbounded causal mask. + device: Device to create the mask on. + + Returns: + A boolean mask of shape (q_len, k_len) where True indicates allowed attention. + """ + tensor = torch.full( + (q_len, k_len), + fill_value=1, + dtype=torch.bool, + device=device, + ) + + shift = k_len - q_len + + mask = torch.tril(tensor, diagonal=shift) + if context is not None: + mask = torch.triu(mask, diagonal=shift - context + 1) + return mask + + +class SelfAttentionConfig(BaseModel): + model_config = ConfigDict(extra="forbid") + + embed_dim: int + num_heads: int + # Can be set to None by the config, in which case it is set to num_heads by the validator. + num_kv_heads: int | None + gating: bool = False + qk_norm: Literal["layernorm", "rmsnorm"] = "layernorm" + + @model_validator(mode="after") + def validate_heads(self): + if self.num_kv_heads is None: + self.num_kv_heads = self.num_heads + + assert self.embed_dim % self.num_heads == 0, ( + f"{self.embed_dim=} must be divisible by {self.num_heads=}" + ) + assert self.num_heads % self.num_kv_heads == 0, ( + f"{self.num_heads=} must be divisible by {self.num_kv_heads=}" + ) + return self + + @property + def head_dim(self) -> int: + return self.embed_dim // self.num_heads + + @property + def total_head_dim(self) -> int: + return (self.num_heads + 2 * self.num_kv_heads) * self.head_dim # type: ignore + + @property + def total_kv_dim(self) -> int: + return self.num_kv_heads * self.head_dim # type: ignore + + +class SelfAttention(nn.Module): + def __init__( + self, + config: SelfAttentionConfig, + causal: bool = False, + context_window_length: int | None = None, + ): + super().__init__() + self.causal = causal + if context_window_length is not None: + assert causal, "Context can only be used with causal attention" + self.context_window_length = context_window_length + self.gating = config.gating + self.dim = config.embed_dim + self.num_heads = config.num_heads + self.head_dim = config.head_dim + + # GQA: fewer KV heads than Q heads. The validator fills num_kv_heads (defaulting to + # num_heads), so it is always set by the time the module is built. + assert config.num_kv_heads is not None + self.num_kv_heads = config.num_kv_heads + self.gqa_enabled = self.num_kv_heads != self.num_heads + + q_out = self.dim + kv_out = self.num_kv_heads * self.head_dim + gate_out = self.dim if self.gating else 0 + + self.wqkv = nn.Linear(self.dim, q_out + 2 * kv_out + gate_out, bias=False) + self.wo = nn.Linear(self.dim, self.dim, bias=False) + + qk_norm_cls = QKRMSNorm if config.qk_norm == "rmsnorm" else QKLayerNorm + self.q_ln = qk_norm_cls((self.num_heads, self.head_dim)) + self.k_ln = qk_norm_cls((self.num_kv_heads, self.head_dim)) + + def forward( + self, + x: Tensor, + rotary_emb: tuple[Tensor, Tensor] | None = None, + return_kv: bool = False, + # (k_ctx, v_ctx) if given, each shape (B, T_ctx, num_kv_heads, head_dim) + kv_cache: tuple[Tensor, Tensor] | None = None, + key_valid_mask: Tensor | None = None, + ): + bsz, seqlen, _ = x.shape + + q_out = self.dim + kv_out = self.num_kv_heads * self.head_dim + if self.gating: + q, k, v, gating = self.wqkv(x).split([q_out, kv_out, kv_out, self.dim], dim=-1) + else: + q, k, v = self.wqkv(x).split([q_out, kv_out, kv_out], dim=-1) + gating = None + + q = q.view(bsz, seqlen, self.num_heads, self.head_dim) + k = k.view(bsz, seqlen, self.num_kv_heads, self.head_dim) + v = v.view(bsz, seqlen, self.num_kv_heads, self.head_dim) + + q = self.q_ln(q) + k = self.k_ln(k) + + to_cache = None + if return_kv: + to_cache = (k.clone(), v.clone()) + if self.context_window_length is not None and seqlen > self.context_window_length: + to_cache = ( + k[:, -self.context_window_length :], + v[:, -self.context_window_length :], + ) + + if kv_cache is not None: + k_ctx, v_ctx = kv_cache + k = torch.cat([k_ctx, k], dim=1) + v = torch.cat([v_ctx, v], dim=1) + + if rotary_emb is not None: + if kv_cache is not None: + rotary_emb_q = (rotary_emb[0][-1:], rotary_emb[1][-1:]) + q = apply_rotary_emb(q, rotary_emb_q) + else: + q = apply_rotary_emb(q, rotary_emb) + k = apply_rotary_emb(k, rotary_emb) + + q, k, v = map(lambda t: t.transpose(1, 2), (q, k, v)) + attn_mask = None + if self.causal: + attn_mask = local_causal_mask( + q_len=q.shape[-2], + k_len=k.shape[-2], + context=self.context_window_length, + device=x.device, + ) + if key_valid_mask is not None: + if key_valid_mask.shape != (bsz, k.shape[-2]): + raise ValueError( + f"key_valid_mask must be [B,K]={bsz,k.shape[-2]}, " + f"got {tuple(key_valid_mask.shape)}" + ) + valid = key_valid_mask[:, None, None, :].bool() + attn_mask = valid if attn_mask is None else attn_mask[None, None] & valid + y = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, enable_gqa=self.gqa_enabled) + y = y.transpose(1, 2).contiguous().view(bsz, seqlen, self.dim) + + if self.gating: + assert gating is not None + y = y * torch.sigmoid(gating) + + y = self.wo(y) + + if return_kv: + return y, to_cache + return y + + +def apply_rotary_emb(x: Tensor, freqs: tuple[Tensor, Tensor]): + x = rearrange(x, "b t n_head c -> b n_head t c") + # assume the channel dimension c contains c/2 imaginary numbers, each represented by two + # consecutive values + cos, sin = freqs # shape (t c) + # both cos and sin are repeat_interleaved, so two consecutive values are identical, matching + # the imaginary numbers above + x_real, x_imag = x.unflatten(-1, (-1, 2)).unbind(-1) # both has shape (b, n_head, t, c // 2) + x_rotated = torch.stack([-x_imag, x_real], dim=-1).flatten(-2) # (b, n_head, t, c) + # apply the rotation matrix + out = (x.float() * cos + x_rotated.float() * sin).to(x.dtype) + out = rearrange(out, "b n_head t c -> b t n_head c") + return out + + +class QKLayerNorm(nn.Module): + def __init__(self, input_shape: tuple, eps: float = 1e-5): + super().__init__() + self.qk_scale = nn.Parameter(torch.ones(input_shape)) + self.eps = eps + + def forward(self, x: Tensor) -> Tensor: + input_dtype = x.dtype + x = x.to(torch.float32) + + mean = x.mean(-1, keepdim=True) + variance = (x - mean).pow(2).mean(-1, keepdim=True) + x = (x - mean) * torch.rsqrt(variance + self.eps) + x = self.qk_scale.to(torch.float32) * x + + x = x.to(input_dtype) + + return x + + +class QKRMSNorm(nn.Module): + """Per-head RMSNorm for Q/K. Same parameter shape as QKLayerNorm so checkpoints are interchangeable.""" + + def __init__(self, input_shape: tuple, eps: float = 1e-5): + super().__init__() + self.qk_scale = nn.Parameter(torch.ones(input_shape)) + self.eps = eps + + def forward(self, x: Tensor) -> Tensor: + input_dtype = x.dtype + x = x.to(torch.float32) + variance = x.pow(2).mean(-1, keepdim=True) + x = x * torch.rsqrt(variance + self.eps) + x = self.qk_scale.to(torch.float32) * x + return x.to(input_dtype) + + +class AdaptiveLayerNorm(nn.Module): + def __init__(self, embed_dim: int, cond_dim: int): + super().__init__() + self.embed_dim = embed_dim + self.layer_norm = nn.LayerNorm(embed_dim, elementwise_affine=False) + self.gamma_beta = nn.Linear(cond_dim, 2 * embed_dim) + + def forward(self, x: Tensor, cond: Tensor) -> Tensor: + normalized_x = self.layer_norm(x) + gamma_beta = self.gamma_beta(cond) + gamma, beta = gamma_beta.chunk(2, dim=-1) + return (1 + gamma) * normalized_x + beta diff --git a/release-20261107/source/workspace_joint/mira/src/mira/ml/config_loading.py b/release-20261107/source/workspace_joint/mira/src/mira/ml/config_loading.py new file mode 100644 index 0000000000000000000000000000000000000000..f3a81e750112587e36b7d4c16780197c8c4c6fc1 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/ml/config_loading.py @@ -0,0 +1,57 @@ +"""Helpers for loading model configs saved alongside checkpoints. + +Checkpoints save their architecture config as a hydra-instantiated YAML. Two kinds of cruft creep in +that the strict (``extra="forbid"``) Pydantic schemas reject: + +* ``_target_`` keys hydra writes at every level it instantiated (e.g. the top-level config and a + nested ``video`` image config), which carry no information the schema needs. +* Fields that have since been removed from the schema but were still written, at their no-op value, + by older training runs. + +:func:`strip_hydra_targets` removes the former everywhere; :func:`drop_removed_fields` removes the +latter only when present at its documented no-op value, and raises otherwise so a checkpoint that +genuinely exercised a since-removed feature still fails loudly instead of loading silently wrong. +""" + +from __future__ import annotations + +from typing import Mapping + + +def strip_hydra_targets(node: object) -> object: + """Return ``node`` with every ``_target_`` key recursively removed from nested dicts/lists.""" + if isinstance(node, dict): + return {k: strip_hydra_targets(v) for k, v in node.items() if k != "_target_"} + if isinstance(node, list): + return [strip_hydra_targets(v) for v in node] + return node + + +def drop_removed_fields(node: object, removed: Mapping[str, object]) -> object: + """Recursively drop known removed fields, tolerating them only at their no-op value. + + Args: + node: A plain dict/list config tree (resolve OmegaConf to a container first). + removed: Maps a removed field name to the no-op value it is allowed to carry. A matching key + at that value is dropped; at any other value a :class:`ValueError` is raised. + + Returns: + A new tree with the removed fields filtered out. + """ + if isinstance(node, dict): + cleaned: dict = {} + for key, value in node.items(): + if key in removed: + noop = removed[key] + if value != noop: + raise ValueError( + f"Config sets dropped field {key!r}={value!r}, which is only tolerated at " + f"its no-op value {noop!r}. This checkpoint used a feature that has since " + f"been removed and cannot be loaded." + ) + continue + cleaned[key] = drop_removed_fields(value, removed) + return cleaned + if isinstance(node, list): + return [drop_removed_fields(v, removed) for v in node] + return node diff --git a/release-20261107/source/workspace_joint/mira/src/mira/ml/image_config.py b/release-20261107/source/workspace_joint/mira/src/mira/ml/image_config.py new file mode 100644 index 0000000000000000000000000000000000000000..60669127f5ec76c8eace6e13f8ece99bf0ee4f36 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/ml/image_config.py @@ -0,0 +1,25 @@ +"""Image/video tensor shape configuration shared by the codec and world model.""" + +from __future__ import annotations + +from pydantic import BaseModel, ConfigDict + + +class ImageConfig(BaseModel): + """Spatial and temporal shape of a video tensor. + + Attributes: + height: Frame height in pixels. + width: Frame width in pixels. + channels: Number of colour channels (3 for RGB). + timesteps: Number of frames per clip. + fps: Frame rate the clip is sampled at. + """ + + model_config = ConfigDict(extra="forbid") + + height: int + width: int + channels: int = 3 + timesteps: int = 20 + fps: int = 10 diff --git a/release-20261107/source/workspace_joint/mira/src/mira/ml/init.py b/release-20261107/source/workspace_joint/mira/src/mira/ml/init.py new file mode 100644 index 0000000000000000000000000000000000000000..e5728ede0cd97b683965b1dd944eb9af5bb18f6c --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/ml/init.py @@ -0,0 +1,35 @@ +"""Weight initialisation for the codec and world-model modules.""" + +from __future__ import annotations + +import torch +import torch.nn as nn + +from .attention import AdaptiveLayerNorm + + +def init_weights(module: nn.Module) -> None: + """Initialise a single module in place, dispatched on its type. + + Intended to be passed to `nn.Module.apply` so it runs over every submodule. Linear and + convolutional weights are drawn from `N(0, 0.02)` with zero bias; embeddings from `N(0, 0.02)`; + normalisation layers are set to unit weight and zero bias; and `AdaptiveLayerNorm`'s conditioning + projection is zeroed so it starts as an identity modulation. + + Args: + module: The submodule to initialise. + """ + if isinstance(module, AdaptiveLayerNorm): + nn.init.zeros_(module.gamma_beta.weight) + nn.init.zeros_(module.gamma_beta.bias) + elif isinstance(module, (nn.Linear, nn.Conv2d, nn.Conv3d)): + nn.init.normal_(module.weight, mean=0.0, std=0.02) + if module.bias is not None: + nn.init.zeros_(module.bias) + elif isinstance(module, nn.Embedding): + nn.init.normal_(module.weight, mean=0.0, std=0.02) + elif isinstance(module, (nn.LayerNorm, nn.GroupNorm, nn.RMSNorm)): + if module.weight is not None: + nn.init.ones_(module.weight) + if hasattr(module, "bias") and isinstance(module.bias, torch.Tensor): + nn.init.zeros_(module.bias) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/text/__init__.py b/release-20261107/source/workspace_joint/mira/src/mira/text/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..93f08a3331323ca49a2676b5bb676f849b67cb95 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/text/__init__.py @@ -0,0 +1,5 @@ +"""Frozen text encoders used only by offline preprocessing.""" + +from .wan_umt5 import WanUMT5Encoder, load_wan_umt5 + +__all__ = ["WanUMT5Encoder", "load_wan_umt5"] diff --git a/release-20261107/source/workspace_joint/mira/src/mira/text/wan_umt5.py b/release-20261107/source/workspace_joint/mira/src/mira/text/wan_umt5.py new file mode 100644 index 0000000000000000000000000000000000000000..c76c935b3fd6dec121e0919ae2fac52ac2bb95cc --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/text/wan_umt5.py @@ -0,0 +1,140 @@ +"""Minimal Wan UMT5-XXL encoder compatible with the released BF16 checkpoint. + +This is intentionally an offline-only dependency: Stage-W training consumes cached hidden states +and never constructs this 24-layer encoder. +""" + +from __future__ import annotations + +import math +from pathlib import Path + +import torch +from torch import Tensor, nn + + +class T5LayerNorm(nn.Module): + def __init__(self, dim: int, eps: float = 1.0e-6) -> None: + super().__init__() + self.eps = eps + self.weight = nn.Parameter(torch.ones(dim)) + + def forward(self, x: Tensor) -> Tensor: + value = x * torch.rsqrt(x.float().square().mean(dim=-1, keepdim=True) + self.eps) + return self.weight * value.to(self.weight.dtype) + + +class T5RelativeEmbedding(nn.Module): + def __init__(self, num_buckets: int, num_heads: int, max_distance: int = 128) -> None: + super().__init__() + self.num_buckets = num_buckets + self.max_distance = max_distance + self.embedding = nn.Embedding(num_buckets, num_heads) + + def _bucket(self, relative: Tensor) -> Tensor: + half = self.num_buckets // 2 + buckets = (relative > 0).long() * half + distance = relative.abs() + exact = half // 2 + large = exact + ( + torch.log(distance.float() / exact) / math.log(self.max_distance / exact) * (half - exact) + ).long() + large = torch.minimum(large, torch.full_like(large, half - 1)) + return buckets + torch.where(distance < exact, distance, large) + + def forward(self, query_length: int, key_length: int) -> Tensor: + device = self.embedding.weight.device + relative = torch.arange(key_length, device=device)[None] - torch.arange(query_length, device=device)[:, None] + return self.embedding(self._bucket(relative)).permute(2, 0, 1).unsqueeze(0).contiguous() + + +class T5Attention(nn.Module): + def __init__(self, dim: int = 4096, attention_dim: int = 4096, heads: int = 64) -> None: + super().__init__() + self.heads = heads + self.head_dim = attention_dim // heads + self.q = nn.Linear(dim, attention_dim, bias=False) + self.k = nn.Linear(dim, attention_dim, bias=False) + self.v = nn.Linear(dim, attention_dim, bias=False) + self.o = nn.Linear(attention_dim, dim, bias=False) + + def forward(self, x: Tensor, mask: Tensor | None, position_bias: Tensor) -> Tensor: + batch = x.shape[0] + q = self.q(x).view(batch, -1, self.heads, self.head_dim).transpose(1, 2) + k = self.k(x).view(batch, -1, self.heads, self.head_dim).transpose(1, 2) + v = self.v(x).view(batch, -1, self.heads, self.head_dim).transpose(1, 2) + bias = position_bias + if mask is not None: + bias = bias.masked_fill(~mask[:, None, None, :], torch.finfo(x.dtype).min) + # T5 attention deliberately does not apply 1/sqrt(head_dim). + attention = (q @ k.transpose(-1, -2) + bias).float().softmax(dim=-1).to(x.dtype) + value = (attention @ v).transpose(1, 2).reshape(batch, -1, self.heads * self.head_dim) + return self.o(value) + + +class T5FeedForward(nn.Module): + def __init__(self, dim: int = 4096, hidden: int = 10240) -> None: + super().__init__() + self.gate = nn.Sequential(nn.Linear(dim, hidden, bias=False), nn.GELU(approximate="tanh")) + self.fc1 = nn.Linear(dim, hidden, bias=False) + self.fc2 = nn.Linear(hidden, dim, bias=False) + + def forward(self, x: Tensor) -> Tensor: + return self.fc2(self.fc1(x) * self.gate(x)) + + +class T5Block(nn.Module): + def __init__(self) -> None: + super().__init__() + self.norm1 = T5LayerNorm(4096) + self.attn = T5Attention() + self.norm2 = T5LayerNorm(4096) + self.ffn = T5FeedForward() + self.pos_embedding = T5RelativeEmbedding(32, 64) + + def forward(self, x: Tensor, mask: Tensor | None) -> Tensor: + bias = self.pos_embedding(x.shape[1], x.shape[1]) + x = x + self.attn(self.norm1(x), mask, bias) + return x + self.ffn(self.norm2(x)) + + +class WanUMT5Encoder(nn.Module): + """Architecture of ``models_t5_umt5-xxl-enc-bf16.pth``.""" + + dim = 4096 + + def __init__(self) -> None: + super().__init__() + self.token_embedding = nn.Embedding(256384, 4096) + self.blocks = nn.ModuleList([T5Block() for _ in range(24)]) + self.norm = T5LayerNorm(4096) + + def forward(self, token_ids: Tensor, mask: Tensor | None = None) -> Tensor: + x = self.token_embedding(token_ids) + for block in self.blocks: + x = block(x, mask) + return self.norm(x) + + +def load_wan_umt5( + checkpoint: str | Path, + *, + device: str | torch.device, + dtype: torch.dtype = torch.bfloat16, +) -> WanUMT5Encoder: + """Load the official Wan checkpoint without a 22 GB random-initialization peak.""" + checkpoint = Path(checkpoint) + if not checkpoint.is_file(): + raise FileNotFoundError(checkpoint) + with torch.device("meta"): + model = WanUMT5Encoder() + state = torch.load(checkpoint, map_location="cpu", weights_only=True, mmap=True) + if len(state) == 1: + for wrapper in ("state_dict", "module", "model_state"): + if wrapper in state: + state = state[wrapper] + break + missing, unexpected = model.load_state_dict(state, strict=False, assign=True) + if missing or unexpected: + raise RuntimeError(f"Wan UMT5 checkpoint mismatch: missing={missing[:8]}, unexpected={unexpected[:8]}") + return model.to(device=device, dtype=dtype).eval() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/__init__.py b/release-20261107/source/workspace_joint/mira/src/mira/training/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e074907ad4efdd7cf624a0e29e88a7394d4f21d2 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/__init__.py @@ -0,0 +1,13 @@ +"""Shared training infrastructure for the codec and world-model trainers. + +The submodules are single-GPU safe: every ``torch.distributed`` call is guarded by +``is_initialized()`` so the trainers (and tests) run without ``torchrun``. + + distributed — DistributedSettings, get_distributed_settings, set_up_distributed + ema — ModelEMA (parameter EMA + swap/restore), DistributedEMA (scalar EMA) + lr_schedule — WarmupConstantCosineDecayLR + checkpoint_manager — CheckpointManager (save / continue_from / finetune_from) + tracker — TrainingTracker, periodic_event, display_execution_time + metrics — DistributedMetric and image-quality metrics + visualization — video helpers for W&B logging +""" diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/action_v10/__init__.py b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v10/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1b798be03cff96b4ad38a79200eaa5edc00f5df8 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v10/__init__.py @@ -0,0 +1 @@ +"""Action-v10 short-history training support.""" diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/action_v10/build_predicted_cache.py b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v10/build_predicted_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..c99c7de105cbb683894f9a99f60dfef868dbea5b --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v10/build_predicted_cache.py @@ -0,0 +1,474 @@ +"""Build World-v10 Online predicted futures for the Action-v10 curriculum.""" + +from __future__ import annotations + +import argparse +import bisect +import hashlib +import json +import math +import os +import random +from collections import defaultdict +from pathlib import Path +from typing import Any + +import torch +import torch.distributed as dist +from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( + CheckpointImpl, + checkpoint_wrapper, +) +from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard + +from mira.data.action_v6 import ( + PREDICTED_FUTURE_ELEMENTS, + PREDICTED_FUTURE_SHAPE, + encode_predicted_future_locator, +) +from mira.data.world_v6 import set_world_v6_process_name +from mira.data.world_v7 import HISTORY_LENGTHS, WorldV7Dataset, collate_world_v7 +from mira.training.action_v6.artifacts import canonical_sha256, sha256_file, write_json_atomic +from mira.training.action_v6.config import load_config +from mira.training.distributed import set_up_distributed +from mira.training.world_v8.checkpoint import checkpoint_fingerprint, load_online_source +from mira.training.world_v8.config import load_config as load_world_config +from mira.world_v6.model import WorldV6System + + +ROW_BYTES = PREDICTED_FUTURE_ELEMENTS * 2 + + +def _barrier() -> None: + if dist.is_initialized(): + dist.barrier() + + +def _cache_micro_batch(config) -> int: + value = int( + os.environ.get( + "MIRA_PREDICTED_CACHE_MICRO_BATCH", + config.training.micro_batch_per_gpu, + ) + ) + maximum = 96 if config.training.protocol == "eval_aligned_epoch_world_v12" else 32 + minimum = 1 if config.training.protocol == "eval_aligned_epoch_world_v12" else config.training.micro_batch_per_gpu + if value < minimum or value > maximum: + raise ValueError( + f"predicted-cache micro batch must be in [{minimum}, {maximum}]" + ) + return value + + +def _seed(*values: object) -> int: + digest = hashlib.sha256("\0".join(map(str, values)).encode()).digest() + return int.from_bytes(digest[:8], "big") % (2**63 - 1) + + +def _select_split(config, split: str, per_stratum: int) -> dict[str, Any]: + source_manifest = ( + config.artifacts.train_source_manifest + if split == "train" + else config.artifacts.val_source_manifest + ) + dataset = WorldV7Dataset( + source_manifest=source_manifest, + dataset_stats=config.artifacts.state_stats, + qwen_cache_root=config.artifacts.qwen_hidden_cache_root, + split=split, + episode_cache_size=1, + mapping_cache_size=1, + ) + strata: dict[tuple[str, str], list[int]] = defaultdict(list) + for episode, row in enumerate(dataset.source_rows): + strata[(str(row["task"]), str(row["domain"]))].append(episode) + selected: list[dict[str, Any]] = [] + + def append(episode: int, latent_start: int, history_index: int) -> None: + row = dataset.source_rows[episode] + expanded = dataset.expanded_index(episode, latent_start, history_index) + history = HISTORY_LENGTHS[history_index] + selected.append( + { + "expanded_index": expanded, + "episode_sha256": row["episode_sha256"], + "task": row["task"], + "domain": row["domain"], + "latent_start": latent_start, + "history_length": history, + "world_seed": _seed( + config.predicted_future_cache.seed_namespace, + config.artifacts.world_checkpoint_sha256, + row["episode_sha256"], + latent_start, + history, + ), + } + ) + + if config.training.protocol == "eval_aligned_epoch_world_v12": + # Match World-v12 exactly: growing prefixes exist only at episode start, + # while H10 contains every legal start. A bounded selection is allowed + # only by the gate config used to exercise cache I/O before the formal run. + limit = int(config.predicted_future_cache.max_rows_per_history) + prefix_episodes = range(len(dataset.source_rows)) + if limit: + prefix_episodes = range(min(limit, len(dataset.source_rows))) + for history_index in (0, 1, 2): + for episode in prefix_episodes: + append(episode, 0, history_index) + remaining = limit if limit else dataset.base_windows + for episode, count in enumerate(dataset.base_counts): + for latent_start in range(count): + if remaining <= 0: + break + append(episode, latent_start, 3) + remaining -= 1 + if remaining <= 0: + break + else: + # Deployment-critical H1 covers every episode exactly once and is always latent_start=0. + for episode in range(len(dataset.source_rows)): + append(episode, 0, 0) + + # Legacy short-history experiments use a deterministic balanced subset. + for (task, domain), episodes in sorted(strata.items()): + cumulative = [] + total = 0 + for episode in episodes: + total += dataset.base_counts[episode] + cumulative.append(total) + keep = min(per_stratum, total) + for history_index in (1, 2, 3): + rng = random.Random(_seed("selection", split, task, domain, history_index, config.experiment.seed)) + offsets = rng.sample(range(total), keep) + for offset in offsets: + position = bisect.bisect_right(cumulative, offset) + previous = cumulative[position - 1] if position else 0 + append(episodes[position], offset - previous, history_index) + + if len({int(row["expanded_index"]) for row in selected}) != len(selected): + raise RuntimeError("Action-v10 cache selection contains duplicate expanded rows") + by_rank: dict[int, list[dict[str, Any]]] = defaultdict(list) + for row in selected: + rank = _seed("writer", split, row["expanded_index"], config.artifacts.world_checkpoint_sha256) % 8 + by_rank[rank].append(row) + root = Path(config.predicted_future_cache.root) / split + root.mkdir(parents=True, exist_ok=True) + for rank in range(8): + rows = sorted(by_rank[rank], key=lambda row: int(row["expanded_index"])) + path = root / f"selection-{rank:02d}.jsonl" + temporary = path.with_name(f".{path.name}.tmp") + with temporary.open("w", encoding="utf-8") as handle: + for row in rows: + handle.write(json.dumps(row, sort_keys=True) + "\n") + os.replace(temporary, path) + report = { + "format_version": 1, + "split": split, + "source_manifest": str(Path(source_manifest).resolve()), + "source_manifest_sha256": sha256_file(source_manifest), + "expanded_rows": len(dataset), + "selected_rows": len(selected), + "h1_rows": sum(int(row["history_length"]) == 1 for row in selected), + "per_history": { + str(history): sum(int(row["history_length"]) == history for row in selected) + for history in HISTORY_LENGTHS + }, + "per_stratum_non_h1": per_stratum, + "episode_start_only_histories": [1, 3, 6] + if config.training.protocol == "eval_aligned_epoch_world_v12" + else [1], + "h10_all_legal_starts": bool( + config.training.protocol == "eval_aligned_epoch_world_v12" + and config.predicted_future_cache.max_rows_per_history == 0 + ), + "base_windows": dataset.base_windows, + "cache_scope": "bounded_gate" + if config.predicted_future_cache.max_rows_per_history + else "formal_full", + "writer_rows": {str(rank): len(by_rank[rank]) for rank in range(8)}, + } + report["identity_sha256"] = canonical_sha256(report) + write_json_atomic(root / "selection.json", report) + return report + + +def _read_jsonl(path: Path) -> list[dict[str, Any]]: + with path.open(encoding="utf-8") as handle: + return [json.loads(line) for line in handle if line.strip()] + + +def _completed(root: Path, shard: int, rows: list[dict[str, Any]]) -> dict[str, Any] | None: + stem = f"shard-{shard:03d}" + meta_path = root / f"{stem}.json" + tensor_path = root / f"{stem}.bf16" + index_path = root / f"{stem}.index.jsonl" + if not (meta_path.is_file() and tensor_path.is_file() and index_path.is_file()): + return None + try: + meta = json.loads(meta_path.read_text()) + except (OSError, json.JSONDecodeError): + return None + valid = ( + int(meta.get("rows", -1)) == len(rows) + and int(meta.get("bytes", -1)) == len(rows) * ROW_BYTES + and meta.get("selection_sha256") == canonical_sha256(rows) + and tensor_path.stat().st_size == len(rows) * ROW_BYTES + and sha256_file(tensor_path) == meta.get("tensor_sha256") + and sha256_file(index_path) == meta.get("index_sha256") + ) + return meta if valid else None + + +def _make_world(config, device: torch.device): + world = load_world_config(config.artifacts.world_config) + system = WorldV6System(world.model) + checkpoint_metadata = json.loads( + (Path(config.artifacts.world_checkpoint) / "trainer_state.json").read_text( + encoding="utf-8" + ) + ) + source_step = int(checkpoint_metadata["completed_steps"]) + source = load_online_source( + system, + config.artifacts.world_checkpoint, + expected_step=source_step, + ) + if source["checkpoint_fingerprint"] != config.artifacts.world_checkpoint_sha256: + raise ValueError("configured World-v10 fingerprint differs from checkpoint") + system = system.to(device) + policy = MixedPrecisionPolicy( + param_dtype=torch.bfloat16, + reduce_dtype=torch.float32, + output_dtype=torch.bfloat16, + ) + if world.model.activation_checkpointing: + system.world_model.external_activation_checkpointing = True + for index, block in enumerate(system.world_model.blocks): + system.world_model.blocks[index] = checkpoint_wrapper( + block, + checkpoint_impl=CheckpointImpl.NO_REENTRANT, + preserve_rng_state=True, + ) + for block in system.world_model.blocks: + fully_shard(block, mp_policy=policy, reshard_after_forward=True) + fully_shard(system, mp_policy=policy, reshard_after_forward=True) + system.eval().requires_grad_(False) + return world, system + + +def _generate_split(config, world, system, split: str, rank: int, world_size: int, device: torch.device) -> None: + dataset = WorldV7Dataset( + source_manifest=(config.artifacts.train_source_manifest if split == "train" else config.artifacts.val_source_manifest), + dataset_stats=config.artifacts.state_stats, + qwen_cache_root=config.artifacts.qwen_hidden_cache_root, + split=split, + episode_cache_size=config.data.episode_cache_size, + ) + root = Path(config.predicted_future_cache.root) / split + rows = _read_jsonl(root / f"selection-{rank:02d}.jsonl") + rows_per_shard = int(config.predicted_future_cache.shard_rows) + local_chunks = math.ceil(len(rows) / rows_per_shard) + count = torch.tensor([local_chunks], dtype=torch.int64, device=device) + gathered = [torch.zeros_like(count) for _ in range(world_size)] + dist.all_gather(gathered, count) + total_chunks = max(int(value.item()) for value in gathered) + for chunk in range(total_chunks): + chunk_rows = rows[chunk * rows_per_shard : (chunk + 1) * rows_per_shard] + shard = chunk * world_size + rank + existing = _completed(root, shard, chunk_rows) if chunk_rows else {} + ready = torch.tensor([int(existing is not None)], device=device) + flags = [torch.zeros_like(ready) for _ in range(world_size)] + dist.all_gather(flags, ready) + if all(int(value) for value in flags): + if rank == 0: + print(json.dumps({"split": split, "chunk": chunk, "resume_skip": True}), flush=True) + continue + active = bool(chunk_rows) and existing is None + stem = f"shard-{shard:03d}" + tensor_partial = root / f".{stem}.bf16.partial" + index_partial = root / f".{stem}.index.jsonl.partial" + mapped = handle = None + if active: + with tensor_partial.open("wb") as output: + output.truncate(len(chunk_rows) * ROW_BYTES) + mapped = torch.from_file( + str(tensor_partial), shared=True, + size=len(chunk_rows) * PREDICTED_FUTURE_ELEMENTS, + dtype=torch.bfloat16, + ).reshape(len(chunk_rows), *PREDICTED_FUTURE_SHAPE) + handle = index_partial.open("w", encoding="utf-8") + cache_micro_batch = _cache_micro_batch(config) + local_batches = math.ceil(len(chunk_rows) / cache_micro_batch) + count.fill_(local_batches) + dist.all_gather(gathered, count) + total_batches = max(int(value.item()) for value in gathered) + padding = chunk_rows or rows + for batch_index in range(total_batches): + start = batch_index * cache_micro_batch + valid = max(0, min(cache_micro_batch, len(chunk_rows) - start)) + chosen = list(chunk_rows[start : start + valid]) + while len(chosen) < cache_micro_batch: + chosen.append(padding[(start + len(chosen)) % len(padding)]) + samples = [dataset[int(row["expanded_index"])] for row in chosen] + batch, _ = collate_world_v7(samples) + batch = batch.to(device) + noises = [] + for row in chosen: + generator = torch.Generator(device=device).manual_seed(int(row["world_seed"])) + noises.append(torch.randn(PREDICTED_FUTURE_SHAPE, generator=generator, device=device)) + noise = torch.stack(noises) + with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16): + raw = system( + z_context_raw=batch.z_context_raw, + z_future_raw=batch.z_future_raw, + state_history=batch.state_history, + history_valid=batch.history_valid, + context_valid=batch.context_valid, + future_valid=batch.future_valid, + view_valid=batch.view_valid, + qwen_hidden=batch.qwen_hidden, + qwen_mask=batch.qwen_mask, + sample_steps=config.world_inference.steps, + sample_noise=noise, + )["sample_future_raw"] + predicted = ((raw.float() - config.world_inference.latent_mean) / config.world_inference.latent_std).to(torch.bfloat16).cpu() + if not torch.isfinite(predicted).all(): + raise FloatingPointError("World-v10 cache generated non-finite future") + if active and valid: + assert mapped is not None and handle is not None + mapped[start : start + valid].copy_(predicted[:valid]) + for offset, row in enumerate(chunk_rows[start : start + valid]): + value = dict(row) + value.update({"shard": shard, "row": start + offset}) + handle.write(json.dumps(value, sort_keys=True) + "\n") + if batch_index % 50 == 0: + print(json.dumps({"split": split, "rank": rank, "chunk": chunk, "batch": batch_index, "batches": total_batches}), flush=True) + if handle is not None: + handle.flush(); os.fsync(handle.fileno()); handle.close() + if mapped is not None: + del mapped + _barrier() + if active: + tensor_path = root / f"{stem}.bf16" + index_path = root / f"{stem}.index.jsonl" + os.replace(tensor_partial, tensor_path) + os.replace(index_partial, index_path) + meta = { + "rows": len(chunk_rows), + "bytes": tensor_path.stat().st_size, + "tensor_file": tensor_path.name, + "index_file": index_path.name, + "selection_sha256": canonical_sha256(chunk_rows), + "tensor_sha256": sha256_file(tensor_path), + "index_sha256": sha256_file(index_path), + } + write_json_atomic(root / f"{stem}.json", meta) + _barrier() + + +def _finalize(config, split: str) -> dict[str, Any]: + root = Path(config.predicted_future_cache.root) / split + selection = json.loads((root / "selection.json").read_text()) + locators = torch.full((int(selection["expanded_rows"]),), -1, dtype=torch.int64) + shards: dict[str, Any] = {} + for rank in range(8): + rows = _read_jsonl(root / f"selection-{rank:02d}.jsonl") + rows_per_shard = int(config.predicted_future_cache.shard_rows) + for chunk, start in enumerate(range(0, len(rows), rows_per_shard)): + chosen = rows[start : start + rows_per_shard] + shard = chunk * 8 + rank + meta = _completed(root, shard, chosen) + if meta is None: + raise RuntimeError(f"missing/incomplete Action-v10 cache shard {split}/{shard}") + shards[str(shard)] = meta + for row_index, row in enumerate(chosen): + index = int(row["expanded_index"]) + if int(locators[index]) >= 0: + raise RuntimeError("duplicate Action-v10 cache locator") + locators[index] = encode_predicted_future_locator(shard, row_index) + if int((locators >= 0).sum()) != int(selection["selected_rows"]): + raise RuntimeError("Action-v10 locator count mismatch") + partial = root / ".locators.i64.partial" + locators.numpy().tofile(partial) + os.replace(partial, root / "locators.i64") + complete = { + **selection, + "locators_sha256": sha256_file(root / "locators.i64"), + "shards": shards, + } + complete["identity_sha256"] = canonical_sha256(complete) + write_json_atomic(root / "COMPLETE.json", complete) + return complete + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", required=True) + args = parser.parse_args() + config = load_config(args.config) + settings = set_up_distributed() + rank, world_size = settings.rank, settings.world_size + if world_size != 8: + raise RuntimeError("Action-v10 cache requires eight ranks") + process_prefix = os.environ.get("MIRA_V6_PROCESS_PREFIX", "filter_x_a11c") + set_world_v6_process_name(f"{process_prefix}{rank}") + device = torch.device("cuda", settings.device) + root = Path(config.predicted_future_cache.root) + if rank == 0: + root.mkdir(parents=True, exist_ok=True) + _select_split(config, "train", config.predicted_future_cache.train_rows_per_stratum_history) + _select_split(config, "val", config.predicted_future_cache.val_rows_per_stratum_history) + _barrier() + world, system = _make_world(config, device) + for split in ("train", "val"): + _generate_split(config, world, system, split, rank, world_size, device) + if rank == 0: + splits = {split: _finalize(config, split) for split in ("train", "val")} + world_metadata = json.loads( + ( + Path(config.artifacts.world_checkpoint) / "trainer_state.json" + ).read_text(encoding="utf-8") + ) + world_step = int(world_metadata["completed_steps"]) + identity = { + "format_version": 1, + "contract": ( + "action-v12-eval-aligned-full-epoch-world-v12-online" + if config.training.protocol == "eval_aligned_epoch_world_v12" + else "action-v11-short-history-world-v11-online" + if config.training.protocol == "h1_50_pred8k_world_v11" + else "action-v10-short-history-world-v10-online" + ), + "world_checkpoint": str(Path(config.artifacts.world_checkpoint).resolve()), + "world_checkpoint_fingerprint": checkpoint_fingerprint(config.artifacts.world_checkpoint), + "world_branch": "online", + "world_step": world_step, + "history_lengths": list(HISTORY_LENGTHS), + "h1_episode_start_only": True, + "episode_start_only_histories": ( + [1, 3, 6] + if config.training.protocol == "eval_aligned_epoch_world_v12" + else [1] + ), + "h10_all_legal_starts": bool( + config.training.protocol == "eval_aligned_epoch_world_v12" + and config.predicted_future_cache.max_rows_per_history == 0 + ), + "shard_rows": config.predicted_future_cache.shard_rows, + "solver": config.world_inference.sampler, + "steps": config.world_inference.steps, + "micro_batch_per_rank": _cache_micro_batch(config), + "seed_namespace": config.predicted_future_cache.seed_namespace, + "splits": splits, + } + identity["identity_sha256"] = canonical_sha256(identity) + write_json_atomic(config.predicted_future_cache.identity_file, identity) + print(json.dumps(identity, indent=2), flush=True) + _barrier() + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/action_v10/export_state_encoder.py b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v10/export_state_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..d921bd5e092c0890325908ebb4e4ce4803954df8 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v10/export_state_encoder.py @@ -0,0 +1,67 @@ +"""Export the exact frozen StateEncoder from the selected World-v10 Online checkpoint.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch +from safetensors.torch import save_file + +from mira.training.action_v6.artifacts import canonical_sha256, sha256_file, write_json_atomic +from mira.training.world_v8.checkpoint import checkpoint_fingerprint, load_online_source +from mira.training.world_v8.config import load_config +from mira.world_v6.model import WorldV6System + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--world-config", required=True) + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--output-root", required=True) + args = parser.parse_args() + checkpoint = Path(args.checkpoint).expanduser().resolve() + metadata = json.loads((checkpoint / "trainer_state.json").read_text(encoding="utf-8")) + if metadata.get("online_only") is not True: + raise ValueError("Action StateEncoder export requires Online-only World weights") + world_step = int(metadata["completed_steps"]) + if metadata.get("architecture") not in { + "bihub-world-v10-h1-50-high-lr-online", + "bihub-world-v11-h1-50-liftpot-continuation-online", + "bihub-world-v12-largebatch-remaining-online", + }: + raise ValueError("selected World checkpoint is not an audited H1-50 model") + config = load_config(args.world_config) + system = WorldV6System(config.model) + source = load_online_source(system, checkpoint, expected_step=world_step) + state = {name: value.detach().cpu().contiguous() for name, value in system.state_encoder.state_dict().items()} + if not state or not all(torch.isfinite(value).all() for value in state.values()): + raise FloatingPointError("World-v10 StateEncoder export is empty or non-finite") + output = Path(args.output_root).expanduser().resolve() + output.mkdir(parents=True, exist_ok=True) + state_path = output / "state_encoder_online.safetensors" + temporary = output / ".state_encoder_online.safetensors.tmp" + save_file(state, temporary) + temporary.replace(state_path) + report = { + "format_version": 1, + "contract": "action-short-history-frozen-state-encoder", + "world_checkpoint": str(checkpoint), + "world_checkpoint_fingerprint": checkpoint_fingerprint(checkpoint), + "world_branch": "online", + "world_step": world_step, + "world_architecture": metadata["architecture"], + "state_encoder": str(state_path), + "state_encoder_sha256": sha256_file(state_path), + "parameter_tensors": len(state), + "parameter_elements": sum(value.numel() for value in state.values()), + "source_load": source, + } + report["identity_sha256"] = canonical_sha256(report) + write_json_atomic(output / "selected_world_for_action.json", report) + print(json.dumps(report, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/action_v10/preflight.py b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v10/preflight.py new file mode 100644 index 0000000000000000000000000000000000000000..957ca00ff31734770ad6c849af3b0ea468cbadc6 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v10/preflight.py @@ -0,0 +1,233 @@ +"""Fail-closed semantic and artifact audit for Action-v10.""" + +from __future__ import annotations + +import argparse +import itertools +import json +from collections import Counter +from pathlib import Path + +import torch + +from mira.data.action_v10 import ActionV10Dataset, ActionV10Sampler +from mira.data.world_v7 import HISTORY_LENGTHS +from mira.training.action_v6.artifacts import action_source_identity, sha256_file +from mira.training.action_v6.config import load_config +from mira.training.action_v6.factory import build_action_stage, trainable_parameter_report +from mira.training.action_v6.train import _load_online_action_only +from mira.training.world_v8.checkpoint import checkpoint_fingerprint + + +def _require_file(path: str, expected_sha: str | None = None) -> Path: + value = Path(path).expanduser().resolve() + if not value.is_file(): + raise FileNotFoundError(value) + if expected_sha is not None and sha256_file(value) != expected_sha: + raise ValueError(f"SHA256 mismatch: {value}") + return value + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", required=True) + parser.add_argument("--require-cache", action="store_true") + args = parser.parse_args() + config = load_config(args.config) + if config.training.ema_decay != 0.0: + raise ValueError("Action-v10 must be Online-only (EMA disabled)") + is_v11 = config.training.protocol == "h1_50_pred8k_world_v11" + predicted_start = ( + 0 if is_v11 else config.training.predicted_future_curriculum[1].start + ) + expected_predicted_updates = 8_000 if is_v11 else 10_000 + if ( + args.require_cache + and config.training.steps - predicted_start != expected_predicted_updates + ): + raise ValueError( + f"phase must contain exactly {expected_predicted_updates} predicted updates" + ) + root = Path(__file__).resolve().parents[4] + source = action_source_identity(root) + if source["sha256"] != config.experiment.code_identity: + raise ValueError(f"source identity drift: actual={source['sha256']}") + _require_file(config.artifacts.codec_checkpoint, config.artifacts.codec_sha256) + _require_file(config.artifacts.state_encoder_ema, config.artifacts.state_encoder_ema_sha256) + _require_file(config.artifacts.world_config, config.artifacts.world_config_sha256) + checkpoint = Path(config.artifacts.world_checkpoint) + metadata = json.loads((checkpoint / "trainer_state.json").read_text(encoding="utf-8")) + expected_world = ( + ("bihub-world-v11-h1-50-liftpot-continuation-online", 50_000) + if is_v11 + else ("bihub-world-v10-h1-50-high-lr-online", 20_000) + ) + if ( + metadata.get("architecture") != expected_world[0] + or metadata.get("online_only") is not True + or int(metadata.get("completed_steps", -1)) != expected_world[1] + or checkpoint_fingerprint(checkpoint) != config.artifacts.world_checkpoint_sha256 + ): + raise ValueError("selected Online World checkpoint contract failed") + qwen_identity = json.loads(_require_file(config.artifacts.qwen_hidden_cache_identity).read_text()) + if ( + qwen_identity.get("complete") is not True + or qwen_identity.get("resampler_cached") is not False + or qwen_identity.get("history_lengths") != list(HISTORY_LENGTHS) + ): + raise ValueError("Qwen cache is not the complete pre-Resampler short-history cache") + predicted_root = config.predicted_future_cache.root if args.require_cache else None + train = ActionV10Dataset( + source_manifest=config.artifacts.train_source_manifest, + dataset_stats=config.artifacts.state_stats, + qwen_cache_root=config.artifacts.qwen_hidden_cache_root, + split="train", + latent_mean=config.world_inference.latent_mean, + latent_std=config.world_inference.latent_std, + predicted_cache_root=predicted_root, + predicted_world_fingerprint=config.artifacts.world_checkpoint_sha256 if args.require_cache else None, + episode_cache_size=1, + ) + # Audit exact temporal adjacency on one episode for all four history lengths. + temporal = [] + for history_index, history in enumerate(HISTORY_LENGTHS): + index = train.expanded_index(0, 0, history_index) + # Temporal adjacency is independent of future source; use GT because + # the sparse predicted cache intentionally does not contain every row. + sample = train[(index, 0)] + meta = sample["metadata"] + valid = int(sample["state_valid_mask"].sum()) + if int(meta["latent_start"]) != 0 or int(meta["current_latent"]) != history - 1: + raise RuntimeError(f"h{history} current-latent alignment failed") + if int(meta["action_start_20hz"]) != 2 * (history - 1) + 1 or valid != 2 * history: + raise RuntimeError(f"h{history} state/action adjacency failed") + if history == 1 and (valid != 2 or int(meta["current_latent"]) != 0): + raise RuntimeError("H1 is not true episode-start latent_start=0") + temporal.append({"history": history, "state_valid": valid, "current_latent": meta["current_latent"], "action_start": meta["action_start_20hz"]}) + # Reconstruct one complete global optimizer batch across all ranks. + counts: Counter[int] = Counter() + sources: Counter[int] = Counter() + supplemental_count = 0 + supplemental_index = None + if config.artifacts.supplemental_case_manifest is not None: + supplemental = json.loads( + Path(config.artifacts.supplemental_case_manifest).read_text(encoding="utf-8") + ) + supplemental_index = int(supplemental["sample"]["expanded_index"]) + for rank in range(8): + sampler = ActionV10Sampler( + train, + seed=2026, + rank=rank, + world_size=8, + micro_batch=4, + accumulation=16, + predicted_start_step=predicted_start, + supplemental_expanded_index=supplemental_index, + ) + sampler.predicted_start_step = predicted_start + if args.require_cache: + sampler.consumed = predicted_start * 64 + for index, future_source in itertools.islice(iter(sampler), 64): + supplemental_count += int(index == supplemental_index) + _episode, latent_start, history_index = train.locate(index) + history = HISTORY_LENGTHS[history_index] + counts[history] += 1 + sources[future_source] += 1 + if history == 1 and latent_start != 0: + raise RuntimeError("sampler emitted non-episode-start H1") + if counts[1] != 256 or sum(counts[h] for h in (3, 6, 10)) != 256 or sorted( + counts[h] for h in (3, 6, 10) + ) != [85, 85, 86]: + raise RuntimeError(f"global history allocation differs from 50%+equal remainder: {counts}") + expected_source = Counter({1 if args.require_cache else 0: 512}) + if sources != expected_source: + raise RuntimeError(f"future-source boundary failed: {sources}") + if supplemental_index is not None: + supplemental_sample = train[(supplemental_index, 1 if args.require_cache else 0)] + supplemental_metadata = supplemental_sample["metadata"] + if ( + supplemental_count != 1 + or supplemental_metadata["task"] != "lift_pot" + or supplemental_metadata["domain"] != "clean" + or int(supplemental_metadata["latent_start"]) != 0 + or int(supplemental_metadata["history_length"]) != 1 + or int(supplemental_sample["state_valid_mask"].sum()) != 2 + ): + raise RuntimeError("supplemental lift_pot Action sample contract failed") + if args.require_cache: + cached_histories = set() + assert train.predicted_cache is not None + for index in train.predicted_cache.available_indices: + history = HISTORY_LENGTHS[train.locate(index)[2]] + if history in cached_histories: + continue + sample = train[(index, 1)] + if sample["future_source"].item() != 1 or not torch.isfinite( + sample["z_future_cond"] + ).all(): + raise RuntimeError(f"invalid predicted cache sample for h{history}") + cached_histories.add(history) + if cached_histories == set(HISTORY_LENGTHS): + break + if cached_histories != set(HISTORY_LENGTHS): + raise RuntimeError(f"predicted cache lacks histories: {cached_histories}") + stage = build_action_stage(config) + frozen_before = { + name: value.clone() for name, value in stage.state_encoder.state_dict().items() + } + initialization = _load_online_action_only( + stage, + Path(str(config.checkpoint.initialize_from_online)).expanduser().resolve(), + expected_step=12_452 if is_v11 else 74_559, + expected_architecture=( + "bihub-wam-v10-action-h1-50" if is_v11 else "bihub-wam-v6-action" + ), + ) + if any( + not torch.equal(value, stage.state_encoder.state_dict()[name]) + for name, value in frozen_before.items() + ): + raise RuntimeError("step-74559 initialization overwrote the selected World-v10 StateEncoder") + report = trainable_parameter_report(stage) + if any(parameter.requires_grad for parameter in stage.state_encoder.parameters()): + raise RuntimeError("World StateEncoder is not frozen") + if report["trainable"] != report["transition_conditioner"] + report["action_flow"]: + raise RuntimeError("unexpected trainable parameter set") + resume_audit = None + if config.checkpoint.resume_from is not None: + resume = Path(config.checkpoint.resume_from).expanduser().resolve() + resume_metadata = json.loads((resume / "trainer_state.json").read_text()) + rank_state = torch.load(resume / "rank-00000.pth", map_location="cpu", weights_only=False) + expected_step = int(resume_metadata["completed_steps"]) + if expected_step != predicted_start: + raise RuntimeError("resume step and predicted boundary differ") + if int(rank_state["sampler"]["consumed"]) != expected_step * 64: + raise RuntimeError("resume sampler cursor does not match completed optimizer steps") + resume_audit = { + "checkpoint": str(resume), + "completed_steps": expected_step, + "sampler_consumed_per_rank": int(rank_state["sampler"]["consumed"]), + "scheduler_last_epoch": int(rank_state["scheduler"]["last_epoch"]), + "optimizer_scheduler_resume": True, + } + result = { + "passed": True, + "require_cache": args.require_cache, + "world_checkpoint_fingerprint": config.artifacts.world_checkpoint_sha256, + "source_identity": source["sha256"], + "temporal_alignment": temporal, + "global_history_counts": dict(counts), + "global_future_source_counts": dict(sources), + "parameter_report": report, + "action_initialization": initialization, + "resume_audit": resume_audit, + "predicted_updates": config.training.steps - predicted_start, + "supplemental_lift_pot_rows_per_global_batch": supplemental_count, + "cuda_devices": torch.cuda.device_count(), + } + print(json.dumps(result, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/action_v12/__init__.py b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v12/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..590d7a353f9c430882b00257d8c8b71504686571 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v12/__init__.py @@ -0,0 +1 @@ +"""Eval-aligned Action-v12 training utilities.""" diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/action_v12/preflight.py b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v12/preflight.py new file mode 100644 index 0000000000000000000000000000000000000000..ba5821f8ff21bf3bb748982dc604f2fbb925c4fe --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v12/preflight.py @@ -0,0 +1,272 @@ +"""Fail-closed audit for the final World-v12 conditioned Action epoch.""" + +from __future__ import annotations + +import argparse +import itertools +import json +import math +from collections import Counter +from pathlib import Path + +import torch + +from mira.data.action_v10 import ActionV10Dataset +from mira.data.action_v12 import ActionV12EpochSampler +from mira.data.world_v7 import HISTORY_LENGTHS +from mira.training.action_v6.artifacts import ( + action_source_identity, + canonical_sha256, + sha256_file, + write_json_atomic, +) +from mira.training.action_v6.config import load_config +from mira.training.action_v6.factory import build_action_stage, trainable_parameter_report +from mira.training.action_v6.train import _load_online_action_only +from mira.training.world_v8.checkpoint import checkpoint_fingerprint + + +def _require_file(path: str, expected_sha: str | None = None) -> Path: + value = Path(path).expanduser().resolve() + if not value.is_file(): + raise FileNotFoundError(value) + if expected_sha is not None and sha256_file(value) != expected_sha: + raise ValueError(f"SHA256 mismatch: {value}") + return value + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", required=True) + parser.add_argument("--report", required=True) + args = parser.parse_args() + config = load_config(args.config) + continuation = config.training.protocol == "eval_aligned_continue4_world_v12" + if config.training.protocol not in { + "eval_aligned_epoch_world_v12", + "eval_aligned_continue4_world_v12", + }: + raise ValueError("eval-aligned Action preflight received another protocol") + root = Path(__file__).resolve().parents[4] + source = action_source_identity(root) + if source["sha256"] != config.experiment.code_identity: + raise ValueError( + f"Action-v12 source identity drift: configured={config.experiment.code_identity} " + f"actual={source['sha256']}" + ) + _require_file(config.artifacts.codec_checkpoint, config.artifacts.codec_sha256) + _require_file(config.artifacts.state_encoder_ema, config.artifacts.state_encoder_ema_sha256) + _require_file(config.artifacts.world_config, config.artifacts.world_config_sha256) + _require_file( + config.artifacts.world_validation_report, + config.artifacts.world_validation_report_sha256, + ) + checkpoint = Path(config.artifacts.world_checkpoint).expanduser().resolve() + metadata = json.loads((checkpoint / "trainer_state.json").read_text()) + if ( + metadata.get("architecture") != "bihub-world-v12-largebatch-remaining-online" + or metadata.get("online_only") is not True + or int(metadata.get("completed_steps", -1)) != 25_066 + or checkpoint_fingerprint(checkpoint) != config.artifacts.world_checkpoint_sha256 + ): + raise ValueError("final Online World-v12 checkpoint contract failed") + selection = json.loads(_require_file(config.artifacts.world_selection_report).read_text()) + if ( + selection.get("world_checkpoint_fingerprint") + != config.artifacts.world_checkpoint_sha256 + or selection.get("world_branch") != "online" + or int(selection.get("world_step", -1)) != 25_066 + or selection.get("state_encoder_sha256") + != config.artifacts.state_encoder_ema_sha256 + ): + raise ValueError("World-v12 StateEncoder selection report mismatch") + qwen = json.loads(_require_file(config.artifacts.qwen_hidden_cache_identity).read_text()) + if ( + qwen.get("complete") is not True + or qwen.get("resampler_cached") is not False + or qwen.get("history_lengths") != list(HISTORY_LENGTHS) + ): + raise ValueError("Qwen hidden cache is not the full pre-Resampler cache") + cache_root = Path(config.predicted_future_cache.root).expanduser().resolve() + cache_identity_path = _require_file(config.predicted_future_cache.identity_file) + cache_identity = json.loads(cache_identity_path.read_text()) + expected_scope = ( + "formal_full" + if config.predicted_future_cache.max_rows_per_history == 0 + else "bounded_gate" + ) + if ( + cache_identity.get("contract") + != "action-v12-eval-aligned-full-epoch-world-v12-online" + or cache_identity.get("world_checkpoint_fingerprint") + != config.artifacts.world_checkpoint_sha256 + or cache_identity.get("episode_start_only_histories") != [1, 3, 6] + or bool(cache_identity.get("h10_all_legal_starts")) + != (expected_scope == "formal_full") + ): + raise ValueError("Action-v12 predicted cache identity mismatch") + datasets = {} + temporal = [] + for split in ("train", "val"): + dataset = ActionV10Dataset( + source_manifest=( + config.artifacts.train_source_manifest + if split == "train" + else config.artifacts.val_source_manifest + ), + dataset_stats=config.artifacts.state_stats, + qwen_cache_root=config.artifacts.qwen_hidden_cache_root, + split=split, + latent_mean=config.world_inference.latent_mean, + latent_std=config.world_inference.latent_std, + predicted_cache_root=cache_root, + predicted_world_fingerprint=config.artifacts.world_checkpoint_sha256, + episode_cache_size=1, + ) + datasets[split] = dataset + split_identity = cache_identity["splits"][split] + if split_identity.get("cache_scope") != expected_scope: + raise ValueError(f"{split} cache scope mismatch") + per_history = {int(key): int(value) for key, value in split_identity["per_history"].items()} + if expected_scope == "formal_full": + expected = { + 1: len(dataset.source_rows), + 3: len(dataset.source_rows), + 6: len(dataset.source_rows), + 10: dataset.world.base_windows, + } + if per_history != expected: + raise ValueError(f"{split} full cache coverage differs: {per_history} != {expected}") + for history_index, history in enumerate(HISTORY_LENGTHS): + index = dataset.expanded_index(0, 0, history_index) + sample = dataset[(index, 1)] + meta = sample["metadata"] + valid = int(sample["state_valid_mask"].sum()) + if ( + int(meta["latent_start"]) != 0 + or int(meta["current_latent"]) != history - 1 + or int(meta["action_start_20hz"]) != 2 * (history - 1) + 1 + or valid != 2 * history + or not torch.isfinite(sample["z_future_cond"]).all() + ): + raise RuntimeError(f"{split} h{history} temporal/cache alignment failed") + if split == "train": + temporal.append( + { + "history": history, + "latent_start": 0, + "current_latent": int(meta["current_latent"]), + "state_valid": valid, + "action_start_20hz": int(meta["action_start_20hz"]), + } + ) + train = datasets["train"] + if train.world.base_windows != config.data.epoch_h10_windows: + raise ValueError("configured H10 epoch length differs from dataset") + rows_per_history = config.training.global_batch // len(HISTORY_LENGTHS) + epoch_steps = math.ceil(train.world.base_windows / rows_per_history) + expected_steps = epoch_steps * (4 if continuation else 1) + if expected_steps != config.training.steps: + raise ValueError("Action-v12 optimizer steps do not cover exactly one H10 epoch") + curriculum = [ + (segment.start, segment.end, segment.start_p, segment.end_p) + for segment in config.training.predicted_future_curriculum + ] + counts: Counter[int] = Counter() + sources: Counter[int] = Counter() + starts: dict[int, set[int]] = {history: set() for history in HISTORY_LENGTHS} + for rank in range(8): + sampler = ActionV12EpochSampler( + train, + seed=config.experiment.seed, + rank=rank, + world_size=8, + micro_batch=config.training.micro_batch_per_gpu, + accumulation=config.training.grad_accumulation, + curriculum=curriculum, + optimizer_step_offset=config.data.sampler_step_offset, + ) + for index, source_id in itertools.islice( + iter(sampler), + config.training.micro_batch_per_gpu * config.training.grad_accumulation, + ): + _episode, latent_start, history_index = train.locate(index) + history = HISTORY_LENGTHS[history_index] + counts[history] += 1 + sources[source_id] += 1 + starts[history].add(latent_start) + if history in (1, 3, 6) and latent_start != 0: + raise RuntimeError(f"sampler emitted nonzero h{history} latent_start") + expected_history_counts = Counter( + {history: rows_per_history for history in HISTORY_LENGTHS} + ) + if counts != expected_history_counts: + raise RuntimeError(f"global history allocation differs: {counts}") + if sources != Counter({1: config.training.global_batch}): + raise RuntimeError(f"formal future source is not 100% World-v12 predicted: {sources}") + stage = build_action_stage(config) + frozen_before = { + name: value.clone() for name, value in stage.state_encoder.state_dict().items() + } + initialization = _load_online_action_only( + stage, + Path(config.checkpoint.initialize_from_online).expanduser().resolve(), + expected_step=5_754 if continuation else 8_000, + expected_architecture=( + "bihub-wam-v12-action-eval-aligned-epoch" + if continuation + else "bihub-wam-v11-action-h1-50-pred8k" + ), + ) + if any( + not torch.equal(value, stage.state_encoder.state_dict()[name]) + for name, value in frozen_before.items() + ): + raise RuntimeError("Action initialization overwrote final World-v12 StateEncoder") + parameters = trainable_parameter_report(stage) + if any(parameter.requires_grad for parameter in stage.state_encoder.parameters()): + raise RuntimeError("final World-v12 StateEncoder is not frozen") + if parameters["trainable"] != ( + parameters["transition_conditioner"] + parameters["action_flow"] + ): + raise RuntimeError("optimizer-visible parameter set is not the complete Action Head") + report = { + "passed": True, + "mode": config.runtime.mode, + "source_identity": source["sha256"], + "world_checkpoint_fingerprint": config.artifacts.world_checkpoint_sha256, + "cache_identity_sha256": sha256_file(cache_identity_path), + "cache_scope": expected_scope, + "train_episodes": len(train.source_rows), + "train_h10_windows": train.world.base_windows, + "epoch_steps": epoch_steps, + "additional_epochs": 4 if continuation else 1, + "training_steps": expected_steps, + "sampler_step_offset": config.data.sampler_step_offset, + "global_batch": config.training.global_batch, + "micro_batch_per_gpu": config.training.micro_batch_per_gpu, + "grad_accumulation": config.training.grad_accumulation, + "global_history_counts": dict(counts), + "global_future_source_counts": dict(sources), + "temporal_alignment": temporal, + "parameter_report": parameters, + "action_initialization": initialization, + "ema_enabled": False, + "optimizer": { + "name": "adamw", + "peak_lr": config.training.peak_lr, + "min_lr": config.training.min_lr, + "warmup_steps": config.training.warmup_steps, + "betas": config.training.betas, + "weight_decay": config.training.weight_decay, + "activation_checkpoint_blocks": config.training.activation_checkpoint_blocks, + }, + "cuda_devices": torch.cuda.device_count(), + } + report["identity_sha256"] = canonical_sha256(report) + write_json_atomic(args.report, report) + print(json.dumps(report, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/__init__.py b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f58be5bf52884fb6ff528d77b243495aa8684989 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/__init__.py @@ -0,0 +1 @@ +"""Training and audit entrypoints for the v6 Action Head.""" diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/artifacts.py b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/artifacts.py new file mode 100644 index 0000000000000000000000000000000000000000..553fa9c26fcb8631a1cf32004834f2c597a523b9 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/artifacts.py @@ -0,0 +1,79 @@ +"""Stable identities and transactional JSON helpers for Action v6.""" + +from __future__ import annotations + +import hashlib +import json +import os +from pathlib import Path +from typing import Any + + +def sha256_file(path: str | Path, *, chunk_size: int = 8 << 20) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + while block := handle.read(chunk_size): + digest.update(block) + return digest.hexdigest() + + +def canonical_sha256(value: Any) -> str: + payload = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + return hashlib.sha256(payload.encode("utf-8")).hexdigest() + + +def tree_identity(path: str | Path) -> dict[str, Any]: + root = Path(path).expanduser().resolve() + rows = [] + for item in sorted(value for value in root.rglob("*") if value.is_file()): + rows.append( + { + "path": item.relative_to(root).as_posix(), + "bytes": item.stat().st_size, + "sha256": sha256_file(item), + } + ) + identity = {"format_version": 1, "files": rows, "bytes": sum(row["bytes"] for row in rows)} + identity["sha256"] = canonical_sha256(identity) + return identity + + +def action_source_identity(repository_root: str | Path) -> dict[str, Any]: + root = Path(repository_root).expanduser().resolve() + patterns = ( + "src/mira/action_v6/**/*.py", + "src/mira/data/action_v6*.py", + "src/mira/data/action_v10*.py", + "src/mira/data/action_v12*.py", + "src/mira/training/action_v6/**/*.py", + "src/mira/training/action_v10/**/*.py", + "src/mira/training/action_v12/**/*.py", + "src/mira/training/ema.py", + "src/mira/benchmark/robotwin_v6/**/*.py", + "src/mira/inference/robotwin_v6_runtime.py", + "tests/action_v6/**/*.py", + "tests/action_v10/**/*.py", + "tests/action_v12/**/*.py", + ) + paths: set[Path] = set() + for pattern in patterns: + paths.update(path for path in root.glob(pattern) if path.is_file()) + rows = [ + {"path": path.relative_to(root).as_posix(), "sha256": sha256_file(path), "bytes": path.stat().st_size} + for path in sorted(paths) + ] + value = {"format_version": 1, "files": rows, "bytes": sum(row["bytes"] for row in rows)} + value["sha256"] = canonical_sha256(value) + return value + + +def write_json_atomic(path: str | Path, value: Any) -> None: + final = Path(path) + final.parent.mkdir(parents=True, exist_ok=True) + temporary = final.with_name(f".{final.name}.{os.getpid()}.tmp") + with temporary.open("w", encoding="utf-8") as handle: + json.dump(value, handle, indent=2, ensure_ascii=False, sort_keys=True, default=str) + handle.write("\n") + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, final) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/audit_predicted_future_cache.py b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/audit_predicted_future_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..23cbb632495d56d5b77a9d508f188fedb1427dc9 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/audit_predicted_future_cache.py @@ -0,0 +1,495 @@ +"""Structural, replay, split, collapse, and visual audit for Action future cache.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from collections import Counter, defaultdict +from pathlib import Path + +import torch +import torch.distributed as dist + +from mira.data.action_v6 import PREDICTED_FUTURE_ELEMENTS, PredictedFutureCacheReader +from mira.data.robotwin_wam_schema import read_jsonl +from mira.data.world_v6 import collate_world_v6, set_world_v6_process_name +from mira.inference.bihub_world_rollout import decode_comparison_video +from mira.training.distributed import set_up_distributed +from mira.training.visualization import write_video_ffmpeg + +from .artifacts import canonical_sha256, sha256_file, write_json_atomic +from .build_predicted_future_cache import ( + DIAGNOSTIC_WINDOWS_PER_STRATUM, + FUTURE_SHAPE, + WRITER_PARTITIONS, + _chunk_shard_id, + _diagnostic_keep_count, + _local_parameter_sha, + _make_world, + _train_keep_count, +) +from .config import load_config + + +def _barrier() -> None: + if dist.is_initialized(): + dist.barrier() + + +def _read_jsonl(path: Path) -> list[dict]: + with path.open(encoding="utf-8") as handle: + return [json.loads(line) for line in handle if line.strip()] + + +def _partition_selections(split_root: Path) -> dict[int, list[dict]]: + return { + partition: _read_jsonl(split_root / f"selection-{partition:02d}.jsonl") + for partition in range(WRITER_PARTITIONS) + } + + +def _expected_shard_rows( + selections: dict[int, list[dict]], metadata: dict, shard_rows: int +) -> list[dict]: + partition = int(metadata["partition"]) + chunk = int(metadata["chunk"]) + shard = int(metadata["shard"]) + if partition not in selections: + raise RuntimeError(f"invalid cache writer partition: {partition}") + if shard != _chunk_shard_id(partition, chunk): + raise RuntimeError( + f"cache shard/partition/chunk mismatch: shard={shard}, " + f"partition={partition}, chunk={chunk}" + ) + start = chunk * shard_rows + expected = selections[partition][start : start + shard_rows] + if len(expected) != int(metadata["rows"]): + raise RuntimeError(f"cache shard selection length mismatch: {shard}") + if canonical_sha256(expected) != metadata["selection_rows_sha256"]: + raise RuntimeError(f"cache shard selection identity mismatch: {shard}") + return expected + + +def _structural_audit(config) -> dict: + root = Path(config.predicted_future_cache.root) + identity = json.loads(Path(config.predicted_future_cache.identity_file).read_text()) + if identity["world_checkpoint_sha256"] != config.artifacts.world_checkpoint_sha256: + raise RuntimeError("cache/selected-World identity mismatch") + locked = { + "code_identity": config.experiment.code_identity, + "world_config_sha256": config.artifacts.world_config_sha256, + "anchor_identity_sha256": config.artifacts.anchor_identity_sha256, + "codec_sha256": config.artifacts.codec_sha256, + "seed_namespace": config.predicted_future_cache.seed_namespace, + "train_window_manifest_sha256": config.artifacts.train_window_manifest_sha256, + "validation_window_manifest_sha256": config.artifacts.validation_window_manifest_sha256, + } + for key, expected in locked.items(): + if identity.get(key) != expected: + raise RuntimeError(f"cache identity contract mismatch for {key}") + output = {"splits": {}, "full_finite_rows": 0} + for split in ("train", "val", "val_sample1"): + split_root = root / split + complete = json.loads((split_root / "COMPLETE.json").read_text()) + if complete["identity_sha256"] != identity["splits"][split]["identity_sha256"]: + raise RuntimeError(f"cache split COMPLETE/main identity mismatch: {split}") + selection = json.loads((split_root / "selection.json").read_text()) + if sha256_file(split_root / "selection.json") != complete["selection_sha256"]: + raise RuntimeError(f"cache selection checksum failed: {split}") + if sha256_file(split_root / "locators.i64") != complete["locators_sha256"]: + raise RuntimeError(f"cache locator checksum failed: {split}") + selections = _partition_selections(split_root) + for partition, rows in selections.items(): + if len(rows) != int(selection["writer_partitions"][str(partition)]): + raise RuntimeError( + f"cache writer-partition selection count mismatch: {split}/{partition}" + ) + selected = [row for partition in range(WRITER_PARTITIONS) for row in selections[partition]] + expected_shards = { + _chunk_shard_id(partition, chunk) + for partition, rows in selections.items() + for chunk, _start in enumerate(range(0, len(rows), int(complete["shard_rows"]))) + } + actual_shards = {int(value) for value in identity["splits"][split]["shards"]} + if actual_shards != expected_shards: + raise RuntimeError(f"cache shard coverage mismatch: {split}") + finite_rows = 0 + for shard_text, metadata in sorted( + identity["splits"][split]["shards"].items(), key=lambda item: int(item[0]) + ): + shard = int(shard_text) + if int(metadata["shard"]) != shard: + raise RuntimeError(f"cache shard key/metadata mismatch: {split}/{shard}") + expected_rows = _expected_shard_rows( + selections, metadata, int(complete["shard_rows"]) + ) + metadata_path = split_root / metadata["metadata_file"] + if json.loads(metadata_path.read_text()) != metadata: + raise RuntimeError(f"cache shard metadata/identity mismatch: {split}/{shard}") + tensor_path = split_root / metadata["tensor_file"] + index_path = split_root / metadata["index_file"] + if sha256_file(tensor_path) != metadata["tensor_sha256"]: + raise RuntimeError(f"cache tensor checksum failed: {split}/{shard}") + if sha256_file(index_path) != metadata["index_sha256"]: + raise RuntimeError(f"cache index checksum failed: {split}/{shard}") + rows = int(metadata["rows"]) + index_rows = _read_jsonl(index_path) + if len(index_rows) != rows: + raise RuntimeError(f"cache index row count mismatch: {split}/{shard}") + tensor = torch.from_file( + str(tensor_path), shared=False, size=rows * PREDICTED_FUTURE_ELEMENTS, dtype=torch.bfloat16 + ).reshape(rows, *FUTURE_SHAPE) + for start in range(0, rows, 64): + value = tensor[start : start + 64] + if not torch.isfinite(value).all(): + raise FloatingPointError(f"non-finite cache tensor: {split}/{shard}/{start}") + finite_rows += len(value) + for row_index, (expected, index_row) in enumerate(zip(expected_rows, index_rows)): + for key in ( + "dataset_index", + "window_id", + "episode_sha256", + "task", + "domain", + "latent_start", + "world_seed", + "partition", + "partition_row", + ): + if index_row.get(key) != expected.get(key): + raise RuntimeError( + f"cache index/selection mismatch: {split}/{shard}/{row_index}/{key}" + ) + if int(index_row.get("shard", -1)) != shard or int( + index_row.get("row", -1) + ) != row_index: + raise RuntimeError( + f"cache index locator mismatch: {split}/{shard}/{row_index}" + ) + tensor_bytes = ( + tensor[row_index].contiguous().view(torch.uint8).numpy().tobytes() + ) + if hashlib.sha256(tensor_bytes).hexdigest() != index_row.get("tensor_sha256"): + raise RuntimeError( + f"cache row checksum failed: {split}/{shard}/{row_index}" + ) + if len(selected) != int(selection["selected_windows"]): + raise RuntimeError(f"cache selected row mismatch: {split}") + if len({row["window_id"] for row in selected}) != len(selected): + raise RuntimeError(f"duplicate window id inside cache split: {split}") + output["splits"][split] = { + "manifest_windows": int(selection["manifest_windows"]), + "selected_windows": len(selected), + "finite_rows": finite_rows, + "complete_identity_sha256": complete["identity_sha256"], + } + output["full_finite_rows"] += finite_rows + if split == "train": + actual_by_episode = Counter(str(row["episode_sha256"]) for row in selected) + expected_by_episode = {} + expected_by_stratum: Counter[str] = Counter() + for source_row in read_jsonl(config.artifacts.train_source_manifest): + episode = str(source_row["episode_sha256"]) + available = int(source_row["n_latents"]) - 19 + expected = _train_keep_count( + available, + config.predicted_future_cache.train_fraction_per_episode, + ) + expected_by_episode[episode] = expected + expected_by_stratum[ + f"{source_row['task']}/{source_row['domain']}" + ] += expected + episode_mismatches = { + episode: { + "expected": expected, + "actual": actual_by_episode.get(episode, 0), + } + for episode, expected in expected_by_episode.items() + if actual_by_episode.get(episode, 0) != expected + } + unexpected_episodes = sorted(set(actual_by_episode) - set(expected_by_episode)) + if episode_mismatches or unexpected_episodes: + raise RuntimeError( + "predicted train cache violates the formal per-episode selection rule: " + f"mismatches={len(episode_mismatches)}, " + f"unexpected={len(unexpected_episodes)}" + ) + totals = selection["task_domain_total"] + counts = selection["task_domain_selected"] + stratum_mismatches = { + key: {"expected": expected, "actual": counts.get(key, 0)} + for key, expected in expected_by_stratum.items() + if counts.get(key, 0) != expected + } + if stratum_mismatches: + raise RuntimeError( + "predicted train stratum counts disagree with per-episode quotas: " + f"{stratum_mismatches}" + ) + ratios = {key: counts[key] / totals[key] for key in totals} + outside_nominal_band = { + key: value + for key, value in ratios.items() + if not 0.195 <= value <= 0.205 + } + output["train_ratio_min"] = min(ratios.values()) + output["train_ratio_max"] = max(ratios.values()) + output["train_selection_protocol"] = { + "formula": "max(1, round(fraction * episode_valid_windows))", + "fraction": config.predicted_future_cache.train_fraction_per_episode, + "episodes": len(expected_by_episode), + "episode_count_mismatches": 0, + "stratum_count_mismatches": 0, + "nominal_task_domain_ratio_band": [0.195, 0.205], + "task_domain_ratios_outside_nominal_band": outside_nominal_band, + "note": ( + "The per-episode one-window floor and integer rounding are the formal " + "selection contract; short episodes can make aggregate stratum ratios " + "fall outside the nominal band." + ), + } + elif split == "val" and len(selected) != 29_668: + raise RuntimeError("primary validation cache must include every validation window") + elif split == "val_sample1": + totals = selection["task_domain_total"] + counts = selection["task_domain_selected"] + expected_counts = { + key: _diagnostic_keep_count(total) for key, total in totals.items() + } + bad = { + key: {"expected": expected, "actual": counts.get(key, 0)} + for key, expected in expected_counts.items() + if counts.get(key, 0) != expected + } + expected_windows = sum(expected_counts.values()) + if bad or len(selected) != expected_windows: + raise RuntimeError( + f"sample-1 diagnostic coverage mismatch: rows={len(selected)}, " + f"expected={expected_windows}, strata={bad}" + ) + short_strata = { + key: { + "available_windows": totals[key], + "selected_windows": counts[key], + } + for key in totals + if totals[key] < DIAGNOSTIC_WINDOWS_PER_STRATUM + } + declared = selection.get("diagnostic_selection") + expected_protocol = { + "requested_windows_per_stratum": DIAGNOSTIC_WINDOWS_PER_STRATUM, + "selection_rule": "min(requested_windows_per_stratum, available_valid_windows)", + "expected_windows": expected_windows, + "short_strata": short_strata, + } + if declared != expected_protocol: + raise RuntimeError("sample-1 diagnostic protocol metadata mismatch") + output["splits"][split]["diagnostic_selection"] = expected_protocol + train_ids = {row["episode_sha256"] for row in read_jsonl(config.artifacts.train_source_manifest)} + val_ids = {row["episode_sha256"] for row in read_jsonl(config.artifacts.val_source_manifest)} + if train_ids & val_ids: + raise RuntimeError("train/validation episode overlap") + output["episode_overlap"] = 0 + return output + + +@torch.inference_mode() +def _online_replay(config, rank, world_size, device) -> dict[str, float]: + world_config, system, ema = _make_world(config, device, rank, world_size) + train_dataset = __import__("mira.training.world_v6.train", fromlist=["_dataset"])._dataset(world_config, "train") + reader = PredictedFutureCacheReader( + config.predicted_future_cache.root, + "train", + expected_windows=len(train_dataset), + expected_manifest_sha256=config.artifacts.train_window_manifest_sha256, + expected_world_sha256=config.artifacts.world_checkpoint_sha256, + ) + rows = [ + row + for partition_rows in _partition_selections( + Path(config.predicted_future_cache.root) / "train" + ).values() + for row in partition_rows + ] + rows.sort(key=lambda row: row["window_id"]) + selected = [rows[index] for index in torch.linspace(0, len(rows) - 1, 256).long().tolist()] + local = selected[rank::world_size] + totals = torch.zeros(10, dtype=torch.float64, device=device) + with ema.average_parameters(): + frozen_before = _local_parameter_sha(system) + for start in range(0, len(local), 4): + chosen = local[start : start + 4] + samples = [train_dataset[int(row["dataset_index"])] for row in chosen] + batch, metadata = collate_world_v6(samples) + batch = batch.to(device) + assert batch.anchors is not None + noise = [] + for row in chosen: + generator = torch.Generator(device=device).manual_seed(int(row["world_seed"])) + noise.append(torch.randn(FUTURE_SHAPE, generator=generator, device=device)) + with torch.autocast("cuda", dtype=torch.bfloat16): + raw = system( + z_context_raw=batch.z_context_raw, + z_future_raw=batch.z_future_raw, + anchors=batch.anchors, + state_history=batch.state_history, + history_valid=batch.history_valid, + future_valid=batch.future_valid, + view_valid=batch.view_valid, + sample_steps=10, + sample_noise=torch.stack(noise), + )["sample_future_raw"] + online = ((raw.float() - config.world_inference.latent_mean) / config.world_inference.latent_std).to(torch.bfloat16).cpu() + cached = torch.stack([reader[int(row["dataset_index"])] for row in chosen]) + difference = online.float() - cached.float() + gt = ((batch.z_future_raw.float().cpu() - config.world_inference.latent_mean) / config.world_inference.latent_std) + current = ((batch.z_context_raw[:, :, -1:].float().cpu() - config.world_inference.latent_mean) / config.world_inference.latent_std) + static = current.expand_as(gt) + predicted_sequence = torch.cat([current, cached.float()], dim=2) + gt_sequence = torch.cat([current, gt], dim=2) + predicted_delta = ( + predicted_sequence[:, :, 1:] - predicted_sequence[:, :, :-1] + ).square().flatten(1).mean(1) + gt_delta = ( + gt_sequence[:, :, 1:] - gt_sequence[:, :, :-1] + ).square().flatten(1).mean(1) + totals[0] += difference.square().sum().to(device) + totals[1] += difference.numel() + totals[2] = torch.maximum(totals[2], difference.abs().max().to(device).double()) + totals[3] += (cached.float() - gt).square().sum().to(device) + totals[4] += (cached.float() - static).square().sum().to(device) + totals[5] += cached.numel() + totals[6] += predicted_delta.sum().to(device) + totals[7] += gt_delta.sum().to(device) + totals[8] += (predicted_delta < 0.1 * gt_delta.clamp_min(1.0e-12)).sum().to(device) + totals[9] += len(chosen) + frozen_after = _local_parameter_sha(system) + if frozen_before != frozen_after: + raise RuntimeError("World/State hash changed during online cache replay") + max_value = totals[2].clone() + dist.all_reduce(totals, op=dist.ReduceOp.SUM) + dist.all_reduce(max_value, op=dist.ReduceOp.MAX) + predicted_delta_mse = totals[6] / totals[9].clamp_min(1) + gt_delta_mse = totals[7] / totals[9].clamp_min(1) + return { + "rows": 256.0, + "replay_mse": float(totals[0] / totals[1]), + "replay_max_abs": float(max_value), + "predicted_vs_gt_mse": float(totals[3] / totals[5]), + "predicted_vs_static_mse": float(totals[4] / totals[5]), + "predicted_delta_mse": float(predicted_delta_mse), + "gt_delta_mse": float(gt_delta_mse), + "predicted_to_gt_delta_ratio": float(predicted_delta_mse / gt_delta_mse.clamp_min(1.0e-12)), + "collapse_tail_fraction": float(totals[8] / totals[9].clamp_min(1)), + } + + +@torch.inference_mode() +def _decode_cases(config, device: torch.device) -> dict: + from mira.codec.codec_model import VideoCodec + from mira.training.world_v6.config import load_config as load_world_config + from mira.training.world_v6.train import _dataset + + world = load_world_config(config.artifacts.world_config) + dataset = _dataset(world, "val") + reader = PredictedFutureCacheReader( + config.predicted_future_cache.root, + "val", + expected_windows=len(dataset), + expected_manifest_sha256=config.artifacts.validation_window_manifest_sha256, + expected_world_sha256=config.artifacts.world_checkpoint_sha256, + ) + rows = [ + row + for partition_rows in _partition_selections( + Path(config.predicted_future_cache.root) / "val" + ).values() + for row in partition_rows + ] + strata: dict[str, list[dict]] = defaultdict(list) + for row in sorted(rows, key=lambda value: value["window_id"]): + strata[f"{row['task']}/{row['domain']}"].append(row) + selected = [values[0] for _, values in sorted(strata.items())] + if len(selected) != 100: + raise RuntimeError("decode audit requires one case per task/domain stratum") + codec = VideoCodec.load_from_checkpoint(config.artifacts.codec_checkpoint, device="cpu") + decoder = codec.decoder.eval().requires_grad_(False).to(device) + del codec + root = Path(config.experiment.artifact_root) / "predicted_future_decode_audit" + root.mkdir(parents=True, exist_ok=True) + for case_index, row in enumerate(selected): + sample = dataset[int(row["dataset_index"])] + prediction_norm = reader[int(row["dataset_index"])].float() + prediction = prediction_norm * config.world_inference.latent_std + config.world_inference.latent_mean + video = decode_comparison_video( + decoder, + sample["z_context_raw"].float(), + sample["z_future_raw"].float(), + prediction, + device=device, + ) + final = root / f"case-{case_index:03d}-{row['task']}-{row['domain']}.mp4" + temporary = final.with_name(f".{final.name}.tmp.mp4") + write_video_ffmpeg(temporary, video, fps=10, preset="fast") + temporary.replace(final) + torch.save( + { + "metadata": row, + "context_raw": sample["z_context_raw"], + "target_raw": sample["z_future_raw"], + "prediction_raw": prediction, + }, + final.with_suffix(".pth"), + ) + return {"cases": len(selected), "root": str(root)} + + +def audit(config_path: str) -> None: + config = load_config(config_path) + settings = set_up_distributed() + rank, world_size = settings.rank, settings.world_size + if world_size != 8: + raise RuntimeError("online predicted-cache replay requires eight ranks") + set_world_v6_process_name(f"syncnet_v6_aaudit{rank}") + device = torch.device("cuda", settings.device) + structural = _structural_audit(config) if rank == 0 else None + _barrier() + replay = _online_replay(config, rank, world_size, device) + if ( + replay["replay_max_abs"] > 5.0e-3 + or replay["predicted_vs_gt_mse"] <= 1.0e-8 + or not 0.05 <= replay["predicted_to_gt_delta_ratio"] <= 20.0 + ): + raise RuntimeError(f"predicted-cache online replay/distribution gate failed: {replay}") + _barrier() + decoded = _decode_cases(config, device) if rank == 0 else None + _barrier() + if rank == 0: + report = { + "format_version": 1, + "passed": True, + "cache_identity_sha256": sha256_file(config.predicted_future_cache.identity_file), + "structural": structural, + "online_replay": replay, + "decode_audit": decoded, + "timeline_contract": { + "first_transition_source": "real_z_current", + "last_transition_target": "predicted_future_index_9", + "view_order": ["left", "global", "right"], + }, + } + report["identity_sha256"] = canonical_sha256(report) + write_json_atomic(Path(config.experiment.artifact_root) / "reports" / "cache_audit.json", report) + print(json.dumps(report, indent=2)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", required=True) + args = parser.parse_args() + audit(args.config) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/build_critical_event_index.py b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/build_critical_event_index.py new file mode 100644 index 0000000000000000000000000000000000000000..e770f99b41d4125ed375dbe6a21e85b7bc6d454d --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/build_critical_event_index.py @@ -0,0 +1,96 @@ +"""Index expert windows containing a real gripper transition and World prediction.""" + +from __future__ import annotations + +import argparse +import json +import os +from collections import Counter +from pathlib import Path + +import numpy as np +from safetensors.torch import load_file + +from mira.data.action_v6 import ActionV6Dataset +from mira.training.action_v6.artifacts import canonical_sha256, sha256_file, write_json_atomic +from mira.training.action_v6.config import load_config + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", required=True) + parser.add_argument("--output", required=True) + args = parser.parse_args() + config = load_config(args.config) + dataset = ActionV6Dataset( + source_manifest=config.artifacts.train_source_manifest, + window_manifest=config.artifacts.train_window_manifest, + window_index=config.artifacts.train_window_index, + dataset_stats=config.artifacts.state_stats, + dataset_root=Path(config.artifacts.state_stats).parents[1], + anchors_root=None, + need_rgb=False, + episode_cache_size=1, + latent_mean=config.world_inference.latent_mean, + latent_std=config.world_inference.latent_std, + predicted_cache_root=config.predicted_future_cache.root, + predicted_world_sha256=config.artifacts.world_checkpoint_sha256, + split="train", + ) + if dataset.predicted_cache is None: + raise RuntimeError("critical-event index requires predicted futures") + selected: list[int] = [] + strata: Counter[str] = Counter() + for episode_index, row in enumerate(dataset.source_rows): + episode = load_file(str(row["cache_path"]), device="cpu") + actions = episode["action20_f32"].float().reshape(-1, 2, 7) + for latent_start in range(dataset.source_window_counts[episode_index]): + action_start = 2 * latent_start + 19 + chunk = actions[action_start : action_start + 20] + gripper = chunk[:, :, 6] + if chunk.shape[0] != 20: + raise RuntimeError("truncated action chunk while indexing critical events") + gripper_event = bool(((gripper.amax(0) - gripper.amin(0)).abs() > 0.5).any()) + high_joint_motion = bool( + ((chunk[:, :, :6].amax(0) - chunk[:, :, :6].amin(0)).abs() > 0.25).any() + ) + if not (gripper_event or high_joint_motion): + continue + index = dataset.source_window_index(episode_index, latent_start) + if not dataset.predicted_cache.has(index): + continue + selected.append(index) + strata[f"{row['task']}/{row['domain']}"] += 1 + if (episode_index + 1) % 1000 == 0: + print(json.dumps({"episodes": episode_index + 1, "selected": len(selected)}), flush=True) + missing = [ + f"{task}/{domain}" + for task, domains in dataset.task_domain_episodes.items() + for domain in domains + if strata[f"{task}/{domain}"] == 0 + ] + if missing: + raise RuntimeError(f"critical index leaves empty task/domain strata: {missing}") + output = Path(args.output).expanduser().resolve() + output.parent.mkdir(parents=True, exist_ok=True) + temporary = output.with_name(f".{output.name}.{os.getpid()}.tmp") + np.asarray(selected, dtype=np.int64).tofile(temporary) + os.replace(temporary, output) + report = { + "format_version": 1, + "definition": "gripper_range_gt_0.5_or_joint_range_gt_0.25_over_next20_and_predicted_future_available", + "rows": len(selected), + "dataset_windows": len(dataset), + "index_path": str(output), + "index_sha256": sha256_file(output), + "train_window_manifest_sha256": dataset.window_manifest_sha256, + "predicted_future_identity_sha256": config.predicted_future_cache.identity_sha256, + "task_domain_rows": dict(sorted(strata.items())), + } + report["identity_sha256"] = canonical_sha256(report) + write_json_atomic(output.with_suffix(".json"), report) + print(json.dumps(report, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/build_exact_cold_cache.py b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/build_exact_cold_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..fbe06b52c42335caf0eb5f4d7b29ab08b7ab1bdb --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/build_exact_cold_cache.py @@ -0,0 +1,246 @@ +"""Build deployment-exact cold-start supervision for Action-v7. + +Each source episode contributes one sample. The observation and state histories +repeat the real initial simulator observation exactly as the deployed policy +does before its first replan. World-v6 EMA then predicts the conditioning +future from that repeated history; the target remains the recorded expert's +next 20 absolute joint targets. No student action is ever used as a label. +""" + +from __future__ import annotations + +import argparse +import hashlib +import io +import json +import os +import time +import zipfile +from pathlib import Path +from typing import Any + +import h5py +import numpy as np +import torch +import torch.distributed as dist +from safetensors.torch import load_file, save_file +from torchvision.io import ImageReadMode, decode_jpeg + +from mira.data.robotwin_wam_schema import read_jsonl, sha256_file +from mira.data.world_v6 import CAMERA_PATHS, preprocess_qwen_rgb +from mira.inference.robotwin_v6_runtime import BiHubWAMRuntime +from mira.training.action_v6.artifacts import canonical_sha256, write_json_atomic + + +def _seed(episode_sha256: str, world_sha256: str) -> int: + payload = f"action-v7-exact-cold\0{episode_sha256}\0{world_sha256}" + return int.from_bytes(hashlib.sha256(payload.encode()).digest()[:8], "big") % (2**63 - 1) + + +def _initial_rgb(dataset_root: Path, row: dict[str, Any]) -> np.ndarray: + with zipfile.ZipFile(dataset_root / str(row["archive"])) as archive: + payload = archive.read(str(row["member"])) + with h5py.File(io.BytesIO(payload), "r") as episode: + encoded = [ + torch.frombuffer(bytearray(bytes(episode[path][0])), dtype=torch.uint8) + for path in CAMERA_PATHS + ] + images = decode_jpeg(encoded, mode=ImageReadMode.RGB) + if not isinstance(images, list) or len(images) != 3: + raise RuntimeError("initial RGB decode did not return three views") + shapes = {tuple(image.shape) for image in images} + if len(shapes) != 1: + raise RuntimeError(f"initial RGB views differ in geometry: {sorted(shapes)}") + return torch.stack(images).permute(0, 2, 3, 1).contiguous().numpy() + + +@torch.inference_mode() +def _build_one( + runtime: BiHubWAMRuntime, + dataset_root: Path, + row: dict[str, Any], +) -> dict[str, torch.Tensor]: + initial_rgb = _initial_rgb(dataset_root, row) + rgb_history = np.repeat(initial_rgb[:, None], 20, axis=1) + context_raw = runtime.encode_history(rgb_history)[None] + + episode = load_file(str(row["cache_path"]), device="cpu") + initial_state = episode["joint_target_state20_f32"][0].float() + state_raw = initial_state[None].repeat(20, 1).to(runtime.device) + state = runtime._normalize_state(state_raw).reshape(1, 20, 2, 7) + valid = torch.ones(1, 20, dtype=torch.bool, device=runtime.device) + + current_rgb = torch.from_numpy(initial_rgb).permute(0, 3, 1, 2) + current_rgb = preprocess_qwen_rgb(current_rgb.to(torch.uint8))[None] + with torch.autocast("cuda", dtype=torch.bfloat16): + qwen_hidden, qwen_mask = runtime.qwen(current_rgb, [str(row["instruction"])]) + runtime.qwen.assert_frozen() + + generator = torch.Generator(device=runtime.device).manual_seed( + _seed(str(row["episode_sha256"]), runtime.config.artifacts.world_checkpoint_sha256) + ) + noise = torch.randn( + (1, 3, 10, 32, 9, 12), generator=generator, device=runtime.device + ) + with torch.autocast("cuda", dtype=torch.bfloat16): + future_raw = runtime.world( + z_context_raw=context_raw, + z_future_raw=torch.empty_like(context_raw), + state_history=state, + history_valid=valid, + future_valid=torch.ones(1, 10, dtype=torch.bool, device=runtime.device), + view_valid=torch.ones(1, 3, dtype=torch.bool, device=runtime.device), + qwen_hidden=qwen_hidden, + qwen_mask=qwen_mask, + sample_steps=10, + sample_noise=noise, + )["sample_future_raw"] + mean = float(runtime.config.world_inference.latent_mean) + std = float(runtime.config.world_inference.latent_std) + action = episode["action20_f32"][:20].float().reshape(20, 2, 7) + if action.shape != (20, 2, 7): + raise RuntimeError("expert episode is shorter than the initial 20-action target") + values = { + "z_current": ((context_raw[0, :, -1:] - mean) / std).to(torch.bfloat16).cpu(), + "z_future_cond": ((future_raw[0] - mean) / std).to(torch.bfloat16).cpu(), + "state_history": state[0].float().cpu(), + "action_gt": action.cpu(), + "initial_state": initial_state.reshape(2, 7).cpu(), + } + if not all(bool(torch.isfinite(value).all()) for value in values.values()): + raise FloatingPointError("non-finite exact-cold cache tensor") + return values + + +def _parse() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--action-checkpoint", required=True) + parser.add_argument("--source-manifest", required=True) + parser.add_argument("--dataset-root", required=True) + parser.add_argument("--output-root", required=True) + parser.add_argument("--split", choices=("train", "val"), required=True) + parser.add_argument("--max-episodes", type=int) + parser.add_argument("--balanced-one-per-stratum", action="store_true") + return parser.parse_args() + + +def main() -> None: + args = _parse() + rank = int(os.environ.get("RANK", "0")) + world_size = int(os.environ.get("WORLD_SIZE", "1")) + local_rank = int(os.environ.get("LOCAL_RANK", "0")) + if world_size > 1: + dist.init_process_group("gloo") + torch.cuda.set_device(local_rank) + + manifest = Path(args.source_manifest).expanduser().resolve() + rows = read_jsonl(manifest) + if args.balanced_one_per_stratum: + selected = [] + seen: set[tuple[str, str]] = set() + for row in rows: + key = (str(row["task"]), str(row["domain"])) + if key not in seen: + seen.add(key) + selected.append(row) + rows = selected + if args.max_episodes is not None: + if args.max_episodes <= 0: + raise ValueError("max-episodes must be positive") + rows = rows[: args.max_episodes] + output = Path(args.output_root).expanduser().resolve() / args.split + output.mkdir(parents=True, exist_ok=True) + runtime = BiHubWAMRuntime(action_checkpoint=args.action_checkpoint, device=f"cuda:{local_rank}") + started = time.monotonic() + built = skipped = 0 + for index in range(rank, len(rows), world_size): + row = rows[index] + episode_sha = str(row["episode_sha256"]) + tensor_path = output / "episodes" / episode_sha[:2] / f"{episode_sha}.safetensors" + metadata_path = tensor_path.with_suffix(".json") + if tensor_path.is_file() and metadata_path.is_file(): + metadata = json.loads(metadata_path.read_text(encoding="utf-8")) + if metadata.get("tensor_sha256") == sha256_file(tensor_path): + skipped += 1 + continue + tensor_path.parent.mkdir(parents=True, exist_ok=True) + values = _build_one(runtime, Path(args.dataset_root).expanduser().resolve(), row) + temporary = tensor_path.with_name(f".{tensor_path.name}.{os.getpid()}.tmp") + save_file(values, temporary) + os.replace(temporary, tensor_path) + movement = float( + (values["action_gt"][:8] - values["initial_state"][None]).abs().amax().item() + ) + metadata = { + "format_version": 1, + "split": args.split, + "source_index": index, + "episode_sha256": episode_sha, + "task": str(row["task"]), + "domain": str(row["domain"]), + "instruction": str(row["instruction"]), + "tensor_path": str(tensor_path), + "tensor_sha256": sha256_file(tensor_path), + "source_cache_sha256": sha256_file(Path(str(row["cache_path"]))), + "world_seed": _seed(episode_sha, runtime.config.artifacts.world_checkpoint_sha256), + "expert_first8_max_delta": movement, + } + metadata["identity_sha256"] = canonical_sha256(metadata) + write_json_atomic(metadata_path, metadata) + built += 1 + if built <= 3 or built % 25 == 0: + rate = built / max(time.monotonic() - started, 1e-6) + print( + json.dumps( + {"rank": rank, "built": built, "skipped": skipped, "index": index, "rate": rate} + ), + flush=True, + ) + + if world_size > 1: + dist.barrier() + if rank == 0: + metadata_rows = [] + for index, row in enumerate(rows): + episode_sha = str(row["episode_sha256"]) + path = output / "episodes" / episode_sha[:2] / f"{episode_sha}.json" + if not path.is_file(): + raise RuntimeError(f"missing exact-cold row after distributed build: {episode_sha}") + value = json.loads(path.read_text(encoding="utf-8")) + if int(value["source_index"]) != index: + raise RuntimeError("exact-cold source order mismatch") + metadata_rows.append(value) + manifest_path = output / "manifest.jsonl" + temporary = manifest_path.with_name(f".{manifest_path.name}.tmp") + with temporary.open("w", encoding="utf-8") as handle: + for value in metadata_rows: + handle.write(json.dumps(value, sort_keys=True, separators=(",", ":")) + "\n") + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, manifest_path) + identity = { + "format_version": 1, + "contract": "deployment_exact_repeat20_initial_rgb_and_state_to_world97314_ema", + "label": "recorded_expert_next20_absolute_qpos", + "split": args.split, + "rows": len(metadata_rows), + "source_manifest": str(manifest), + "source_manifest_sha256": sha256_file(manifest), + "action_initialization_checkpoint": str(runtime.action_checkpoint), + "action_initialization_fingerprint": runtime.provenance.action_checkpoint_fingerprint, + "world_checkpoint": runtime.provenance.world_checkpoint, + "world_checkpoint_fingerprint": runtime.provenance.world_checkpoint_fingerprint, + "codec_sha256": runtime.provenance.codec_sha256, + "manifest_sha256": sha256_file(manifest_path), + "moving_first8_rows": sum(v["expert_first8_max_delta"] >= 0.01 for v in metadata_rows), + } + identity["identity_sha256"] = canonical_sha256(identity) + write_json_atomic(output / "COMPLETE.json", identity) + print(json.dumps(identity, indent=2), flush=True) + if world_size > 1: + dist.barrier() + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/build_predicted_future_cache.py b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/build_predicted_future_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..8434b727c570518757ac909ed30db6b558962ae6 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/build_predicted_future_cache.py @@ -0,0 +1,645 @@ +"""Generate deterministic 20%-train/all-validation World-EMA future conditions.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from collections import defaultdict +from pathlib import Path +from typing import Any + +import torch +import torch.distributed as dist +from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import CheckpointImpl, checkpoint_wrapper +from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard + +from mira.data.robotwin_wam_schema import read_jsonl +from mira.data.action_v6 import ( + PREDICTED_FUTURE_LOCATOR_SHIFT, + encode_predicted_future_locator, +) +from mira.data.world_v6 import ( + WorldV6BalancedSampler, + collate_world_v6, + set_world_v6_process_name, + window_id, +) +from mira.training.distributed import set_up_distributed +from mira.training.ema import ModelEMA +from mira.training.world_v6.checkpoint import load_checkpoint +from mira.training.world_v6.config import load_config as load_world_config +from mira.training.world_v6.train import ( + _artifact_identity, + _canonical_parameter_name, + _configure_trainable, + _dataset, + _load_resampler_selection, + _optimizer, + _scheduler, +) +from mira.world_v6.migration import load_migrated_system + +from .artifacts import canonical_sha256, sha256_file, write_json_atomic +from .config import ActionV6RunConfig, load_config + +WRITER_PARTITIONS = 8 +DIAGNOSTIC_WINDOWS_PER_STRATUM = 8 +FUTURE_SHAPE = (3, 10, 32, 9, 12) +FUTURE_ELEMENTS = 3 * 10 * 32 * 9 * 12 +ROW_BYTES = FUTURE_ELEMENTS * 2 + + +def _barrier() -> None: + if dist.is_initialized(): + dist.barrier() + + +def _selection_hash(identifier: str, world_sha: str, namespace: str) -> str: + return hashlib.sha256(f"{identifier}{world_sha}{namespace}".encode()).hexdigest() + + +def _world_seed(identifier: str, world_sha: str, namespace: str) -> int: + digest = hashlib.sha256(f"{identifier}\0{world_sha}\0{namespace}".encode()).digest() + return int.from_bytes(digest[:8], "big") % (2**63 - 1) + + +def _cache_shard(identifier: str, world_sha: str, split: str) -> int: + digest = hashlib.sha256(f"{identifier}\0{world_sha}\0{split}\0shard".encode()).digest() + return int.from_bytes(digest[:8], "big") % WRITER_PARTITIONS + + +def _diagnostic_keep_count(available: int) -> int: + """Use all valid windows when a held-out stratum has fewer than eight.""" + if available < 0: + raise ValueError("available diagnostic windows cannot be negative") + return min(DIAGNOSTIC_WINDOWS_PER_STRATUM, available) + + +def _train_keep_count(available: int, fraction: float) -> int: + """Formal per-episode selection rule, including the one-window floor.""" + if available <= 0: + raise ValueError("train episodes must contain at least one valid window") + if not 0.0 < fraction <= 1.0: + raise ValueError("predicted-future train fraction must be in (0, 1]") + return max(1, round(fraction * available)) + + +def _chunk_shard_id(partition: int, chunk_index: int, partitions: int = WRITER_PARTITIONS) -> int: + shard = chunk_index * partitions + partition + if not 0 <= shard < 256: + raise RuntimeError("predicted-future cache exceeds the uint8 locator shard namespace") + return shard + + +def _shard_stem(shard: int) -> str: + return f"shard-{shard:03d}" + + +def _completed_shard_metadata( + root: Path, + shard: int, + expected_rows: list[dict[str, Any]], +) -> dict[str, Any] | None: + stem = _shard_stem(shard) + metadata_path = root / f"{stem}.json" + tensor_path = root / f"{stem}.bf16" + index_path = root / f"{stem}.index.jsonl" + if not (metadata_path.is_file() and tensor_path.is_file() and index_path.is_file()): + return None + try: + metadata = json.loads(metadata_path.read_text(encoding="utf-8")) + except (json.JSONDecodeError, OSError): + return None + expected_selection = canonical_sha256(expected_rows) + identity_payload = {key: value for key, value in metadata.items() if key != "identity_sha256"} + valid = ( + int(metadata.get("format_version", 0)) == 2 + and int(metadata.get("shard", -1)) == shard + and int(metadata.get("rows", -1)) == len(expected_rows) + and int(metadata.get("bytes", -1)) == len(expected_rows) * ROW_BYTES + and metadata.get("selection_rows_sha256") == expected_selection + and metadata.get("tensor_file") == tensor_path.name + and metadata.get("index_file") == index_path.name + and metadata.get("metadata_file") == metadata_path.name + and tensor_path.stat().st_size == len(expected_rows) * ROW_BYTES + and sha256_file(tensor_path) == metadata.get("tensor_sha256") + and sha256_file(index_path) == metadata.get("index_sha256") + and canonical_sha256(identity_payload) == metadata.get("identity_sha256") + ) + return metadata if valid else None + + +def _build_selection(config: ActionV6RunConfig, split: str, output_split: str) -> dict[str, Any]: + source_manifest = ( + config.artifacts.train_source_manifest if split == "train" else config.artifacts.val_source_manifest + ) + rows = read_jsonl(source_manifest) + by_shard: dict[int, list[dict[str, Any]]] = defaultdict(list) + task_domain_total: dict[str, int] = defaultdict(int) + task_domain_selected: dict[str, int] = defaultdict(int) + cumulative = 0 + selected_episodes: set[str] = set() + diagnostic_candidates: dict[str, list[tuple[str, int, int, dict[str, Any]]]] = defaultdict(list) + for episode_index, row in enumerate(rows): + count = int(row["n_latents"]) - 19 + candidates = [] + for latent_start in range(count): + identifier = window_id(str(row["episode_sha256"]), latent_start) + score = _selection_hash(identifier, config.artifacts.world_checkpoint_sha256, config.predicted_future_cache.seed_namespace) + candidates.append((score, latent_start, identifier)) + key = f"{row['task']}/{row['domain']}" + task_domain_total[key] += count + if output_split == "train": + keep = _train_keep_count( + count, config.predicted_future_cache.train_fraction_per_episode + ) + chosen = sorted(candidates)[:keep] + elif output_split == "val": + chosen = candidates + elif output_split == "val_sample1": + for score, latent_start, identifier in candidates: + diagnostic_candidates[key].append((score, episode_index, latent_start, row)) + chosen = [] + else: + raise ValueError(output_split) + for _score, latent_start, identifier in chosen: + dataset_index = cumulative + latent_start + shard = _cache_shard(identifier, config.artifacts.world_checkpoint_sha256, output_split) + by_shard[shard].append( + { + "dataset_index": dataset_index, + "window_id": identifier, + "episode_sha256": row["episode_sha256"], + "task": row["task"], + "domain": row["domain"], + "latent_start": latent_start, + "world_seed": _world_seed( + identifier, + config.artifacts.world_checkpoint_sha256, + "sample-0" if split == "train" else "val-sample-0", + ), + } + ) + task_domain_selected[key] += 1 + selected_episodes.add(str(row["episode_sha256"])) + cumulative += count + if output_split == "val_sample1": + for key, candidates in sorted(diagnostic_candidates.items()): + keep = _diagnostic_keep_count(len(candidates)) + for _score, episode_index, latent_start, row in sorted(candidates)[:keep]: + identifier = window_id(str(row["episode_sha256"]), latent_start) + dataset_index = sum(int(value["n_latents"]) - 19 for value in rows[:episode_index]) + latent_start + shard = _cache_shard(identifier, config.artifacts.world_checkpoint_sha256, output_split) + by_shard[shard].append( + { + "dataset_index": dataset_index, + "window_id": identifier, + "episode_sha256": row["episode_sha256"], + "task": row["task"], + "domain": row["domain"], + "latent_start": latent_start, + "world_seed": _world_seed( + identifier, config.artifacts.world_checkpoint_sha256, "val-sample-1" + ), + } + ) + task_domain_selected[key] += 1 + selected_episodes.add(str(row["episode_sha256"])) + + output_root = Path(config.predicted_future_cache.root) / output_split + output_root.mkdir(parents=True, exist_ok=True) + shard_counts = {} + for shard in range(WRITER_PARTITIONS): + values = sorted(by_shard[shard], key=lambda row: int(row["dataset_index"])) + for row_index, row in enumerate(values): + row["partition"] = shard + row["partition_row"] = row_index + selection_path = output_root / f"selection-{shard:02d}.jsonl" + temporary = selection_path.with_name(f".{selection_path.name}.tmp") + with temporary.open("w", encoding="utf-8") as handle: + for row in values: + handle.write(json.dumps(row, sort_keys=True, separators=(",", ":")) + "\n") + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, selection_path) + shard_counts[str(shard)] = len(values) + report = { + "format_version": 1, + "split": output_split, + "source_split": split, + "source_manifest": source_manifest, + "source_manifest_sha256": sha256_file(source_manifest), + "window_manifest_sha256": ( + config.artifacts.train_window_manifest_sha256 + if split == "train" + else config.artifacts.validation_window_manifest_sha256 + ), + "manifest_windows": cumulative, + "source_episodes": len(rows), + "selected_episodes": len(selected_episodes), + "selected_windows": sum(shard_counts.values()), + "writer_partitions": shard_counts, + "task_domain_total": dict(sorted(task_domain_total.items())), + "task_domain_selected": dict(sorted(task_domain_selected.items())), + } + if output_split == "val_sample1": + short_strata = { + key: { + "available_windows": total, + "selected_windows": _diagnostic_keep_count(total), + } + for key, total in sorted(task_domain_total.items()) + if total < DIAGNOSTIC_WINDOWS_PER_STRATUM + } + report["diagnostic_selection"] = { + "requested_windows_per_stratum": DIAGNOSTIC_WINDOWS_PER_STRATUM, + "selection_rule": "min(requested_windows_per_stratum, available_valid_windows)", + "expected_windows": sum( + _diagnostic_keep_count(total) for total in task_domain_total.values() + ), + "short_strata": short_strata, + } + report["identity_sha256"] = canonical_sha256(report) + write_json_atomic(output_root / "selection.json", report) + return report + + +def _load_selection(path: Path) -> list[dict[str, Any]]: + values = [] + with path.open(encoding="utf-8") as handle: + for line in handle: + if line.strip(): + values.append(json.loads(line)) + return values + + +def _local_parameter_sha(model: torch.nn.Module) -> str: + digest = hashlib.sha256() + for name, value in sorted(model.state_dict().items()): + if not isinstance(value, torch.Tensor): + continue + local = value.to_local() if hasattr(value, "to_local") else value + digest.update(name.encode()) + digest.update(local.detach().cpu().contiguous().view(torch.uint8).numpy().tobytes()) + return digest.hexdigest() + + +def _make_world(config: ActionV6RunConfig, device: torch.device, rank: int, world_size: int): + if sha256_file(config.artifacts.anchor_identity) != config.artifacts.anchor_identity_sha256: + raise RuntimeError("anchor identity SHA changed before Action cache generation") + world = load_world_config(config.artifacts.world_config) + if canonical_sha256(world.model_dump(mode="json")) != config.artifacts.world_config_sha256: + raise RuntimeError("World resolved-config identity changed before Action cache generation") + selection = json.loads(Path(world.artifacts.resampler_selection).read_text()) + system = load_migrated_system(selection["system_weights"], world.model) + _load_resampler_selection(system, world.artifacts.resampler_selection) + _configure_trainable(system, "main") + system = system.to(device) + policy = MixedPrecisionPolicy( + param_dtype=torch.bfloat16, reduce_dtype=torch.float32, output_dtype=torch.bfloat16 + ) + if world.model.activation_checkpointing: + system.world_model.external_activation_checkpointing = True + for index, block in enumerate(system.world_model.blocks): + system.world_model.blocks[index] = checkpoint_wrapper( + block, checkpoint_impl=CheckpointImpl.NO_REENTRANT, preserve_rng_state=True + ) + for block in system.world_model.blocks: + fully_shard(block, mp_policy=policy, reshard_after_forward=True) + fully_shard(system, mp_policy=policy, reshard_after_forward=True) + names = {id(parameter): _canonical_parameter_name(name) for name, parameter in system.named_parameters()} + optimizer, _ = _optimizer(system, world, names) + scheduler = _scheduler(optimizer, world) + ema = ModelEMA(system, decay=world.optimizer.ema_decay, unbias=False) + # A sampler is needed only because strict World recovery includes its state. + validation_dataset = _dataset(world, "val") + sampler = WorldV6BalancedSampler( + validation_dataset, seed=world.experiment.seed, rank=rank, world_size=world_size + ) + step = load_checkpoint( + config.artifacts.world_checkpoint, + model=system, + optimizer=optimizer, + scheduler=scheduler, + ema=ema, + sampler=sampler, + expected_artifact_identity=_artifact_identity(world), + ) + if step != 97314: + raise RuntimeError(f"Action cache expected World step 97314, got {step}") + system.eval() + return world, system, ema + + +def _generate_split( + config: ActionV6RunConfig, + world_config, + system, + split: str, + output_split: str, + rank: int, + world_size: int, + device: torch.device, +) -> dict[str, Any] | None: + dataset = _dataset(world_config, split) + root = Path(config.predicted_future_cache.root) / output_split + selection_path = root / f"selection-{rank:02d}.jsonl" + rows = _load_selection(selection_path) + shard_rows = config.predicted_future_cache.shard_rows + local_chunks = (len(rows) + shard_rows - 1) // shard_rows + counts = [torch.zeros(1, dtype=torch.int64, device=device) for _ in range(world_size)] + dist.all_gather(counts, torch.tensor([local_chunks], dtype=torch.int64, device=device)) + total_chunks = max(int(value.item()) for value in counts) + if not rows and total_chunks: + raise RuntimeError("cache sharding unexpectedly assigned an empty rank") + + for chunk_index in range(total_chunks): + chunk_start = chunk_index * shard_rows + chunk_rows = rows[chunk_start : chunk_start + shard_rows] + shard = _chunk_shard_id(rank, chunk_index, world_size) + existing = _completed_shard_metadata(root, shard, chunk_rows) if chunk_rows else None + complete = torch.tensor([int(existing is not None or not chunk_rows)], device=device) + complete_flags = [torch.zeros_like(complete) for _ in range(world_size)] + dist.all_gather(complete_flags, complete) + if all(int(value.item()) == 1 for value in complete_flags): + if rank == 0: + print( + json.dumps( + { + "split": output_split, + "chunk": chunk_index, + "chunks": total_chunks, + "resume_skip": True, + } + ), + flush=True, + ) + continue + + active_write = bool(chunk_rows) and existing is None + stem = _shard_stem(shard) + tensor_partial = root / f".{stem}.bf16.partial" + index_partial = root / f".{stem}.index.jsonl.partial" + mapped = None + handle = None + if active_write: + with tensor_partial.open("wb") as tensor_handle: + tensor_handle.truncate(len(chunk_rows) * ROW_BYTES) + mapped = torch.from_file( + str(tensor_partial), + shared=True, + size=len(chunk_rows) * FUTURE_ELEMENTS, + dtype=torch.bfloat16, + ).reshape(len(chunk_rows), *FUTURE_SHAPE) + handle = index_partial.open("w", encoding="utf-8") + + local_batches = ( + len(chunk_rows) + config.training.micro_batch_per_gpu - 1 + ) // config.training.micro_batch_per_gpu + batch_counts = [torch.zeros(1, dtype=torch.int64, device=device) for _ in range(world_size)] + dist.all_gather( + batch_counts, torch.tensor([local_batches], dtype=torch.int64, device=device) + ) + total_batches = max(int(value.item()) for value in batch_counts) + try: + for batch_index in range(total_batches): + start = batch_index * config.training.micro_batch_per_gpu + valid = max(0, min(config.training.micro_batch_per_gpu, len(chunk_rows) - start)) + chosen = list(chunk_rows[start : start + valid]) + padding_pool = chunk_rows or rows + while len(chosen) < config.training.micro_batch_per_gpu: + chosen.append(padding_pool[(start + len(chosen)) % len(padding_pool)]) + samples = [dataset[int(row["dataset_index"])] for row in chosen] + batch, _metadata_rows = collate_world_v6(samples) + batch = batch.to(device) + assert batch.anchors is not None + noises = [] + for row in chosen: + generator = torch.Generator(device=device).manual_seed(int(row["world_seed"])) + noises.append(torch.randn(FUTURE_SHAPE, generator=generator, device=device)) + noise = torch.stack(noises) + with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16): + raw = system( + z_context_raw=batch.z_context_raw, + z_future_raw=batch.z_future_raw, + anchors=batch.anchors, + state_history=batch.state_history, + history_valid=batch.history_valid, + future_valid=batch.future_valid, + view_valid=batch.view_valid, + sample_steps=10, + sample_noise=noise, + )["sample_future_raw"] + predicted = ( + (raw.float() - config.world_inference.latent_mean) + / config.world_inference.latent_std + ).to(torch.bfloat16).cpu() + if predicted.shape != (config.training.micro_batch_per_gpu, *FUTURE_SHAPE): + raise RuntimeError("World cache output shape mismatch") + if not torch.isfinite(predicted).all(): + raise FloatingPointError("World cache produced non-finite future") + if active_write and valid: + assert mapped is not None and handle is not None + mapped[start : start + valid].copy_(predicted[:valid]) + for offset, row in enumerate(chunk_rows[start : start + valid]): + tensor_bytes = predicted[offset].contiguous().view(torch.uint8).numpy().tobytes() + value = dict(row) + value.update( + { + "split": output_split, + "shard": shard, + "row": start + offset, + "world_sha256": config.artifacts.world_checkpoint_sha256, + "solver": "linear_quadratic_euler", + "steps": 10, + "tensor_key": "z_future_pred_norm", + "shape": list(FUTURE_SHAPE), + "dtype": "bfloat16", + "tensor_sha256": hashlib.sha256(tensor_bytes).hexdigest(), + } + ) + handle.write( + json.dumps(value, sort_keys=True, separators=(",", ":")) + "\n" + ) + if batch_index % 20 == 0: + print( + json.dumps( + { + "split": output_split, + "rank": rank, + "chunk": chunk_index, + "chunks": total_chunks, + "batch": batch_index, + "batches": total_batches, + "rows": min(chunk_start + start + valid, len(rows)), + "total_rows": len(rows), + "write": active_write, + } + ), + flush=True, + ) + finally: + if handle is not None: + handle.flush() + os.fsync(handle.fileno()) + handle.close() + if mapped is not None: + del mapped + _barrier() + if active_write: + final_tensor = root / f"{stem}.bf16" + final_index = root / f"{stem}.index.jsonl" + metadata_path = root / f"{stem}.json" + os.replace(tensor_partial, final_tensor) + os.replace(index_partial, final_index) + metadata = { + "format_version": 2, + "split": output_split, + "shard": shard, + "partition": rank, + "chunk": chunk_index, + "rows": len(chunk_rows), + "bytes": final_tensor.stat().st_size, + "tensor_file": final_tensor.name, + "index_file": final_index.name, + "metadata_file": metadata_path.name, + "tensor_sha256": sha256_file(final_tensor), + "index_sha256": sha256_file(final_index), + "selection_rows_sha256": canonical_sha256(chunk_rows), + } + metadata["identity_sha256"] = canonical_sha256(metadata) + write_json_atomic(metadata_path, metadata) + _barrier() + return None + + +def _finalize_split(config: ActionV6RunConfig, split: str, source_split: str) -> dict[str, Any]: + root = Path(config.predicted_future_cache.root) / split + selection = json.loads((root / "selection.json").read_text()) + locators = torch.full((int(selection["manifest_windows"]),), -1, dtype=torch.int64) + shards = {} + shard_rows = config.predicted_future_cache.shard_rows + for partition in range(WRITER_PARTITIONS): + rows = _load_selection(root / f"selection-{partition:02d}.jsonl") + if len(rows) != int(selection["writer_partitions"][str(partition)]): + raise RuntimeError("cache writer-partition row count differs from selection") + for chunk_index, start in enumerate(range(0, len(rows), shard_rows)): + chunk_rows = rows[start : start + shard_rows] + shard = _chunk_shard_id(partition, chunk_index) + metadata = _completed_shard_metadata(root, shard, chunk_rows) + if metadata is None: + raise RuntimeError(f"cache shard {shard} is missing or incomplete") + shards[str(shard)] = metadata + for row_index, row in enumerate(chunk_rows): + dataset_index = int(row["dataset_index"]) + if int(locators[dataset_index]) >= 0: + raise RuntimeError("duplicate predicted-future cache locator") + locators[dataset_index] = encode_predicted_future_locator(shard, row_index) + if int((locators >= 0).sum()) != int(selection["selected_windows"]): + raise RuntimeError("cache locator selected count mismatch") + locator_partial = root / ".locators.i64.partial" + locators.numpy().tofile(locator_partial) + with locator_partial.open("rb") as handle: + os.fsync(handle.fileno()) + os.replace(locator_partial, root / "locators.i64") + complete = { + "format_version": 1, + "split": split, + "source_split": source_split, + "manifest_windows": int(selection["manifest_windows"]), + "selected_windows": int(selection["selected_windows"]), + "window_manifest_sha256": selection["window_manifest_sha256"], + "locators_sha256": sha256_file(root / "locators.i64"), + "selection_sha256": sha256_file(root / "selection.json"), + "shard_rows": shard_rows, + "writer_partitions": WRITER_PARTITIONS, + "locator_encoding": { + "dtype": "int64", + "missing": -1, + "shard_bits": 8, + "shard_shift": PREDICTED_FUTURE_LOCATOR_SHIFT, + "row_bits": PREDICTED_FUTURE_LOCATOR_SHIFT, + }, + "shards": shards, + } + complete["identity_sha256"] = canonical_sha256(complete) + write_json_atomic(root / "COMPLETE.json", complete) + return complete + + +def build_cache(config_path: str) -> None: + config = load_config(config_path) + settings = set_up_distributed() + rank, world_size = settings.rank, settings.world_size + if world_size != config.training.expected_world_size: + raise RuntimeError("formal predicted-future cache requires eight ranks") + set_world_v6_process_name(f"syncnet_v6_acache{rank}") + device = torch.device("cuda", settings.device) + root = Path(config.predicted_future_cache.root) + anchor_hash_before = sha256_file(config.artifacts.anchor_identity) + if rank == 0: + root.mkdir(parents=True, exist_ok=True) + _build_selection(config, "train", "train") + _build_selection(config, "val", "val") + _build_selection(config, "val", "val_sample1") + _barrier() + world_config, system, ema = _make_world(config, device, rank, world_size) + with ema.average_parameters(): + frozen_before = _local_parameter_sha(system) + for split, output_split in (("train", "train"), ("val", "val"), ("val", "val_sample1")): + _generate_split( + config, world_config, system, split, output_split, rank, world_size, device + ) + frozen_after = _local_parameter_sha(system) + if frozen_before != frozen_after: + raise RuntimeError("frozen World/State parameters changed during cache generation") + if sha256_file(config.artifacts.anchor_identity) != anchor_hash_before: + raise RuntimeError("anchor identity changed during cache generation") + gathered: list[str | None] = [None] * world_size + dist.all_gather_object(gathered, frozen_after) + if rank == 0: + split_identities = { + "train": _finalize_split(config, "train", "train"), + "val": _finalize_split(config, "val", "val"), + "val_sample1": _finalize_split(config, "val_sample1", "val"), + } + identity = { + "format_version": 1, + "world_checkpoint": config.artifacts.world_checkpoint, + "world_checkpoint_sha256": config.artifacts.world_checkpoint_sha256, + "world_branch": "ema", + "world_selection_report_sha256": sha256_file(config.artifacts.world_selection_report), + "world_config_sha256": config.artifacts.world_config_sha256, + "anchor_identity_sha256": anchor_hash_before, + "codec_sha256": config.artifacts.codec_sha256, + "solver": "linear_quadratic_euler", + "steps": 10, + "dtype": "bfloat16", + "shape": list(FUTURE_SHAPE), + "latent_normalization_sha256": canonical_sha256( + {"mean": config.world_inference.latent_mean, "std": config.world_inference.latent_std} + ), + "code_identity": config.experiment.code_identity, + "seed_namespace": config.predicted_future_cache.seed_namespace, + "train_window_manifest_sha256": config.artifacts.train_window_manifest_sha256, + "validation_window_manifest_sha256": config.artifacts.validation_window_manifest_sha256, + "frozen_rank_hashes": gathered, + "splits": split_identities, + } + identity["identity_sha256"] = canonical_sha256(identity) + write_json_atomic(config.predicted_future_cache.identity_file, identity) + print(json.dumps(identity, indent=2), flush=True) + _barrier() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", required=True) + args = parser.parse_args() + build_cache(args.config) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/build_statistics.py b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/build_statistics.py new file mode 100644 index 0000000000000000000000000000000000000000..d300480523fc7dfef82d5158b6123ee68b5fb89b --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/build_statistics.py @@ -0,0 +1,229 @@ +"""Compute train-only 14D action and [3,10,32] latent-delta statistics.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch +from safetensors.torch import load_file + +from mira.data.robotwin_wam_schema import read_jsonl + +from .artifacts import canonical_sha256, sha256_file, write_json_atomic +from .config import load_config + + +def _physical_limits(path: str | Path) -> tuple[list[float], list[float], dict[str, str]]: + """Read the six arm limits and gripper base limit from the pinned ALOHA URDF.""" + import xml.etree.ElementTree as ET + + root = Path(path).expanduser().resolve() + config_path = root / "config.yml" + config = __import__("yaml").safe_load(config_path.read_text(encoding="utf-8")) + # The embodiment file contains separate left/right entries whose ordered arm names are authoritative. + entries = config if isinstance(config, list) else config.get("embodiment", config) + if isinstance(entries, dict) and "left" in entries: + left_config, right_config = entries["left"], entries["right"] + arm_entries = [left_config["arm_joints_name"], right_config["arm_joints_name"]] + gripper_entries = [left_config["gripper_name"], right_config["gripper_name"]] + elif isinstance(entries, dict): + left_config = right_config = entries + arm_entries = entries["arm_joints_name"] + gripper_entries = entries["gripper_name"] + elif isinstance(entries, list) and len(entries) >= 2: + left_config, right_config = entries[0], entries[1] + arm_entries = [left_config["arm_joints_name"], right_config["arm_joints_name"]] + gripper_entries = [left_config["gripper_name"], right_config["gripper_name"]] + else: + raise RuntimeError("cannot resolve pinned ALOHA left/right embodiment entries") + urdf_rel = left_config.get("urdf_path") or right_config.get("urdf_path") + if not urdf_rel: + raise RuntimeError("ALOHA embodiment config has no URDF path") + urdf_path = root / urdf_rel + urdf = ET.parse(urdf_path).getroot() + limits = {} + for joint in urdf.findall("joint"): + limit = joint.find("limit") + if limit is not None and "lower" in limit.attrib and "upper" in limit.attrib: + limits[joint.attrib["name"]] = (float(limit.attrib["lower"]), float(limit.attrib["upper"])) + + arm_left, arm_right = list(arm_entries[0]), list(arm_entries[1]) + if len(arm_left) != 6 or len(arm_right) != 6: + raise RuntimeError("ALOHA action contract requires six joints per arm") + gripper_left, gripper_right = gripper_entries[0], gripper_entries[1] + grip_left_name = gripper_left["base"] + grip_right_name = gripper_right["base"] + ordered_arm = arm_left + arm_right + ordered_urdf = arm_left + [grip_left_name] + arm_right + [grip_right_name] + if any(name not in limits for name in ordered_urdf): + raise RuntimeError(f"URDF is missing action joint limits: {[n for n in ordered_urdf if n not in limits]}") + # RoboTwin's qpos policy API deliberately exposes grippers as normalized + # [0,1] commands. Robot.set_gripper maps those values through gripper_scale + # before touching the prismatic URDF drive target. The six arm channels are + # direct radians and therefore use the URDF limits unchanged. + lower = [limits[name][0] for name in arm_left] + [0.0] + lower += [limits[name][0] for name in arm_right] + [0.0] + upper = [limits[name][1] for name in arm_left] + [1.0] + upper += [limits[name][1] for name in arm_right] + [1.0] + return lower, upper, { + "config": str(config_path), + "config_sha256": sha256_file(config_path), + "urdf": str(urdf_path), + "urdf_sha256": sha256_file(urdf_path), + "arm_joint_names": ordered_arm, + "gripper_joint_names": [grip_left_name, grip_right_name], + "gripper_policy_limits": [0.0, 1.0], + "gripper_real_scale": list(entries["gripper_scale"]) if isinstance(entries, dict) else None, + "gripper_mapping": "policy_[0,1]_mapped_by_Robot.set_gripper_to_prismatic_drive_target", + } + + +def build_statistics(config_path: str) -> None: + config = load_config(config_path) + rows = read_jsonl(config.artifacts.train_source_manifest) + if len(rows) != 26_950 or any(row["split"] != "train" for row in rows): + raise RuntimeError("Action statistics require the immutable 26,950-episode train split") + val_episodes = { + row["episode_sha256"] for row in read_jsonl(config.artifacts.val_source_manifest) + } + train_episodes = {row["episode_sha256"] for row in rows} + if train_episodes & val_episodes: + raise RuntimeError("train/validation episodes overlap") + + # The first Action target for latent window k=0 is u20[19], while the + # final window k=N-20 ends at u20[2N-2]. Statistics therefore use the + # de-duplicated union of values that can actually be supervised targets, + # not the episode-prefix drive targets that are history only. + total_actions = sum(2 * int(row["n_latents"]) - 20 for row in rows) + all_actions = torch.empty((total_actions, 14), dtype=torch.float32) + cursor = 0 + delta_square = torch.zeros((3, 10, 32), dtype=torch.float64) + delta_count = torch.zeros((3, 10, 32), dtype=torch.int64) + source_windows = 0 + for row_index, row in enumerate(rows): + episode = load_file(row["cache_path"], device="cpu") + action = episode["action20_f32"].float() + expected_actions = int(row["n_video20_frames"]) - 1 + if action.shape != (expected_actions, 14) or not torch.isfinite(action).all(): + raise RuntimeError(f"invalid action tensor in train row {row_index}") + target_end = 2 * int(row["n_latents"]) - 1 + valid_targets = action[19:target_end] + expected_targets = 2 * int(row["n_latents"]) - 20 + if valid_targets.shape != (expected_targets, 14): + raise RuntimeError(f"invalid Action-target union in train row {row_index}") + all_actions[cursor : cursor + expected_targets].copy_(valid_targets) + cursor += expected_targets + latent = episode["world_latent_raw_bf16"].float() + windows = int(row["n_latents"]) - 19 + if latent.shape != (3, int(row["n_latents"]), 32, 9, 12) or windows <= 0: + raise RuntimeError(f"invalid latent tensor in train row {row_index}") + difference = latent[:, 1:] - latent[:, :-1] + for horizon in range(10): + value = difference[:, 9 + horizon : 9 + horizon + windows] + delta_square[:, horizon] += value.double().square().sum(dim=(1, 3, 4)) + delta_count[:, horizon] += value.shape[1] * 9 * 12 + source_windows += windows + if row_index and row_index % 1000 == 0: + print(json.dumps({"episodes": row_index, "actions": cursor, "windows": source_windows}), flush=True) + if cursor != total_actions: + raise RuntimeError("action statistics streaming count mismatch") + mean = all_actions.double().mean(dim=0) + std = all_actions.double().std(dim=0, unbiased=False).clamp_min(1.0e-4) + quantiles = torch.quantile(all_actions, torch.tensor([0.001, 0.5, 0.999]), dim=0) + median = quantiles[1] + mad = (all_actions - median).abs().median(dim=0).values + embodiment_root = Path(config.experiment.artifact_root).parent / "benchmark" / "aloha-agilex" + if not embodiment_root.is_dir(): + # Pinned upstream assets live outside generated Action artifacts. + embodiment_root = Path(config.experiment.artifact_root).parents[1] / "vendor" / "RoboTwin" / "assets" / "embodiments" / "aloha-agilex" + lower, upper, physical_identity = _physical_limits(embodiment_root) + low = torch.tensor(lower, dtype=torch.float32) + high = torch.tensor(upper, dtype=torch.float32) + physical_violations = ((all_actions < low) | (all_actions > high)).sum(dim=0) + robust_violations = ( + (all_actions - median).abs() > (20.0 * mad).clamp_min(1.0e-6) + ).sum(dim=0) + action_stats = { + "format_version": 1, + "split": "train_only", + "source_manifest": config.artifacts.train_source_manifest, + "source_manifest_sha256": sha256_file(config.artifacts.train_source_manifest), + "validation_manifest_sha256": sha256_file(config.artifacts.val_source_manifest), + "episode_count": len(rows), + "validation_episode_count": len(val_episodes), + "episode_overlap": 0, + "sample_count": total_actions, + "dimension_order": [ + "left_joint_0", "left_joint_1", "left_joint_2", "left_joint_3", "left_joint_4", "left_joint_5", "left_gripper", + "right_joint_0", "right_joint_1", "right_joint_2", "right_joint_3", "right_joint_4", "right_joint_5", "right_gripper", + ], + "mean": mean.tolist(), + "std": std.tolist(), + "std_floor": 1.0e-4, + "q001": quantiles[0].double().tolist(), + "median": median.double().tolist(), + "q999": quantiles[2].double().tolist(), + "mad": mad.double().tolist(), + "physical_min": lower, + "physical_max": upper, + "physical_limit_violations": physical_violations.tolist(), + "median_20mad_violations": robust_violations.tolist(), + "physical_identity": physical_identity, + "statistics_scope": "deduplicated_union_of_action20_targets_reachable_by_train_windows", + "per_episode_target_slice": "action20_f32[19:2*n_latents-1]", + } + action_stats["identity_sha256"] = canonical_sha256(action_stats) + # Action inputs are normalized LingBot latents, so the Pair Builder scale must + # live in that same space (the additive latent mean cancels in a delta). + delta_scale = ( + torch.sqrt(delta_square / delta_count.clamp_min(1)) / config.world_inference.latent_std + ).clamp_min(1.0e-4) + delta_stats = { + "format_version": 1, + "split": "train_only", + "source_manifest_sha256": sha256_file(config.artifacts.train_source_manifest), + "window_manifest_sha256": config.artifacts.train_window_manifest_sha256, + "windows": source_windows, + "view_order": ["left", "global", "right"], + "intervals": 10, + "channels": 32, + "rms": delta_scale.tolist(), + "count": delta_count.tolist(), + "floor": 1.0e-4, + "latent_mean": config.world_inference.latent_mean, + "latent_std": config.world_inference.latent_std, + "note": "Raw GT latent deltas are divided by the locked World latent_std; RMS and Pair Builder inputs are both in normalized latent space.", + } + delta_stats["identity_sha256"] = canonical_sha256(delta_stats) + write_json_atomic(config.data.action_stats, action_stats) + write_json_atomic(config.data.delta_stats, delta_stats) + report = { + "format_version": 1, + "passed": bool(physical_violations.sum() == 0), + "action_stats": config.data.action_stats, + "action_stats_sha256": sha256_file(config.data.action_stats), + "delta_stats": config.data.delta_stats, + "delta_stats_sha256": sha256_file(config.data.delta_stats), + "physical_limit_violations": int(physical_violations.sum()), + "robust_outliers": int(robust_violations.sum()), + "valid_action_target_samples": total_actions, + "action_statistics_scope": action_stats["statistics_scope"], + "train_windows": source_windows, + } + write_json_atomic(Path(config.experiment.artifact_root) / "reports" / "statistics.json", report) + print(json.dumps(report, indent=2), flush=True) + if not report["passed"]: + raise RuntimeError("train actions exceed pinned embodiment physical limits; audit required") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", required=True) + args = parser.parse_args() + build_statistics(args.config) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/checkpoint.py b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..f3d9d0e510699ca57d1f0e8a12afb2cea3db234b --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/checkpoint.py @@ -0,0 +1,148 @@ +"""Atomic FSDP2 Action-v6 recovery checkpoints.""" + +from __future__ import annotations + +import json +import os +import random +import shutil +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import torch.distributed as dist +import torch.distributed.checkpoint as dcp +from torch.distributed.checkpoint.state_dict import get_state_dict, set_state_dict + +from mira.training.ema import ModelEMA + +from .artifacts import canonical_sha256 + + +def _barrier() -> None: + if dist.is_initialized(): + dist.barrier() + + +def complete_checkpoints(root: str | Path) -> list[tuple[int, Path]]: + values = [] + for path in Path(root).glob("action-checkpoint-*"): + suffix = path.name.rsplit("-", 1)[-1] + if suffix.isdecimal() and (path / "trainer_state.json").is_file(): + values.append((int(suffix), path)) + return sorted(values) + + +def latest_checkpoint(root: str | Path) -> Path | None: + values = complete_checkpoints(root) + return values[-1][1] if values else None + + +def save_checkpoint( + root: str | Path, + *, + completed_steps: int, + model: torch.nn.Module, + optimizer: torch.optim.Optimizer, + scheduler: Any, + ema: ModelEMA, + sampler: Any, + resolved_config: dict[str, Any], + artifact_identity: dict[str, Any], + metrics: dict[str, Any], + keep_recent: int, +) -> Path: + rank = dist.get_rank() if dist.is_initialized() else 0 + root = Path(root) + final = root / f"action-checkpoint-{completed_steps}" + temporary = root / f".{final.name}.tmp" + if rank == 0: + root.mkdir(parents=True, exist_ok=True) + if temporary.exists(): + shutil.rmtree(temporary) + temporary.mkdir(parents=True) + _barrier() + model_state, optimizer_state = get_state_dict(model, optimizer) + dcp.save( + {"model": model_state, "optimizer": optimizer_state, "ema": ema.state_dict()}, + checkpoint_id=temporary / "distributed", + ) + torch.save( + { + "scheduler": scheduler.state_dict(), + "sampler": sampler.state_dict(), + "python_rng": random.getstate(), + "numpy_rng": np.random.get_state(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state() if torch.cuda.is_available() else None, + }, + temporary / f"rank-{rank:05d}.pth", + ) + _barrier() + if rank == 0: + state = { + "format_version": 1, + "architecture": artifact_identity.get("architecture", "bihub-wam-v6-action"), + "completed_steps": completed_steps, + "next_step": completed_steps, + "artifact_identity": artifact_identity, + "artifact_identity_sha256": canonical_sha256(artifact_identity), + "resolved_config": resolved_config, + "metrics": metrics, + } + (temporary / "trainer_state.json").write_text( + json.dumps(state, indent=2, default=str) + "\n", encoding="utf-8" + ) + if final.exists(): + shutil.rmtree(final) + os.replace(temporary, final) + preserved = {int(v) for v in resolved_config["checkpoint"]["preserve_steps"]} + best_path = root / "best_checkpoint.json" + if best_path.is_file(): + best = json.loads(best_path.read_text(encoding="utf-8")) + preserved.add(int(best["step"])) + removable = [(step, path) for step, path in complete_checkpoints(root) if step not in preserved] + for _, path in removable[:-keep_recent]: + shutil.rmtree(path) + _barrier() + return final + + +def load_checkpoint( + checkpoint: str | Path, + *, + model: torch.nn.Module, + optimizer: torch.optim.Optimizer, + scheduler: Any, + ema: ModelEMA, + sampler: Any, + expected_artifact_identity: dict[str, Any], +) -> int: + rank = dist.get_rank() if dist.is_initialized() else 0 + checkpoint = Path(checkpoint) + metadata = json.loads((checkpoint / "trainer_state.json").read_text()) + if metadata["artifact_identity_sha256"] != canonical_sha256(expected_artifact_identity): + raise ValueError("Action-v6 resume artifact identity changed") + model_state, optimizer_state = get_state_dict(model, optimizer) + state = {"model": model_state, "optimizer": optimizer_state, "ema": ema.state_dict()} + dcp.load(state, checkpoint_id=checkpoint / "distributed") + set_state_dict( + model, + optimizer, + model_state_dict=state["model"], + optim_state_dict=state["optimizer"], + ) + ema.load_state_dict(state["ema"]) + rank_state = torch.load( + checkpoint / f"rank-{rank:05d}.pth", map_location="cpu", weights_only=False + ) + scheduler.load_state_dict(rank_state["scheduler"]) + sampler.load_state_dict(rank_state["sampler"]) + random.setstate(rank_state["python_rng"]) + np.random.set_state(rank_state["numpy_rng"]) + torch.set_rng_state(rank_state["torch_rng"]) + if torch.cuda.is_available() and rank_state["cuda_rng"] is not None: + torch.cuda.set_rng_state(rank_state["cuda_rng"]) + _barrier() + return int(metadata["next_step"]) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/config.py b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/config.py new file mode 100644 index 0000000000000000000000000000000000000000..274bbe2256effc9fb893040bb5d9f1d9dde43337 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/config.py @@ -0,0 +1,661 @@ +"""Strict, immutable Action-v6 configuration schema.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Literal + +from omegaconf import OmegaConf +from pydantic import BaseModel, ConfigDict, model_validator + + +class StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class ExperimentConfig(StrictModel): + name: Literal[ + "robotwin_bihub_wam_v6_action", + "robotwin_bihub_wam_v7_action", + "robotwin_bihub_wam_v10_action", + "robotwin_bihub_wam_v11_action", + "robotwin_bihub_wam_v12_action", + "robotwin_bihub_wam_v13_action", + ] + version: Literal[ + "v6.0-action", + "v7.0-action-corrective", + "v10.0-action-h1-50", + "v11.0-action-h1-50-pred8k", + "v12.0-action-eval-aligned-epoch", + "v13.0-action-eval-aligned-continue4epoch", + ] + seed: Literal[2026] + output_root: str + artifact_root: str + code_identity: str + + +class ArtifactConfig(StrictModel): + codec_checkpoint: str + codec_sha256: str + anchor_identity: str + anchor_identity_sha256: str + world_checkpoint: str + world_checkpoint_sha256: str + world_branch: Literal["ema", "online"] + world_config: str + world_config_sha256: str + world_validation_report: str + world_validation_report_sha256: str + world_selection_report: str + state_encoder_ema: str + state_encoder_ema_sha256: str + state_stats: str + state_stats_sha256: str + train_source_manifest: str + val_source_manifest: str + train_window_manifest: str + train_window_manifest_sha256: str + validation_window_manifest: str + validation_window_manifest_sha256: str + train_window_index: str + validation_window_index: str + split_identity: str + qwen_hidden_cache_root: str | None = None + qwen_hidden_cache_identity: str | None = None + supplemental_case_manifest: str | None = None + + +class DataConfig(StrictModel): + tasks: Literal[50] + view_order: list[str] + arm_order: list[str] + latent_shape: list[int] + context_latents: Literal[10] + future_latents: Literal[10] + latent_fps: Literal[10] + state_steps: Literal[20] + action_steps: Literal[20] + action_fps: Literal[20] + state_source_field: Literal["joint_action/vector"] + state_semantics: Literal["simulator_drive_target_not_measured_qpos"] + action_semantics: Literal["next_simulator_drive_target_absolute_qpos"] + action_dim_per_arm: Literal[7] + task_uniform: Literal[True] + clean_probability: Literal[0.5] + num_workers: int + episode_cache_size: int + action_stats: str + action_stats_sha256: str + delta_stats: str + delta_stats_sha256: str + history_lengths: list[int] = [10] + history_probabilities: list[float] = [1.0] + h1_episode_start_only: bool = False + episode_start_only_histories: list[int] = [] + h10_all_legal_starts: bool = False + epoch_h10_windows: int = 0 + sampler_step_offset: int = 0 + + +class WorldInferenceConfig(StrictModel): + trainable: Literal[False] + sampler: Literal["linear_quadratic_euler"] + steps: Literal[10] + decoder_loaded: Literal[False] + latent_mean: float + latent_std: float + + +class PredictedFutureCacheConfig(StrictModel): + root: str + identity_file: str + identity_sha256: str + train_fraction_per_episode: float + samples_per_window: Literal[1] + dtype: Literal["bfloat16"] + shard_rows: int + seed_namespace: str + train_rows_per_stratum_history: int = 0 + val_rows_per_stratum_history: int = 0 + full_eval_aligned: bool = False + max_rows_per_history: int = 0 + + +class TransitionConfig(StrictModel): + width: Literal[1024] + queries_per_view_interval: Literal[4] + qformer_layers: Literal[2] + heads: Literal[16] + head_dim: Literal[64] + ffn_hidden: Literal[4096] + dropout: Literal[0.0] + qk_norm: Literal[True] + delta_normalization: Literal["train_gt_rms_per_view_horizon_channel"] + topology: Literal["sequential_global_gather_local_broadcast"] + residual_gate_init: Literal[0.1] + + +class ActionConfig(StrictModel): + horizon: Literal[20] + width: Literal[1024] + layers: Literal[8] + heads: Literal[16] + head_dim: Literal[64] + ffn_hidden: Literal[4096] + dropout: Literal[0.0] + qk_norm: Literal[True] + local_weights_shared: Literal[True] + global_registers: Literal[20] + direct_left_right_attention: Literal[False] + monotonic_sigma: Literal[0.1] + flow_time_distribution: Literal["logit_normal"] + flow_time_logit_mean: Literal[0.0] + flow_time_logit_std: Literal[1.0] + loss: Literal[ + "masked_action_flow_mse_only", + "masked_action_flow_mse_execute8_gripper_weighted", + ] + sampler: Literal["euler"] + sampling_steps: Literal[10] + cfg_scale: Literal[1.0] + execute_steps: Literal[8] + normalized_action_clip: Literal[5.0] + + +class CurriculumSegment(StrictModel): + start: int + end: int + start_p: float + end_p: float + + +class TrainingConfig(StrictModel): + protocol: Literal[ + "preregistered_100k", + "compressed_22k", + "continuation_100k", + "corrective_v7_round0", + "h1_50_gt10k_pred20k", + "h1_50_pred8k_world_v11", + "eval_aligned_epoch_world_v12", + "eval_aligned_continue4_world_v12", + ] + steps: int + global_batch: int + micro_batch_per_gpu: int + grad_accumulation: int + expected_world_size: Literal[8] + strategy: Literal["fsdp2_full_shard"] + optimizer: Literal["adamw"] + betas: list[float] + eps: Literal[1e-08] + peak_lr: float + min_lr: float + weight_decay: Literal[0.01] + warmup_steps: int + scheduler: Literal["cosine"] + grad_clip: Literal[1.0] + precision: Literal["bfloat16"] + flow_compute_dtype: Literal["float32"] + activation_checkpointing: Literal[True] + activation_checkpoint_blocks: int = 8 + ema_decay: float + log_every: Literal[20] + light_val_every: int + full_val_every: int + save_every: int + predicted_future_curriculum: list[CurriculumSegment] + continuation_resume_step: int | None = None + continuation_rewarm_steps: int = 0 + continuation_peak_lr: float | None = None + + +class CheckpointConfig(StrictModel): + keep_last_recovery: int + preserve_steps: list[int] + auto_resume: Literal[True] + resume_from: str | None + initialize_from_ema: str | None = None + initialize_from_online: str | None = None + atomic: Literal[True] + + +class ValidationConfig(StrictModel): + enabled: bool + fixed_seed: Literal[2026] + light_batches: int + full_batches: int + save_cases: int + quick_enabled: bool = False + quick_every: int = 5000 + quick_batches: int = 16 + quick_save_cases: int = 4 + + +class LoggingConfig(StrictModel): + swanlab_enabled: Literal[True] + swanlab_project: Literal["multi-wam"] + swanlab_experiment_name: str + swanlab_token_file: str + + +class RuntimeConfig(StrictModel): + phase: Literal["upstream", "statistics", "cache", "overfit64", "canary", "training", "eval"] + mode: Literal["formal", "gate"] + max_steps: int | None = None + + +class CorrectiveConfig(StrictModel): + exact_cold_train_manifest: str + exact_cold_val_manifest: str + critical_event_index: str + critical_event_identity: str + regular_expert_share: float + exact_cold_share: float + critical_event_share: float + regular_predicted_probability: float + + +class ActionV6RunConfig(StrictModel): + experiment: ExperimentConfig + artifacts: ArtifactConfig + data: DataConfig + world_inference: WorldInferenceConfig + predicted_future_cache: PredictedFutureCacheConfig + transition: TransitionConfig + action: ActionConfig + training: TrainingConfig + checkpoint: CheckpointConfig + validation: ValidationConfig + logging: LoggingConfig + runtime: RuntimeConfig + corrective: CorrectiveConfig | None = None + + @model_validator(mode="after") + def validate_locked_contract(self) -> "ActionV6RunConfig": + expected_experiment = ( + ( + "robotwin_bihub_wam_v13_action", + "v13.0-action-eval-aligned-continue4epoch", + ) + if self.training.protocol == "eval_aligned_continue4_world_v12" + else + ("robotwin_bihub_wam_v12_action", "v12.0-action-eval-aligned-epoch") + if self.training.protocol == "eval_aligned_epoch_world_v12" + else + ("robotwin_bihub_wam_v11_action", "v11.0-action-h1-50-pred8k") + if self.training.protocol == "h1_50_pred8k_world_v11" + else + ("robotwin_bihub_wam_v10_action", "v10.0-action-h1-50") + if self.training.protocol == "h1_50_gt10k_pred20k" + else + ("robotwin_bihub_wam_v7_action", "v7.0-action-corrective") + if self.training.protocol == "corrective_v7_round0" + else ("robotwin_bihub_wam_v6_action", "v6.0-action") + ) + if (self.experiment.name, self.experiment.version) != expected_experiment: + raise ValueError("experiment name/version do not match the selected Action protocol") + if self.data.view_order != ["left", "global", "right"]: + raise ValueError("view order must be [left,global,right]") + if self.data.arm_order != ["left", "right"]: + raise ValueError("arm order must be [left,right]") + if self.data.latent_shape != [32, 9, 12]: + raise ValueError("LingBot latent geometry must be [32,9,12]") + if self.training.betas != [0.9, 0.95]: + raise ValueError("formal AdamW betas are locked to [0.9,0.95]") + if ( + self.training.micro_batch_per_gpu + * self.training.grad_accumulation + * 8 + != self.training.global_batch + ): + raise ValueError("micro batch and accumulation do not match global_batch") + if ( + self.training.protocol not in { + "eval_aligned_epoch_world_v12", + "eval_aligned_continue4_world_v12", + } + and self.training.global_batch != 512 + ): + raise ValueError("legacy Action protocols require global batch 512") + if self.training.protocol not in { + "corrective_v7_round0", + "h1_50_gt10k_pred20k", + "h1_50_pred8k_world_v11", + "eval_aligned_epoch_world_v12", + "eval_aligned_continue4_world_v12", + } and ( + self.training.peak_lr != 1.0e-4 + or self.training.min_lr != 1.0e-6 + or self.training.warmup_steps != 5000 + or self.training.ema_decay != 0.9999 + ): + raise ValueError("legacy Action-v6 optimizer schedule is immutable") + preregistered = [ + (0, 10000, 0.0, 0.0), + (10000, 40000, 0.0, 0.5), + (40000, 80000, 0.5, 0.5), + (80000, 90000, 0.5, 0.75), + (90000, 100000, 0.75, 0.75), + ] + compressed = [ + (0, 10000, 0.0, 0.0), + (10000, 13000, 0.0, 0.5), + (13000, 16000, 0.5, 0.5), + (16000, 19000, 0.5, 0.75), + (19000, 22000, 0.75, 0.75), + ] + continuation = compressed + [(22000, 100000, 0.75, 0.75)] + actual = [(v.start, v.end, v.start_p, v.end_p) for v in self.training.predicted_future_curriculum] + if self.training.protocol == "preregistered_100k": + if self.training.steps != 100000 or actual != preregistered: + raise ValueError("preregistered_100k protocol differs from the locked design") + if not self.validation.enabled: + raise ValueError("preregistered_100k protocol requires validation") + elif self.training.protocol == "compressed_22k": + if self.training.steps != 22000 or actual != compressed: + raise ValueError("compressed_22k protocol must use the audited 10k+4x3k curriculum") + if self.validation.enabled: + raise ValueError("compressed_22k protocol disables in-training validation") + if self.checkpoint.preserve_steps != [10000, 13000, 16000, 19000, 22000]: + raise ValueError("compressed_22k protocol must preserve every stage boundary") + if ( + self.checkpoint.resume_from is None + or Path(self.checkpoint.resume_from).name != "action-checkpoint-10000" + ): + raise ValueError("compressed_22k protocol must start from action-checkpoint-10000") + elif self.training.protocol == "continuation_100k": + if self.training.steps != 100000 or actual != continuation: + raise ValueError( + "continuation_100k must preserve the audited 0-22k history and hold predicted p=0.75" + ) + if self.validation.enabled or not self.validation.quick_enabled: + raise ValueError( + "continuation_100k uses quick trajectory validation and disables exhaustive in-training validation" + ) + if ( + self.training.continuation_resume_step != 22000 + or self.training.continuation_rewarm_steps != 2000 + or self.training.continuation_peak_lr != 3.0e-5 + ): + raise ValueError("continuation_100k requires the locked conservative 22k-24k LR rewarm") + if self.training.save_every != 5000 or self.validation.quick_every != 5000: + raise ValueError("continuation_100k checkpoints and quick validation must align every 5k steps") + if self.validation.quick_batches != 16 or self.validation.quick_save_cases != 4: + raise ValueError("continuation_100k quick validation is locked to 512 windows and four cases") + if self.checkpoint.preserve_steps != [30000, 40000, 50000, 60000, 75000, 90000, 100000]: + raise ValueError("continuation_100k preserve steps differ from the reviewed plan") + if ( + self.checkpoint.resume_from is None + or Path(self.checkpoint.resume_from).name != "action-checkpoint-22000" + ): + raise ValueError("continuation_100k must start from action-checkpoint-22000") + elif self.training.protocol == "corrective_v7_round0": + if self.corrective is None: + raise ValueError("corrective_v7_round0 requires corrective data identities") + if self.training.steps != 3000 or actual != [(0, 3000, 0.75, 0.75)]: + raise ValueError("corrective_v7_round0 is locked to 3k updates at predicted p=0.75") + if ( + self.training.peak_lr != 1.0e-5 + or self.training.min_lr != 1.0e-6 + or self.training.warmup_steps != 500 + or self.training.ema_decay != 0.9995 + ): + raise ValueError("corrective_v7_round0 LR/EMA schedule differs from the reviewed plan") + if self.action.loss != "masked_action_flow_mse_execute8_gripper_weighted": + raise ValueError("corrective_v7_round0 requires the global-plus-deployment loss") + shares = ( + self.corrective.regular_expert_share, + self.corrective.exact_cold_share, + self.corrective.critical_event_share, + ) + if shares != (0.5, 0.4, 0.1) or self.corrective.regular_predicted_probability != 0.75: + raise ValueError("corrective_v7_round0 source mixture must be 50/40/10 and p_pred=0.75") + if self.checkpoint.resume_from is not None: + raise ValueError("Action-v7 resets optimizer state and cannot resume the v6 optimizer") + if ( + self.checkpoint.initialize_from_ema is None + or Path(self.checkpoint.initialize_from_ema).name != "action-checkpoint-60000" + ): + raise ValueError("Action-v7 round0 must initialize model weights from step-60k EMA") + if self.checkpoint.preserve_steps != [1000, 2000, 3000]: + raise ValueError("Action-v7 round0 must preserve each 1k boundary") + if not self.validation.quick_enabled or self.validation.quick_every != 1000: + raise ValueError("Action-v7 round0 requires a lightweight 1k validation panel") + elif self.training.protocol == "h1_50_gt10k_pred20k": + original = ( + self.training.steps == 30000 + and actual == [(0, 10000, 0.0, 0.0), (10000, 30000, 1.0, 1.0)] + and self.checkpoint.preserve_steps == [10000, 15000, 20000, 25000, 30000] + ) + shortened = ( + self.training.steps == 14139 + and actual == [(0, 4139, 0.0, 0.0), (4139, 14139, 1.0, 1.0)] + and self.checkpoint.preserve_steps == [4139, 6639, 9139, 11639, 14139] + and self.checkpoint.resume_from is not None + and Path(self.checkpoint.resume_from).name == "action-checkpoint-4139" + ) + if not (original or shortened): + raise ValueError("Action-v10 must use an audited GT-to-predicted curriculum") + if self.artifacts.world_branch != "online": + raise ValueError("Action-v10 requires the selected Online World-v10 checkpoint") + if ( + self.training.peak_lr != 1.0e-4 + or self.training.min_lr != 1.0e-6 + or self.training.warmup_steps != 5000 + or self.training.ema_decay != 0.0 + ): + raise ValueError("Action-v10 uses the original LR schedule and Online-only weights") + if self.data.history_lengths != [1, 3, 6, 10] or any( + abs(a - b) > 1e-9 + for a, b in zip( + self.data.history_probabilities, + [0.5, 1 / 6, 1 / 6, 1 / 6], + ) + ): + raise ValueError("Action-v10 history mixture must be 50%,1/6,1/6,1/6") + if not self.data.h1_episode_start_only: + raise ValueError("Action-v10 H1 must be episode-start latent_start=0") + if ( + self.checkpoint.initialize_from_online is None + or Path(self.checkpoint.initialize_from_online).name != "action-checkpoint-74559" + or self.checkpoint.initialize_from_ema is not None + ): + raise ValueError("Action-v10 must cold-start optimizer from step-74559 Online Action weights") + if self.predicted_future_cache.train_rows_per_stratum_history != 256: + raise ValueError("Action-v10 predicted-cache diversity must be 256/stratum/history") + if self.predicted_future_cache.val_rows_per_stratum_history != 16: + raise ValueError("Action-v10 validation cache must be 16/stratum/history") + elif self.training.protocol == "h1_50_pred8k_world_v11": + if ( + self.training.steps != 8000 + or actual != [(0, 8000, 1.0, 1.0)] + or self.checkpoint.preserve_steps != [2000, 4000, 6000, 8000] + ): + raise ValueError("Action-v11 must run exactly 8k predicted-future updates") + if ( + self.training.peak_lr != 3.0e-5 + or self.training.min_lr != 1.0e-6 + or self.training.warmup_steps != 500 + or self.training.ema_decay != 0.0 + ): + raise ValueError("Action-v11 optimizer schedule differs from the reviewed plan") + if self.artifacts.world_branch != "online": + raise ValueError("Action-v11 requires Online World weights") + if self.data.history_lengths != [1, 3, 6, 10] or any( + abs(a - b) > 1e-9 + for a, b in zip( + self.data.history_probabilities, + [0.5, 1 / 6, 1 / 6, 1 / 6], + ) + ): + raise ValueError("Action-v11 history mixture must be 50%,1/6,1/6,1/6") + if not self.data.h1_episode_start_only: + raise ValueError("Action-v11 H1 must be episode-start latent_start=0") + if ( + self.checkpoint.initialize_from_online is None + or Path(self.checkpoint.initialize_from_online).name + != "action-checkpoint-12452" + or self.checkpoint.resume_from is not None + or self.checkpoint.initialize_from_ema is not None + ): + raise ValueError("Action-v11 must reset optimizer from Action-v10 step-12452 Online") + if self.predicted_future_cache.train_rows_per_stratum_history != 128: + raise ValueError("Action-v11 cache must use 128 non-H1 rows/stratum/history") + if self.predicted_future_cache.val_rows_per_stratum_history != 16: + raise ValueError("Action-v11 validation cache must use 16 rows/stratum/history") + if self.artifacts.supplemental_case_manifest is None: + raise ValueError("Action-v11 requires the locked lift_pot supplemental case") + if not self.validation.quick_enabled or self.validation.quick_every != 2000: + raise ValueError("Action-v11 requires quick validation every 2k steps") + elif self.training.protocol == "eval_aligned_epoch_world_v12": + if ( + self.training.steps != 5_754 + or actual != [(0, 5_754, 1.0, 1.0)] + or self.checkpoint.preserve_steps != [1250, 2500, 3750, 5000, 5754] + ): + raise ValueError("Action-v12 must run one complete aligned H10 epoch") + if ( + self.training.global_batch != 1024 + or self.training.micro_batch_per_gpu != 128 + or self.training.grad_accumulation != 1 + or self.training.strategy != "fsdp2_full_shard" + or self.training.peak_lr != 1.0e-4 + or self.training.min_lr != 1.0e-6 + or self.training.warmup_steps != 300 + or self.training.ema_decay != 0.0 + ): + raise ValueError("Action-v12 must use the scaled original Action optimizer and no EMA") + if self.artifacts.world_branch != "online": + raise ValueError("Action-v12 requires final Online World-v12 weights") + if self.data.history_lengths != [1, 3, 6, 10] or any( + abs(value - 0.25) > 1e-12 for value in self.data.history_probabilities + ): + raise ValueError("Action-v12 histories must be exactly 25% each") + if ( + not self.data.h1_episode_start_only + or self.data.episode_start_only_histories != [1, 3, 6] + or not self.data.h10_all_legal_starts + or self.data.epoch_h10_windows != 1_472_828 + ): + raise ValueError("Action-v12 growing-prefix/H10 epoch contract changed") + if ( + self.checkpoint.initialize_from_online is None + or Path(self.checkpoint.initialize_from_online).name != "action-checkpoint-8000" + or self.checkpoint.resume_from is not None + or self.checkpoint.initialize_from_ema is not None + ): + raise ValueError("Action-v12 must reset optimizer from Action-v11 step-8000 Online") + if ( + not self.predicted_future_cache.full_eval_aligned + or self.predicted_future_cache.shard_rows != 8192 + or self.predicted_future_cache.train_rows_per_stratum_history != 0 + or self.predicted_future_cache.val_rows_per_stratum_history != 0 + ): + raise ValueError("Action-v12 requires the complete eval-aligned predicted cache") + if self.runtime.mode == "formal" and self.predicted_future_cache.max_rows_per_history != 0: + raise ValueError("formal Action-v12 cannot use a bounded smoke cache") + if self.validation.enabled: + raise ValueError("Action-v12 uses lightweight fixed validation, not exhaustive validation") + if not self.validation.quick_enabled or self.validation.quick_every != 1250: + raise ValueError("Action-v12 requires lightweight validation every 1250 steps") + if self.data.sampler_step_offset != 0: + raise ValueError("Action-v12 first epoch must start at sampler step zero") + elif self.training.protocol == "eval_aligned_continue4_world_v12": + boundaries = [5_754, 11_508, 17_262, 23_016] + if ( + self.training.steps != 23_016 + or actual != [(0, 23_016, 1.0, 1.0)] + or self.checkpoint.preserve_steps != boundaries + ): + raise ValueError("Action-v13 must run four complete additional aligned epochs") + if ( + self.training.global_batch != 1024 + or ( + self.training.micro_batch_per_gpu, + self.training.grad_accumulation, + ) + not in {(128, 1), (32, 4)} + or self.training.strategy != "fsdp2_full_shard" + or self.training.peak_lr != 5.0e-5 + or self.training.min_lr != 1.0e-6 + or self.training.warmup_steps != 1200 + or self.training.ema_decay != 0.0 + ): + raise ValueError("Action-v13 optimizer/effective-batch schedule differs from the reviewed continuation") + if self.artifacts.world_branch != "online": + raise ValueError("Action-v13 requires final Online World-v12 weights") + if self.data.history_lengths != [1, 3, 6, 10] or any( + abs(value - 0.25) > 1e-12 for value in self.data.history_probabilities + ): + raise ValueError("Action-v13 histories must remain exactly 25% each") + if ( + not self.data.h1_episode_start_only + or self.data.episode_start_only_histories != [1, 3, 6] + or not self.data.h10_all_legal_starts + or self.data.epoch_h10_windows != 1_472_828 + or self.data.sampler_step_offset != 5_754 + ): + raise ValueError("Action-v13 growing-prefix/H10 continuation cursor changed") + if ( + self.checkpoint.initialize_from_online is None + or Path(self.checkpoint.initialize_from_online).name != "action-checkpoint-5754" + or self.checkpoint.resume_from is not None + or self.checkpoint.initialize_from_ema is not None + ): + raise ValueError("Action-v13 must reset optimizer from final Action-v12 Online weights") + if ( + not self.predicted_future_cache.full_eval_aligned + or self.predicted_future_cache.shard_rows != 8192 + or self.predicted_future_cache.train_rows_per_stratum_history != 0 + or self.predicted_future_cache.val_rows_per_stratum_history != 0 + or self.predicted_future_cache.max_rows_per_history != 0 + ): + raise ValueError("Action-v13 must reuse the complete Action-v12 predicted cache") + if self.validation.enabled: + raise ValueError("Action-v13 uses lightweight fixed validation") + if ( + self.runtime.mode == "formal" + and self.training.activation_checkpoint_blocks != 7 + ): + raise ValueError("formal Action-v13 requires the selected 7/8 checkpoint layout") + if ( + not self.validation.quick_enabled + or self.validation.quick_every != 5_754 + or self.training.save_every != 5_754 + ): + raise ValueError("Action-v13 validates and checkpoints at every epoch boundary") + if self.training.steps <= self.training.warmup_steps: + raise ValueError("training steps must exceed warmup steps") + if not 0 <= self.training.activation_checkpoint_blocks <= 8: + raise ValueError("activation-checkpointed Action blocks must be in [0,8]") + if ( + self.training.protocol != "eval_aligned_continue4_world_v12" + and self.training.activation_checkpoint_blocks != 8 + ): + raise ValueError("only Action-v13 may use the reviewed partial checkpointing layout") + if min( + self.training.light_val_every, + self.training.full_val_every, + self.training.save_every, + self.validation.quick_every, + self.validation.quick_batches, + self.validation.quick_save_cases, + ) <= 0: + raise ValueError("validation and checkpoint intervals must be positive") + return self + + +def _load_extends(path: Path): + value = OmegaConf.load(path) + parent = value.pop("extends", None) + if parent is None: + return value + return OmegaConf.merge(_load_extends((path.parent / str(parent)).resolve()), value) + + +def load_config(path: str | Path) -> ActionV6RunConfig: + resolved = OmegaConf.to_container(_load_extends(Path(path).expanduser().resolve()), resolve=True) + return ActionV6RunConfig.model_validate(resolved) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/factory.py b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..d709e9140f7802c6a0824b7e1256f282181f4157 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/factory.py @@ -0,0 +1,75 @@ +"""Strict construction helpers; no legacy Action weights are accepted.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import torch +from safetensors.torch import load_file + +from mira.action_v6.model import BiHubWAMActionStage +from mira.world_v6.state_encoder import StateEncoderV6 + +from .artifacts import sha256_file +from .config import ActionV6RunConfig + + +def load_statistics(config: ActionV6RunConfig) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + if sha256_file(config.data.action_stats) != config.data.action_stats_sha256: + raise ValueError("action statistics SHA mismatch") + if sha256_file(config.data.delta_stats) != config.data.delta_stats_sha256: + raise ValueError("delta statistics SHA mismatch") + action = json.loads(Path(config.data.action_stats).read_text(encoding="utf-8")) + delta = json.loads(Path(config.data.delta_stats).read_text(encoding="utf-8")) + if action["split"] != "train_only" or delta["split"] != "train_only": + raise ValueError("Action v6 refuses non-train-only normalization") + if action["dimension_order"] != [ + "left_joint_0", "left_joint_1", "left_joint_2", "left_joint_3", "left_joint_4", "left_joint_5", "left_gripper", + "right_joint_0", "right_joint_1", "right_joint_2", "right_joint_3", "right_joint_4", "right_joint_5", "right_gripper", + ]: + raise ValueError("action statistics dimension order mismatch") + if delta["view_order"] != ["left", "global", "right"]: + raise ValueError("delta statistics view order mismatch") + mean = torch.tensor(action["mean"], dtype=torch.float32) + std = torch.tensor(action["std"], dtype=torch.float32) + scale = torch.tensor(delta["rms"], dtype=torch.float32) + if mean.shape != (14,) or std.shape != (14,) or scale.shape != (3, 10, 32): + raise ValueError("normalization tensor shape mismatch") + return mean, std, scale + + +def load_frozen_state_encoder(config: ActionV6RunConfig) -> StateEncoderV6: + if sha256_file(config.artifacts.state_encoder_ema) != config.artifacts.state_encoder_ema_sha256: + raise ValueError("frozen World State Encoder SHA mismatch") + encoder = StateEncoderV6(hidden_size=512, layers=2, heads=8, history_steps=20) + state = load_file(config.artifacts.state_encoder_ema, device="cpu") + forbidden = [name for name in state if "action" in name.lower()] + if forbidden: + raise RuntimeError(f"legacy/Action keys are forbidden in State Encoder export: {forbidden}") + encoder.load_state_dict(state, strict=True) + encoder.eval().requires_grad_(False) + return encoder + + +def build_action_stage(config: ActionV6RunConfig) -> BiHubWAMActionStage: + mean, std, delta = load_statistics(config) + stage = BiHubWAMActionStage( + state_encoder=load_frozen_state_encoder(config), + delta_scale=delta, + action_mean=mean, + action_std=std, + loss_mode=config.action.loss, + ) + return stage + + +def trainable_parameter_report(stage: BiHubWAMActionStage) -> dict[str, int]: + values = { + "transition_conditioner": sum(p.numel() for p in stage.transition_conditioner.parameters()), + "action_flow": sum(p.numel() for p in stage.action_flow.parameters()), + "state_encoder_frozen": sum(p.numel() for p in stage.state_encoder.parameters()), + } + values["trainable"] = sum(p.numel() for p in stage.parameters() if p.requires_grad) + values["total"] = sum(p.numel() for p in stage.parameters()) + return values diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/preflight.py b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/preflight.py new file mode 100644 index 0000000000000000000000000000000000000000..cd55740c409e81841e248701955da7a466e0b62b --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/preflight.py @@ -0,0 +1,341 @@ +"""Hard-fail Action-v6 upstream/training deployment audit.""" + +from __future__ import annotations + +import argparse +import json +import platform +import sys +from pathlib import Path + +import numpy as np +import torch + +from mira.action_v6.model import BiHubActionFlow, TransitionConditioner +from mira.benchmark.robotwin_v6.adapter import pack_action_dict, unpack_action_chunk +from mira.data.action_v6 import ActionV6Dataset, ExactColdStartDataset +from mira.data.robotwin_wam_schema import read_jsonl +from mira.training.world_v6.config import load_config as load_world_config + +from .artifacts import action_source_identity, canonical_sha256, sha256_file, write_json_atomic +from .config import ActionV6RunConfig, load_config + + +def _require_file(path: str | Path, expected_sha: str | None = None) -> Path: + value = Path(path).expanduser().resolve() + if not value.is_file(): + raise FileNotFoundError(value) + if expected_sha is not None and sha256_file(value) != expected_sha: + raise ValueError(f"SHA256 mismatch: {value}") + return value + + +def _dataset(config: ActionV6RunConfig, split: str, cache: bool) -> ActionV6Dataset: + return ActionV6Dataset( + source_manifest=config.artifacts.train_source_manifest if split == "train" else config.artifacts.val_source_manifest, + window_manifest=config.artifacts.train_window_manifest if split == "train" else config.artifacts.validation_window_manifest, + window_index=config.artifacts.train_window_index if split == "train" else config.artifacts.validation_window_index, + dataset_stats=config.artifacts.state_stats, + dataset_root=Path(config.artifacts.state_stats).parents[1], + anchors_root=None, + need_rgb=False, + episode_cache_size=1, + latent_mean=config.world_inference.latent_mean, + latent_std=config.world_inference.latent_std, + predicted_cache_root=config.predicted_future_cache.root if cache else None, + predicted_world_sha256=config.artifacts.world_checkpoint_sha256 if cache else None, + split=split, + ) + + +def _architecture_report() -> dict: + delta = torch.ones(3, 10, 32, device="cpu") + with torch.device("meta"): + transition = TransitionConditioner(delta) + action = BiHubActionFlow() + transition_count = sum(value.numel() for value in transition.parameters()) + action_count = sum(value.numel() for value in action.parameters()) + return { + "architecture": "bihub-wam-v6-action", + "transition_parameters": transition_count, + "action_parameters": action_count, + "trainable_parameters": transition_count + action_count, + "transition_module_tree": [name for name, _ in transition.named_modules()], + "action_module_tree": [name for name, _ in action.named_modules()], + "topology": { + "transition": "sequential_global_gather_local_broadcast", + "action": "local_shared_global_separate_action_register_hub", + "direct_left_right_attention": False, + "final_global_dead_branch": ( + "eliminated: post-broadcast Global FFN in block 8 has no observable consumer; " + "all earlier Global FFNs and the specified observable graph are unchanged" + ), + }, + } + + +def preflight(config_path: str, phase: str) -> None: + if phase not in {"upstream", "training"}: + raise ValueError("preflight phase must be upstream or training") + config = load_config(config_path) + checks: dict[str, object] = {} + _require_file(config.artifacts.codec_checkpoint, config.artifacts.codec_sha256) + _require_file(config.artifacts.world_config) + world_config = load_world_config(config.artifacts.world_config) + if canonical_sha256(world_config.model_dump(mode="json")) != config.artifacts.world_config_sha256: + raise RuntimeError("World resolved-config identity changed") + _require_file(config.artifacts.anchor_identity, config.artifacts.anchor_identity_sha256) + _require_file(config.artifacts.world_validation_report, config.artifacts.world_validation_report_sha256) + _require_file(config.artifacts.state_encoder_ema, config.artifacts.state_encoder_ema_sha256) + _require_file(config.artifacts.state_stats, config.artifacts.state_stats_sha256) + _require_file(config.artifacts.train_window_manifest, config.artifacts.train_window_manifest_sha256) + _require_file(config.artifacts.validation_window_manifest, config.artifacts.validation_window_manifest_sha256) + for path in ( + config.artifacts.world_selection_report, + config.artifacts.train_source_manifest, + config.artifacts.val_source_manifest, + config.artifacts.train_window_index, + config.artifacts.validation_window_index, + config.artifacts.split_identity, + ): + _require_file(path) + if not Path(config.artifacts.world_checkpoint).is_dir(): + raise FileNotFoundError(config.artifacts.world_checkpoint) + world_tree = json.loads( + (Path(config.artifacts.world_selection_report).parent / "world_checkpoint_tree.json").read_text() + ) + if world_tree["sha256"] != config.artifacts.world_checkpoint_sha256: + raise ValueError("selected World checkpoint tree identity mismatch") + selection = json.loads(Path(config.artifacts.world_selection_report).read_text()) + if selection["branch"] != "ema" or selection["sampling_steps"] != 10: + raise ValueError("Action v6 requires selected World EMA with 10-step solver") + if selection["checkpoint_sha256"] != config.artifacts.world_checkpoint_sha256: + raise ValueError("World selection report and config disagree") + validation = json.loads(Path(config.artifacts.world_validation_report).read_text()) + if not validation["passed"] or validation["step"] != 97314: + raise RuntimeError("final World validation did not pass at step 97314") + checks["world_ema_locked"] = True + + train_rows = read_jsonl(config.artifacts.train_source_manifest) + val_rows = read_jsonl(config.artifacts.val_source_manifest) + train_ids = {str(row["episode_sha256"]) for row in train_rows} + val_ids = {str(row["episode_sha256"]) for row in val_rows} + if len(train_rows) != 26_950 or len(val_rows) != 550 or train_ids & val_ids: + raise RuntimeError("immutable train/validation episode split mismatch") + summary = json.loads(Path(config.artifacts.split_identity).read_text()) + if summary["splits"]["train"]["windows"] != 1_472_828 or summary["splits"]["val"]["windows"] != 29_668: + raise RuntimeError("server window counts differ from locked Action deployment values") + checks["episodes"] = {"train": len(train_rows), "validation": len(val_rows), "overlap": 0} + checks["windows"] = {"train": 1_472_828, "validation": 29_668} + expected_full_batches = int(np.ceil(29_668 / (8 * config.training.micro_batch_per_gpu))) + if config.validation.full_batches != expected_full_batches or config.validation.save_cases != 8: + raise RuntimeError("formal validation must exhaust all windows and preserve eight fixed cases") + checks["validation_protocol"] = { + "all_windows": 29_668, + "distributed_batches": expected_full_batches, + "fixed_cases": 8, + "paired_future_sources": ["gt", "predicted"], + "flow_taus": [0.05, 0.25, 0.5, 0.75, 0.95], + "swanlab_immediate_upload": True, + } + + train_dataset = _dataset(config, "train", cache=False) + for index in (0, len(train_dataset) // 2, len(train_dataset) - 1): + sample = train_dataset[index] + expected = { + "z_current": (3, 1, 32, 9, 12), + "z_future_cond": (3, 10, 32, 9, 12), + "state_history": (20, 2, 7), + "action_gt": (20, 2, 7), + } + for name, shape in expected.items(): + if tuple(sample[name].shape) != shape or not torch.isfinite(sample[name]).all(): + raise RuntimeError(f"Action sample contract failed for {name}") + source = train_dataset._episode( + str(train_dataset.source_rows[train_dataset._locate_source(int(train_dataset.source_indices[index]))[0]]["cache_path"]) + ) + start = int(sample["metadata"]["action_start_20hz"]) + if not torch.equal(sample["action_gt"].reshape(20, 14), source["action20_f32"][start : start + 20]): + raise RuntimeError("Action target alignment failed") + checks["tensor_time_order_contract"] = True + + round_trip = np.linspace(-1, 1, 14, dtype=np.float32) + if not np.array_equal(pack_action_dict(unpack_action_chunk(round_trip)[0]), round_trip): + raise RuntimeError("XPolicyLab 14D qpos round trip failed") + checks["xpolicylab_round_trip"] = True + + repository = Path(__file__).resolve().parents[4] + source_identity = action_source_identity(repository) + checks["source_identity"] = source_identity["sha256"] + forbidden_patterns = ( + "from " + "mira.action" + " import", + "import " + "mira.action" + " ", + "action_head" + "_stage", + ) + for row in source_identity["files"]: + text = (repository / row["path"]).read_text(encoding="utf-8") + if any(pattern in text for pattern in forbidden_patterns): + raise RuntimeError(f"new Action-v6 source references forbidden legacy Action code: {row['path']}") + if phase == "training" and source_identity["sha256"] != config.experiment.code_identity: + raise RuntimeError("Action-v6 source changed after cache/config lock") + architecture = _architecture_report() + if config.corrective is not None: + architecture["architecture"] = "bihub-wam-v7-action-corrective" + architecture["initialization"] = "step-60000 EMA weights; fresh optimizer/scheduler/EMA" + architecture["objective"] = "0.5 global 20-step MSE + 0.5 execute8/gripper-weighted MSE" + architecture["source_identity"] = source_identity["sha256"] + write_json_atomic(Path(config.experiment.artifact_root) / "reports" / "architecture.json", architecture) + checks["architecture_parameters"] = architecture["trainable_parameters"] + + if torch.cuda.device_count() < 8: + raise RuntimeError("Action v6 formal launch requires eight visible GPUs") + gpu = [] + for index in range(8): + capability = torch.cuda.get_device_capability(index) + if not torch.cuda.is_bf16_supported(index): + raise RuntimeError(f"GPU {index} lacks BF16 support") + gpu.append( + { + "index": index, + "name": torch.cuda.get_device_name(index), + "capability": list(capability), + "memory_bytes": torch.cuda.get_device_properties(index).total_memory, + } + ) + checks["gpus"] = gpu + + if phase == "training": + pending = [ + value + for value in ( + config.experiment.code_identity, + config.data.action_stats_sha256, + config.data.delta_stats_sha256, + config.predicted_future_cache.identity_sha256, + ) + if value.startswith("PENDING") + ] + if pending: + raise RuntimeError("training config still contains pending identities") + _require_file(config.data.action_stats, config.data.action_stats_sha256) + _require_file(config.data.delta_stats, config.data.delta_stats_sha256) + _require_file(config.predicted_future_cache.identity_file, config.predicted_future_cache.identity_sha256) + gate_reports = {} + if config.corrective is None: + gate_specs = [ + (Path(config.experiment.artifact_root), name, name in {"tests.json", "overfit64.json", "canary.json"}) + for name in ("statistics.json", "tests.json", "overfit64.json", "cache_audit.json", "canary.json") + ] + else: + legacy_root = Path(config.experiment.artifact_root).with_name("action_v6") + gate_specs = [ + (legacy_root, "statistics.json", False), + (legacy_root, "overfit64.json", False), + (legacy_root, "cache_audit.json", False), + (Path(config.experiment.artifact_root), "tests.json", True), + (Path(config.experiment.artifact_root), "canary.json", True), + ] + for gate_root, report_name, require_current_source in gate_specs: + report_path = gate_root / "reports" / report_name + report = json.loads(_require_file(report_path).read_text()) + gate_reports[report_name] = report + if not report.get("passed"): + raise RuntimeError(f"Action training gate report did not pass: {report_path}") + if require_current_source and report.get("source_identity") != config.experiment.code_identity: + raise RuntimeError(f"Action training gate used another source tree: {report_path}") + checks["cache_diagnostic_protocol"] = gate_reports["cache_audit.json"]["structural"][ + "splits" + ]["val_sample1"]["diagnostic_selection"] + cache_identity = json.loads(Path(config.predicted_future_cache.identity_file).read_text()) + if cache_identity["world_checkpoint_sha256"] != config.artifacts.world_checkpoint_sha256: + raise RuntimeError("predicted cache uses another World") + cache_contract = { + "world_config_sha256": config.artifacts.world_config_sha256, + "anchor_identity_sha256": config.artifacts.anchor_identity_sha256, + "codec_sha256": config.artifacts.codec_sha256, + "seed_namespace": config.predicted_future_cache.seed_namespace, + "train_window_manifest_sha256": config.artifacts.train_window_manifest_sha256, + "validation_window_manifest_sha256": config.artifacts.validation_window_manifest_sha256, + } + if config.corrective is None: + cache_contract["code_identity"] = config.experiment.code_identity + for key, expected in cache_contract.items(): + if cache_identity.get(key) != expected: + raise RuntimeError(f"predicted cache contract mismatch for {key}") + for split in ("train", "val", "val_sample1"): + if not (Path(config.predicted_future_cache.root) / split / "COMPLETE.json").is_file(): + raise RuntimeError(f"predicted cache split {split} incomplete") + checks["downstream_gates"] = True + if config.corrective is not None: + cold_train = ExactColdStartDataset(config.corrective.exact_cold_train_manifest) + cold_val = ExactColdStartDataset(config.corrective.exact_cold_val_manifest) + if len(cold_train) != 26_950 or len(cold_val) != 550: + raise RuntimeError("formal exact-cold cache must cover every train/validation episode") + cold_train_ids = {str(row["episode_sha256"]) for row in cold_train.rows} + cold_val_ids = {str(row["episode_sha256"]) for row in cold_val.rows} + if cold_train_ids != train_ids or cold_val_ids != val_ids or cold_train_ids & cold_val_ids: + raise RuntimeError("exact-cold cache does not preserve the immutable episode split") + expected_initialization = str( + Path(config.checkpoint.initialize_from_ema or "").expanduser().resolve() + ) + for cold in (cold_train, cold_val): + if cold.identity.get("action_initialization_checkpoint") != expected_initialization: + raise RuntimeError("exact-cold cache was generated with another Action initialization") + if cold.identity.get("world_checkpoint") != str(Path(config.artifacts.world_checkpoint).resolve()): + raise RuntimeError("exact-cold cache was generated with another World checkpoint") + if cold.identity.get("codec_sha256") != config.artifacts.codec_sha256: + raise RuntimeError("exact-cold cache was generated with another codec") + critical_identity = json.loads( + _require_file(config.corrective.critical_event_identity).read_text() + ) + critical_path = _require_file( + config.corrective.critical_event_index, + critical_identity["index_sha256"], + ) + if critical_path.stat().st_size != 8 * int(critical_identity["rows"]): + raise RuntimeError("critical-event index byte count mismatch") + if len(critical_identity["task_domain_rows"]) != 100 or min( + critical_identity["task_domain_rows"].values() + ) <= 0: + raise RuntimeError("critical-event index does not cover all task/domain strata") + checks["corrective_data"] = { + "exact_cold_train": len(cold_train), + "exact_cold_validation": len(cold_val), + "critical_events": int(critical_identity["rows"]), + "mixture": [0.5, 0.4, 0.1], + "initialization": expected_initialization, + } + + environment = { + "python": sys.version, + "platform": platform.platform(), + "torch": torch.__version__, + "cuda": torch.version.cuda, + "cudnn": torch.backends.cudnn.version(), + "nccl": torch.cuda.nccl.version(), + } + report = { + "format_version": 1, + "passed": True, + "phase": phase, + "config": str(Path(config_path).resolve()), + "resolved_config_sha256": canonical_sha256(config.model_dump(mode="json")), + "checks": checks, + "environment": environment, + } + report["identity_sha256"] = canonical_sha256(report) + destination = Path(config.experiment.artifact_root) / "reports" / f"preflight-{phase}.json" + write_json_atomic(destination, report) + print(json.dumps(report, indent=2, default=str)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", required=True) + parser.add_argument("--phase", choices=("upstream", "training"), required=True) + args = parser.parse_args() + preflight(args.config, args.phase) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/select_world.py b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/select_world.py new file mode 100644 index 0000000000000000000000000000000000000000..5e5db2312cb22141ad3cdd1a7d057073ef07bb4c --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/select_world.py @@ -0,0 +1,202 @@ +"""Lock the final World EMA and export its exact frozen State Encoder.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch +import torch.distributed as dist +from safetensors.torch import save_file +from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import CheckpointImpl, checkpoint_wrapper +from torch.distributed.checkpoint.state_dict import StateDictOptions, get_model_state_dict +from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard + +from mira.data.world_v6 import WorldV6BalancedSampler, collate_world_v6, set_world_v6_process_name +from mira.training.distributed import set_up_distributed +from mira.training.ema import ModelEMA +from mira.training.world_v6.checkpoint import load_checkpoint +from mira.training.world_v6.config import load_config +from mira.training.world_v6.train import ( + _artifact_identity, + _canonical_parameter_name, + _configure_trainable, + _dataset, + _load_resampler_selection, + _optimizer, + _scheduler, +) +from mira.world_v6.migration import load_migrated_system + +from .artifacts import canonical_sha256, sha256_file, tree_identity, write_json_atomic + + +def _barrier() -> None: + if dist.is_initialized(): + dist.barrier() + + +def select_world( + world_config_path: str, + checkpoint_path: str, + validation_path: str, + output_root: str, +) -> None: + settings = set_up_distributed() + rank, world_size = settings.rank, settings.world_size + if world_size != 8: + raise RuntimeError("World-for-Action lock requires the formal eight-rank topology") + set_world_v6_process_name(f"syncnet_v6_asel{rank}") + device = torch.device("cuda", settings.device) + config = load_config(world_config_path) + if config.runtime.phase != "main": + raise ValueError("selected World config must resolve to phase=main") + checkpoint = Path(checkpoint_path).expanduser().resolve() + metadata = json.loads((checkpoint / "trainer_state.json").read_text(encoding="utf-8")) + validation_file = Path(validation_path).expanduser().resolve() + validation = json.loads(validation_file.read_text(encoding="utf-8")) + if not validation.get("passed") or int(validation.get("step", -1)) != int(metadata["completed_steps"]): + raise RuntimeError("fixed World validation does not certify the selected checkpoint") + if Path(validation["checkpoint"]).resolve() != checkpoint: + raise RuntimeError("fixed World validation points to another checkpoint") + + bootstrap_selection = json.loads(Path(config.artifacts.resampler_selection).read_text()) + system = load_migrated_system(bootstrap_selection["system_weights"], config.model) + _load_resampler_selection(system, config.artifacts.resampler_selection) + _configure_trainable(system, "main") + system = system.to(device) + policy = MixedPrecisionPolicy( + param_dtype=torch.bfloat16, reduce_dtype=torch.float32, output_dtype=torch.bfloat16 + ) + if config.model.activation_checkpointing: + system.world_model.external_activation_checkpointing = True + for index, block in enumerate(system.world_model.blocks): + system.world_model.blocks[index] = checkpoint_wrapper( + block, checkpoint_impl=CheckpointImpl.NO_REENTRANT, preserve_rng_state=True + ) + for block in system.world_model.blocks: + fully_shard(block, mp_policy=policy, reshard_after_forward=True) + fully_shard(system, mp_policy=policy, reshard_after_forward=True) + names = {id(parameter): _canonical_parameter_name(name) for name, parameter in system.named_parameters()} + optimizer, _ = _optimizer(system, config, names) + scheduler = _scheduler(optimizer, config) + ema = ModelEMA(system, decay=config.optimizer.ema_decay, unbias=False) + dataset = _dataset(config, "val") + sampler = WorldV6BalancedSampler( + dataset, seed=config.experiment.seed, rank=rank, world_size=world_size + ) + step = load_checkpoint( + checkpoint, + model=system, + optimizer=optimizer, + scheduler=scheduler, + ema=ema, + sampler=sampler, + expected_artifact_identity=_artifact_identity(config), + ) + if step != int(metadata["completed_steps"]): + raise RuntimeError("World checkpoint resume step mismatch") + system.eval() + + sample = dataset[rank] + batch, _ = collate_world_v6([sample]) + batch = batch.to(device) + assert batch.anchors is not None + generator = torch.Generator(device=device).manual_seed(2026 + rank) + noise = torch.randn(batch.z_future_raw.shape, generator=generator, device=device) + with ema.average_parameters(), torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16): + first = system( + z_context_raw=batch.z_context_raw, + z_future_raw=batch.z_future_raw, + anchors=batch.anchors, + state_history=batch.state_history, + history_valid=batch.history_valid, + future_valid=batch.future_valid, + view_valid=batch.view_valid, + sample_steps=10, + sample_noise=noise, + )["sample_future_raw"] + second = system( + z_context_raw=batch.z_context_raw, + z_future_raw=batch.z_future_raw, + anchors=batch.anchors, + state_history=batch.state_history, + history_valid=batch.history_valid, + future_valid=batch.future_valid, + view_valid=batch.view_valid, + sample_steps=10, + sample_noise=noise, + )["sample_future_raw"] + if not torch.equal(first, second): + raise RuntimeError("World EMA 10-step sampling is not exactly reproducible") + if not torch.isfinite(first).all(): + raise FloatingPointError("selected World generated non-finite future") + full = get_model_state_dict( + system, options=StateDictOptions(full_state_dict=True, cpu_offload=True) + ) + + output = Path(output_root).expanduser().resolve() + state_path = output / "state_encoder_ema.safetensors" + if rank == 0: + state = { + name.removeprefix("state_encoder."): value.contiguous() + for name, value in full.items() + if name.startswith("state_encoder.") and isinstance(value, torch.Tensor) + } + expected = system.state_encoder.state_dict() + if set(state) != set(expected): + missing = sorted(set(expected) - set(state)) + extra = sorted(set(state) - set(expected)) + raise RuntimeError(f"State Encoder export mismatch: missing={missing}, extra={extra}") + output.mkdir(parents=True, exist_ok=True) + temporary = state_path.with_name(f".{state_path.name}.tmp") + save_file(state, temporary) + temporary.replace(state_path) + _barrier() + + if rank == 0: + checkpoint_identity_path = output / "world_checkpoint_tree.json" + if checkpoint_identity_path.is_file(): + checkpoint_identity = json.loads(checkpoint_identity_path.read_text()) + else: + checkpoint_identity = tree_identity(checkpoint) + write_json_atomic(checkpoint_identity_path, checkpoint_identity) + selected = { + "format_version": 1, + "checkpoint": str(checkpoint), + "checkpoint_sha256": checkpoint_identity["sha256"], + "checkpoint_completed_steps": step, + "branch": "ema", + "resolved_config_sha256": canonical_sha256(metadata["resolved_config"]), + "codec_sha256": config.artifacts.codec_sha256, + "anchor_identity_sha256": sha256_file(config.artifacts.anchor_cache_identity), + "state_stats_sha256": sha256_file(config.artifacts.dataset_stats), + "world_validation_report": str(validation_file), + "world_validation_report_sha256": sha256_file(validation_file), + "state_encoder_ema": str(state_path), + "state_encoder_ema_sha256": sha256_file(state_path), + "sampler": "linear_quadratic_euler", + "sampling_steps": 10, + "flow_endpoint": "noise_0_to_data_1", + "deterministic_replay": True, + "view_order": ["left", "global", "right"], + } + selected["identity_sha256"] = canonical_sha256(selected) + write_json_atomic(output / "selected_world_for_action.json", selected) + print(json.dumps(selected, indent=2, ensure_ascii=False)) + _barrier() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--world-config", required=True) + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--validation", required=True) + parser.add_argument("--output-root", required=True) + args = parser.parse_args() + select_world(args.world_config, args.checkpoint, args.validation, args.output_root) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/train.py b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/train.py new file mode 100644 index 0000000000000000000000000000000000000000..b8a9b0e000b24ac24a5d9095d2509f383f6567c6 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/action_v6/train.py @@ -0,0 +1,1887 @@ +"""Eight-GPU formal/canary trainer for the v6 BiHub Action Head.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import logging +import math +import os +import pickle +import random +import signal +import time +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import torch.distributed as dist +import torch.distributed.checkpoint as dcp +from torch import Tensor +from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import CheckpointImpl, checkpoint_wrapper +from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard +from torch.utils.data import DataLoader + +from mira.action_v6.model import ActionV6Batch, BiHubWAMActionStage +from mira.data.action_v6 import ( + ActionV6Dataset, + ActionV7MixedDataset, + ExactColdStartDataset, + collate_action_v6, +) +from mira.data.action_v6_sampler import ( + ActionV6BalancedSampler, + ActionV7CorrectiveSampler, + Overfit64Sampler, + overfit64_indices, + predicted_probability, +) +from mira.data.action_v10 import ActionV10Dataset, ActionV10Sampler +from mira.data.action_v12 import ActionV12EpochSampler +from mira.data.world_v6 import set_world_v6_process_name +from mira.training.distributed import set_up_distributed +from mira.training.ema import ModelEMA +from mira.training.swanlab_tracker import SwanLabTracker +from mira.inference.robotwin_v6_runtime import _load_model_and_ema + +from .artifacts import action_source_identity, canonical_sha256, sha256_file, write_json_atomic +from .checkpoint import latest_checkpoint, load_checkpoint, save_checkpoint +from .config import ActionV6RunConfig, load_config +from .factory import build_action_stage, trainable_parameter_report + +LOGGER = logging.getLogger(__name__) +OVERFIT_EULER_TAUS = tuple(index / 10.0 for index in range(10)) +SHORT_HISTORY_ACTION_PROTOCOLS = { + "h1_50_gt10k_pred20k", + "h1_50_pred8k_world_v11", + "eval_aligned_epoch_world_v12", + "eval_aligned_continue4_world_v12", +} +EVAL_ALIGNED_ACTION_PROTOCOLS = { + "eval_aligned_epoch_world_v12", + "eval_aligned_continue4_world_v12", +} + + +def _barrier() -> None: + if dist.is_initialized(): + dist.barrier() + + +def _all_reduce_mean(value: Tensor) -> Tensor: + result = value.detach().clone() + if dist.is_initialized(): + dist.all_reduce(result) + result /= dist.get_world_size() + return result + + +def _canonical_name(name: str) -> str: + return name.replace("._checkpoint_wrapped_module.", ".") + + +def _artifact_identity(config: ActionV6RunConfig) -> dict[str, Any]: + if config.training.protocol in SHORT_HISTORY_ACTION_PROTOCOLS: + values = { + "architecture": ( + "bihub-wam-v13-action-eval-aligned-continue4epoch" + if config.training.protocol == "eval_aligned_continue4_world_v12" + else "bihub-wam-v12-action-eval-aligned-epoch" + if config.training.protocol == "eval_aligned_epoch_world_v12" + else "bihub-wam-v11-action-h1-50-pred8k" + if config.training.protocol == "h1_50_pred8k_world_v11" + else "bihub-wam-v10-action-h1-50" + ), + "code_identity": config.experiment.code_identity, + "codec": config.artifacts.codec_sha256, + "world": config.artifacts.world_checkpoint_sha256, + "world_branch": config.artifacts.world_branch, + "state_encoder": config.artifacts.state_encoder_ema_sha256, + "state_stats": config.artifacts.state_stats_sha256, + "action_stats": config.data.action_stats_sha256, + "delta_stats": config.data.delta_stats_sha256, + "train_source": sha256_file(config.artifacts.train_source_manifest), + "validation_source": sha256_file(config.artifacts.val_source_manifest), + "history_lengths": config.data.history_lengths, + "history_probabilities": config.data.history_probabilities, + "h1_episode_start_only": config.data.h1_episode_start_only, + "episode_start_only_histories": config.data.episode_start_only_histories, + "h10_all_legal_starts": config.data.h10_all_legal_starts, + "epoch_h10_windows": config.data.epoch_h10_windows, + "sampler_step_offset": config.data.sampler_step_offset, + "ema_enabled": False, + "supplemental_case": ( + sha256_file(config.artifacts.supplemental_case_manifest) + if config.artifacts.supplemental_case_manifest is not None + else None + ), + "predicted_cache_contract": { + "seed_namespace": config.predicted_future_cache.seed_namespace, + "train_rows_per_stratum_history": config.predicted_future_cache.train_rows_per_stratum_history, + "val_rows_per_stratum_history": config.predicted_future_cache.val_rows_per_stratum_history, + "full_eval_aligned": config.predicted_future_cache.full_eval_aligned, + "identity_sha256": ( + sha256_file(config.predicted_future_cache.identity_file) + if config.training.protocol in EVAL_ALIGNED_ACTION_PROTOCOLS + else None + ), + }, + "action_initialization_online": { + "checkpoint": str(config.checkpoint.initialize_from_online), + "trainer_state_sha256": sha256_file( + Path(str(config.checkpoint.initialize_from_online)) / "trainer_state.json" + ), + "branch": "online", + "optimizer_reset": True, + }, + "training_schedule": { + "steps": config.training.steps, + "activation_checkpoint_blocks": config.training.activation_checkpoint_blocks, + "curriculum": [ + segment.model_dump(mode="json") + for segment in config.training.predicted_future_curriculum + ], + }, + } + values["sha256"] = canonical_sha256(values) + return values + values = { + "architecture": "bihub-wam-v6-action", + "code_identity": config.experiment.code_identity, + "codec": config.artifacts.codec_sha256, + "anchor": config.artifacts.anchor_identity_sha256, + "world": config.artifacts.world_checkpoint_sha256, + "world_branch": config.artifacts.world_branch, + "world_selection": sha256_file(config.artifacts.world_selection_report), + "state_encoder": config.artifacts.state_encoder_ema_sha256, + "state_stats": config.artifacts.state_stats_sha256, + "action_stats": config.data.action_stats_sha256, + "delta_stats": config.data.delta_stats_sha256, + "train_windows": config.artifacts.train_window_manifest_sha256, + "validation_windows": config.artifacts.validation_window_manifest_sha256, + "predicted_future_cache": config.predicted_future_cache.identity_sha256, + } + if config.corrective is not None: + values.update( + { + "architecture": "bihub-wam-v7-action-corrective", + "initialization_checkpoint": str(config.checkpoint.initialize_from_ema), + "initialization_trainer_state": sha256_file( + Path(str(config.checkpoint.initialize_from_ema)) / "trainer_state.json" + ), + "exact_cold_train": sha256_file(config.corrective.exact_cold_train_manifest), + "exact_cold_train_identity": sha256_file( + Path(config.corrective.exact_cold_train_manifest).parent / "COMPLETE.json" + ), + "exact_cold_val": sha256_file(config.corrective.exact_cold_val_manifest), + "exact_cold_val_identity": sha256_file( + Path(config.corrective.exact_cold_val_manifest).parent / "COMPLETE.json" + ), + "critical_events": sha256_file(config.corrective.critical_event_index), + "critical_event_identity": sha256_file(config.corrective.critical_event_identity), + } + ) + values["sha256"] = canonical_sha256(values) + return values + + +def _dataset(config: ActionV6RunConfig, split: str, *, cache: bool = True) -> Any: + if config.training.protocol in SHORT_HISTORY_ACTION_PROTOCOLS: + if config.artifacts.qwen_hidden_cache_root is None: + raise ValueError("Action-v10 requires the World-v10 Qwen hidden cache") + return ActionV10Dataset( + source_manifest=( + config.artifacts.train_source_manifest + if split == "train" + else config.artifacts.val_source_manifest + ), + dataset_stats=config.artifacts.state_stats, + qwen_cache_root=config.artifacts.qwen_hidden_cache_root, + split=split, + latent_mean=config.world_inference.latent_mean, + latent_std=config.world_inference.latent_std, + predicted_cache_root=config.predicted_future_cache.root if cache else None, + predicted_world_fingerprint=config.artifacts.world_checkpoint_sha256 if cache else None, + episode_cache_size=config.data.episode_cache_size, + ) + return ActionV6Dataset( + source_manifest=( + config.artifacts.train_source_manifest + if split == "train" + else config.artifacts.val_source_manifest + ), + window_manifest=( + config.artifacts.train_window_manifest + if split == "train" + else config.artifacts.validation_window_manifest + ), + window_index=( + config.artifacts.train_window_index + if split == "train" + else config.artifacts.validation_window_index + ), + dataset_stats=config.artifacts.state_stats, + dataset_root=Path(config.artifacts.state_stats).parents[1], + anchors_root=None, + need_rgb=False, + episode_cache_size=config.data.episode_cache_size, + latent_mean=config.world_inference.latent_mean, + latent_std=config.world_inference.latent_std, + predicted_cache_root=config.predicted_future_cache.root if cache else None, + predicted_world_sha256=config.artifacts.world_checkpoint_sha256 if cache else None, + split=split, + ) + + +def _optimizer(stage: BiHubWAMActionStage, config: ActionV6RunConfig): + decay, no_decay = [], [] + names = {} + for name, parameter in stage.named_parameters(): + name = _canonical_name(name) + if not parameter.requires_grad: + continue + if not (name.startswith("transition_conditioner.") or name.startswith("action_flow.")): + raise RuntimeError(f"optimizer refuses non-Action parameter {name}") + names[id(parameter)] = name + is_matrix_weight = ( + parameter.ndim >= 2 + and name.endswith(".weight") + and not any(token in name.lower() for token in ("norm", "embedding")) + ) + (decay if is_matrix_weight else no_decay).append(parameter) + optimizer = torch.optim.AdamW( + [ + {"params": decay, "weight_decay": config.training.weight_decay}, + {"params": no_decay, "weight_decay": 0.0}, + ], + lr=config.training.peak_lr, + betas=tuple(config.training.betas), + eps=config.training.eps, + ) + return optimizer, names + + +def _scheduler(optimizer: torch.optim.Optimizer, config: ActionV6RunConfig): + total_steps = config.training.steps + warmup_steps = config.training.warmup_steps + if config.runtime.phase == "overfit64": + total_steps = int(config.runtime.max_steps or 3000) + warmup_steps = 100 + + def scale(step: int) -> float: + completed = step + 1 + if completed <= warmup_steps: + return completed / warmup_steps + floor = config.training.min_lr / config.training.peak_lr + if config.training.protocol == "continuation_100k": + resume_step = int(config.training.continuation_resume_step or 0) + rewarm_steps = config.training.continuation_rewarm_steps + continuation_peak_lr = float(config.training.continuation_peak_lr or 0.0) + continuation_peak_scale = continuation_peak_lr / config.training.peak_lr + # The step-22k checkpoint has LambdaLR.last_epoch=22000 and lr=1e-6. + # Keep the first resumed optimizer update at that exact LR, then + # conservatively rewarm to 3e-5 over 2k updates. This repairs the + # prematurely exhausted compressed schedule without a discontinuous + # jump in optimizer state. + boundary_completed = resume_step + 1 + rewarm_end = boundary_completed + rewarm_steps + if completed <= boundary_completed: + return floor + if completed <= rewarm_end: + progress = (completed - boundary_completed) / rewarm_steps + return floor + (continuation_peak_scale - floor) * progress + decay_progress = min( + 1.0, + (completed - rewarm_end) / (total_steps - rewarm_end), + ) + cosine = 0.5 * (1.0 + math.cos(math.pi * decay_progress)) + return floor + (continuation_peak_scale - floor) * cosine + if config.training.protocol == "compressed_22k": + # LambdaLR has already advanced to scheduler index 10_000 in the + # step-10k checkpoint, which corresponds to ``completed=10_001`` + # in this function. Reproduce the old curve through that exact + # boundary, then decay smoothly to the floor at step 22k. + boundary_completed = 10001 + original_progress = (min(completed, boundary_completed) - warmup_steps) / ( + 100000 - warmup_steps + ) + original_scale = floor + (1.0 - floor) * 0.5 * ( + 1.0 + math.cos(math.pi * original_progress) + ) + if completed <= boundary_completed: + return original_scale + boundary = floor + (1.0 - floor) * 0.5 * ( + 1.0 + + math.cos( + math.pi + * (boundary_completed - warmup_steps) + / (100000 - warmup_steps) + ) + ) + continuation_progress = min( + 1.0, + (completed - boundary_completed) / (total_steps - boundary_completed), + ) + continuation_cosine = 0.5 * (1.0 + math.cos(math.pi * continuation_progress)) + return floor + (boundary - floor) * continuation_cosine + progress = min( + 1.0, + (completed - warmup_steps) / (total_steps - warmup_steps), + ) + cosine = 0.5 * (1.0 + math.cos(math.pi * progress)) + return floor + (1.0 - floor) * cosine + + return torch.optim.lr_scheduler.LambdaLR(optimizer, scale) + + +def _frozen_hash(stage: BiHubWAMActionStage) -> str: + digest = hashlib.sha256() + for name, value in sorted(stage.state_encoder.state_dict().items()): + local = value.to_local() if hasattr(value, "to_local") else value + digest.update(name.encode()) + digest.update(local.detach().cpu().contiguous().view(torch.uint8).numpy().tobytes()) + return digest.hexdigest() + + +def _trainable_initialization_hash(stage: BiHubWAMActionStage) -> str: + digest = hashlib.sha256() + for name, value in sorted(stage.named_parameters()): + if not value.requires_grad: + continue + digest.update(name.encode()) + digest.update(value.detach().cpu().contiguous().view(torch.uint8).numpy().tobytes()) + return digest.hexdigest() + + +def _load_online_action_only( + stage: BiHubWAMActionStage, + checkpoint: Path, + *, + expected_step: int = 74_559, + expected_architecture: str = "bihub-wam-v6-action", +) -> dict[str, Any]: + """Load old Online Action weights while preserving the World-v10 StateEncoder.""" + + metadata = json.loads((checkpoint / "trainer_state.json").read_text(encoding="utf-8")) + if int(metadata.get("completed_steps", -1)) != expected_step: + raise ValueError(f"Action initialization is not the locked step-{expected_step} checkpoint") + if metadata.get("architecture") != expected_architecture: + raise ValueError("Action initialization architecture mismatch") + selected_state_encoder = { + name: value.detach().cpu().clone() + for name, value in stage.state_encoder.state_dict().items() + } + state = {"model": stage.state_dict()} + dcp.load(state, checkpoint_id=checkpoint / "distributed") + stage.load_state_dict(state["model"], strict=True) + stage.state_encoder.load_state_dict(selected_state_encoder, strict=True) + if not all(torch.isfinite(parameter).all() for parameter in stage.parameters()): + raise FloatingPointError("non-finite Action-v6 Online initialization") + digest = hashlib.sha256() + for relative in ("trainer_state.json", "distributed/.metadata"): + path = checkpoint / relative + digest.update(relative.encode()) + digest.update(sha256_file(path).encode()) + return { + "checkpoint": str(checkpoint), + "checkpoint_step": expected_step, + "checkpoint_fingerprint": digest.hexdigest(), + "source_branch": "online", + "optimizer_loaded": False, + "scheduler_loaded": False, + "ema_loaded": False, + "state_encoder_loaded": False, + } + + +def _full_grad_report(stage: BiHubWAMActionStage) -> tuple[dict[str, float], list[str]]: + groups: dict[str, Tensor] = {} + missing = [] + for name, parameter in stage.named_parameters(): + if not parameter.requires_grad: + if parameter.grad is not None: + raise RuntimeError(f"frozen parameter received a gradient: {name}") + continue + canonical = _canonical_name(name) + if parameter.grad is None: + missing.append(canonical) + continue + local = parameter.grad.to_local() if hasattr(parameter.grad, "to_local") else parameter.grad + if not torch.isfinite(local).all(): + raise FloatingPointError(f"non-finite gradient in {canonical}") + group = "transition" if canonical.startswith("transition_conditioner") else "action" + value = local.detach().float().square().sum() + groups[group] = groups.get(group, torch.zeros_like(value)) + value + if dist.is_initialized(): + for value in groups.values(): + dist.all_reduce(value) + return {name: float(value.sqrt()) for name, value in groups.items()}, missing + + +def _save_case_plot( + output: Path, + *, + completed: int, + branch: str, + case_index: int, + metadata: dict[str, Any], + prediction: Tensor, + target: Tensor, +) -> Path | None: + root = output / "fixed_cases" / branch / f"step-{completed:06d}" + root.mkdir(parents=True, exist_ok=True) + payload = { + "metadata": metadata, + "prediction": prediction.cpu(), + "target": target.cpu(), + "step": completed, + "branch": branch, + } + stem = f"case-{case_index:02d}" + torch.save(payload, root / f"{stem}.pth") + try: + import matplotlib.pyplot as plt + + labels = [f"L{i}" for i in range(6)] + ["Lgrip"] + [f"R{i}" for i in range(6)] + ["Rgrip"] + predicted = prediction.reshape(20, 14).float().numpy() + target = target.reshape(20, 14).float().numpy() + figure, axes = plt.subplots(7, 2, figsize=(12, 17), sharex=True) + for index, axis in enumerate(axes.flatten()): + axis.plot(target[:, index], label="GT", linewidth=2) + axis.plot(predicted[:, index], label="EMA/online sample", linewidth=1.5) + axis.set_title(labels[index]) + axis.grid(alpha=0.2) + axes[0, 0].legend() + figure.suptitle(f"{metadata['task']} / {metadata['domain']} / step {completed} / {branch}") + figure.tight_layout() + image_path = root / f"{stem}.png" + figure.savefig(image_path, dpi=130) + plt.close(figure) + return image_path + except Exception as error: + (root / f"{stem}.plot_error.txt").write_text(f"{type(error).__name__}: {error}\n") + return None + + +def _runtime_fingerprint( + stage: BiHubWAMActionStage, + optimizer: torch.optim.Optimizer, + scheduler: Any, + ema: ModelEMA, + sampler: Any, +) -> str: + """Hash every recovery-critical local value around an in-place DCP round trip.""" + + digest = hashlib.sha256() + + def update(value: Any) -> None: + if isinstance(value, Tensor): + local = value.to_local() if hasattr(value, "to_local") else value + digest.update(str(local.dtype).encode()) + digest.update(str(tuple(local.shape)).encode()) + # NumPy serializes scalar and non-scalar tensors uniformly; a + # dtype-changing Tensor.view is invalid for zero-dimensional Adam + # step counters. + digest.update(local.detach().cpu().contiguous().numpy().tobytes()) + elif isinstance(value, dict): + for key in sorted(value, key=str): + digest.update(str(key).encode()) + update(value[key]) + elif isinstance(value, (list, tuple)): + for child in value: + update(child) + else: + digest.update(pickle.dumps(value, protocol=5)) + + update({name: value for name, value in stage.state_dict().items()}) + update(optimizer.state_dict()) + update(scheduler.state_dict()) + update(ema.state_dict()) + update(sampler.state_dict()) + update(random.getstate()) + update(np.random.get_state()) + update(torch.get_rng_state()) + update(torch.cuda.get_rng_state() if torch.cuda.is_available() else None) + return digest.hexdigest() + + +@torch.inference_mode() +def _validate( + stage: BiHubWAMActionStage, + dataset: Any, + config: ActionV6RunConfig, + *, + device: torch.device, + rank: int, + world_size: int, + completed: int, + branch: str, + full: bool, + output: Path, + quick: bool = False, +) -> tuple[dict[str, float], list[Path]]: + was_training = stage.training + stage.eval() + batches = ( + config.validation.quick_batches + if quick + else (config.validation.full_batches if full else config.validation.light_batches) + ) + if full and config.runtime.phase != "training" and not quick: + batches = min(batches, config.validation.light_batches) + exhaustive = full and config.runtime.phase == "training" and not quick + global_micro_batch = world_size * config.training.micro_batch_per_gpu + required_batches = math.ceil(len(dataset) / global_micro_batch) + if exhaustive and batches != required_batches: + raise RuntimeError( + f"full validation must exhaust all {len(dataset)} windows: " + f"expected {required_batches} batches, configured {batches}" + ) + tau_values = (0.05, 0.25, 0.50, 0.75, 0.95) + condition_totals = { + source: { + "flow_sq": torch.zeros(5, 20, 2, 7, dtype=torch.float64, device=device), + "flow_count": torch.zeros(5, 20, 2, 7, dtype=torch.float64, device=device), + "sample_sq": torch.zeros(20, 2, 7, dtype=torch.float64, device=device), + "sample_abs": torch.zeros(20, 2, 7, dtype=torch.float64, device=device), + "sample_count": torch.zeros(20, 2, 7, dtype=torch.float64, device=device), + "denorm_abs": torch.zeros(20, 2, 7, dtype=torch.float64, device=device), + "motion_abs": torch.zeros(3, dtype=torch.float64, device=device), + "motion_pred_abs": torch.zeros(3, dtype=torch.float64, device=device), + "motion_target_abs": torch.zeros(3, dtype=torch.float64, device=device), + "motion_count": torch.zeros(3, dtype=torch.float64, device=device), + "first_action_current_abs": torch.zeros(2, dtype=torch.float64, device=device), + "endpoint_sq": torch.zeros(2, 7, dtype=torch.float64, device=device), + "endpoint_count": torch.zeros(2, 7, dtype=torch.float64, device=device), + "rates": torch.zeros(4, dtype=torch.float64, device=device), + "sync": torch.zeros(2, dtype=torch.float64, device=device), + } + for source in ("gt", "predicted") + } + intervention_totals = { + name: torch.zeros(2, dtype=torch.float64, device=device) + for name in ("interval_shuffled", "reversed", "current_repeat", "global_shuffled") + } + physical_stats = json.loads(Path(config.data.action_stats).read_text()) + lower = torch.tensor(physical_stats["physical_min"], device=device).reshape(2, 7) + upper = torch.tensor(physical_stats["physical_max"], device=device).reshape(2, 7) + state_stats = json.loads(Path(config.artifacts.state_stats).read_text()) + state_mean = torch.tensor(state_stats["mean"], device=device).reshape(2, 7) + state_std = torch.tensor(state_stats["std"], device=device).clamp_min( + float(state_stats.get("normalization_std_floor", 1.0e-2)) + ).reshape(2, 7) + case_limit = config.validation.quick_save_cases if quick else config.validation.save_cases + case_slots = set( + torch.linspace(0, max(0, batches - 1), case_limit) + .round() + .to(torch.int64) + .tolist() + ) if full else set() + saved_cases: list[Path] = [] + for batch_index in range(batches): + if exhaustive: + raw_indices = [ + batch_index * global_micro_batch + + rank * config.training.micro_batch_per_gpu + + offset + for offset in range(config.training.micro_batch_per_gpu) + ] + valid_samples = torch.tensor( + [index < len(dataset) for index in raw_indices], dtype=torch.bool, device=device + ) + indices = [min(index, len(dataset) - 1) for index in raw_indices] + else: + validation_indices = ( + dataset.validation_indices() + if isinstance(dataset, ActionV10Dataset) + else None + ) + if validation_indices is not None and not validation_indices: + raise RuntimeError("Action-v10 validation cache has no selected rows") + global_batch = batch_index * world_size + rank + start_index = ( + global_batch * config.training.micro_batch_per_gpu * 9973 + ) % (len(validation_indices) if validation_indices is not None else len(dataset)) + logical = [ + (start_index + offset) + % (len(validation_indices) if validation_indices is not None else len(dataset)) + for offset in range(config.training.micro_batch_per_gpu) + ] + indices = ( + [validation_indices[index] for index in logical] + if validation_indices is not None + else logical + ) + valid_samples = torch.ones(len(indices), dtype=torch.bool, device=device) + generator = torch.Generator(device=device).manual_seed( + config.validation.fixed_seed + batch_index * world_size + rank + ) + noise = torch.randn((len(indices), 20, 2, 7), generator=generator, device=device) + for source_id, source_name in ((0, "gt"), (1, "predicted")): + samples = [dataset[(index, source_id)] for index in indices] + batch, metadata = collate_action_v6(samples) + batch = batch.to(device) + valid_mask = ( + batch.action_valid_mask[:, :, None, None] + & valid_samples[:, None, None, None] + ).expand_as(batch.action_gt) + totals = condition_totals[source_name] + first_result = None + for tau_index, tau_value in enumerate(tau_values): + tau = torch.full( + (len(indices),), tau_value, dtype=torch.float32, device=device + ) + kwargs = {} + if first_result is not None: + kwargs = { + "transitions": first_result["transitions"], + "state_lgr": first_result["state_lgr"], + } + with torch.autocast("cuda", dtype=torch.bfloat16): + result = stage(batch, noise=noise, tau=tau, **kwargs) + if first_result is None: + first_result = result + squared = (result["velocity_pred"] - result["velocity_target"]).square() + totals["flow_sq"][tau_index] += (squared * valid_mask).sum(0).double() + totals["flow_count"][tau_index] += valid_mask.sum(0).double() + if not full: + continue + assert first_result is not None + value = noise.float().clone() + for solver_step in range(10): + solver_tau = torch.full( + (len(indices),), solver_step / 10.0, dtype=torch.float32, device=device + ) + with torch.autocast("cuda", dtype=torch.bfloat16): + step_result = stage( + batch, + noise=noise, + tau=solver_tau, + action_tau=value, + transitions=first_result["transitions"], + state_lgr=first_result["state_lgr"], + ) + value = value + 0.1 * step_result["velocity_pred"].float() + target_norm = stage.normalize_action(batch.action_gt) + difference = value - target_norm + totals["sample_sq"] += (difference.square() * valid_mask).sum(0).double() + totals["sample_abs"] += (difference.abs() * valid_mask).sum(0).double() + totals["sample_count"] += valid_mask.sum(0).double() + clipped = value.clamp( + -config.action.normalized_action_clip, config.action.normalized_action_clip + ) + action = stage.denormalize_action(clipped) + limited = action.clamp(lower, upper) + totals["denorm_abs"] += ( + (limited - batch.action_gt).abs() * valid_mask + ).sum(0).double() + totals["endpoint_sq"] += ( + difference[:, -1].square() * valid_samples[:, None, None] + ).sum(0).double() + totals["endpoint_count"] += valid_samples.sum().double() + totals["rates"][0] += ((clipped != value) & valid_mask).sum().double() + totals["rates"][1] += ((limited != action) & valid_mask).sum().double() + totals["rates"][2] += ((~torch.isfinite(value)) & valid_mask).sum().double() + totals["rates"][3] += valid_mask.sum().double() + current_state = batch.state_history[:, -1] * state_std + state_mean + first_action_mask = valid_samples[:, None, None].expand_as(current_state) + totals["first_action_current_abs"][0] += ( + (limited[:, 0] - current_state).abs() * first_action_mask + ).sum().double() + totals["first_action_current_abs"][1] += first_action_mask.sum().double() + for derivative in range(1, 4): + predicted_motion = torch.diff(limited, n=derivative, dim=1) + target_motion = torch.diff(batch.action_gt, n=derivative, dim=1) + motion_mask = valid_samples[:, None, None, None].expand_as(predicted_motion) + totals["motion_abs"][derivative - 1] += ( + (predicted_motion - target_motion).abs() * motion_mask + ).sum().double() + totals["motion_pred_abs"][derivative - 1] += ( + predicted_motion.abs() * motion_mask + ).sum().double() + totals["motion_target_abs"][derivative - 1] += ( + target_motion.abs() * motion_mask + ).sum().double() + totals["motion_count"][derivative - 1] += motion_mask.sum().double() + target_motion = torch.linalg.vector_norm( + torch.diff(target_norm, dim=1), dim=-1 + ) + predicted_motion = torch.linalg.vector_norm( + torch.diff(value, dim=1), dim=-1 + ) + for sample_index in range(len(indices)): + if not bool(valid_samples[sample_index]): + continue + if bool((target_motion[sample_index].amax(0) > 0.1).all()): + target_onset = (target_motion[sample_index] > 0.1).float().argmax(0) + predicted_onset = (predicted_motion[sample_index] > 0.1).float().argmax(0) + totals["sync"][0] += abs( + float(predicted_onset[0] - predicted_onset[1]) + - float(target_onset[0] - target_onset[1]) + ) + totals["sync"][1] += 1 + if ( + source_name == "predicted" + and rank == 0 + and batch_index in case_slots + and len(saved_cases) < case_limit + ): + case_path = _save_case_plot( + output, + completed=completed, + branch=branch, + case_index=len(saved_cases), + metadata=metadata[0], + prediction=limited[0].cpu(), + target=batch.action_gt[0].cpu(), + ) + if case_path is not None: + saved_cases.append(case_path) + if source_name == "predicted" and branch == "ema" and not quick: + sequence = torch.cat([batch.z_current, batch.z_future_cond], dim=2) + probe_tau = torch.full( + (len(indices),), 0.5, dtype=torch.float32, device=device + ) + repeat_batch = ActionV6Batch( + z_current=batch.z_current, + z_future_cond=batch.z_current.expand(-1, -1, 10, -1, -1, -1), + state_history=batch.state_history, + state_valid_mask=batch.state_valid_mask, + action_gt=batch.action_gt, + action_valid_mask=batch.action_valid_mask, + future_source=batch.future_source, + ) + with torch.autocast("cuda", dtype=torch.bfloat16): + reversed_result = stage( + batch, + noise=noise, + tau=probe_tau, + action_tau=noise, + state_lgr=first_result["state_lgr"], + transition_source=sequence[:, :, 1:], + transition_target=sequence[:, :, :-1], + ) + repeat_result = stage( + repeat_batch, + noise=noise, + tau=probe_tau, + action_tau=noise, + state_lgr=first_result["state_lgr"], + ) + shuffled = first_result["transitions"][:, :, [7, 2, 9, 0, 5, 1, 8, 3, 6, 4]] + global_shuffled = first_result["transitions"].clone() + global_shuffled[:, 1] = global_shuffled[:, 1].roll(1, dims=0) + intervention_transitions = { + "interval_shuffled": shuffled, + "reversed": reversed_result["transitions"], + "current_repeat": repeat_result["transitions"], + "global_shuffled": global_shuffled, + } + for intervention_name, intervention_transition in intervention_transitions.items(): + intervention_value = noise.float().clone() + for solver_step in range(10): + solver_tau = torch.full( + (len(indices),), + solver_step / 10.0, + dtype=torch.float32, + device=device, + ) + with torch.autocast("cuda", dtype=torch.bfloat16): + intervention_result = stage( + batch, + noise=noise, + tau=solver_tau, + action_tau=intervention_value, + transitions=intervention_transition, + state_lgr=first_result["state_lgr"], + ) + intervention_value += 0.1 * intervention_result[ + "velocity_pred" + ].float() + intervention_difference = intervention_value - target_norm + intervention_totals[intervention_name][0] += ( + intervention_difference.square() * valid_mask + ).sum().double() + intervention_totals[intervention_name][1] += valid_mask.sum().double() + for totals in condition_totals.values(): + for value in totals.values(): + dist.all_reduce(value) + for value in intervention_totals.values(): + dist.all_reduce(value) + metrics: dict[str, float] = {} + for source_name, totals in condition_totals.items(): + flow = totals["flow_sq"] / totals["flow_count"].clamp_min(1) + prefix = f"validation/{branch}/{source_name}" + metrics[f"{prefix}/flow_mse"] = float(flow.mean()) + metrics[f"{prefix}/flow_mse_left"] = float(flow[:, :, 0].mean()) + metrics[f"{prefix}/flow_mse_right"] = float(flow[:, :, 1].mean()) + for tau_index, tau_value in enumerate(tau_values): + metrics[f"{prefix}/flow_mse_tau_{tau_value:.2f}"] = float(flow[tau_index].mean()) + if full: + sample_mse = totals["sample_sq"] / totals["sample_count"].clamp_min(1) + sample_mae = totals["sample_abs"] / totals["sample_count"].clamp_min(1) + denorm_mae = totals["denorm_abs"] / totals["sample_count"].clamp_min(1) + metrics[f"{prefix}/sample_normalized_mse"] = float(sample_mse.mean()) + metrics[f"{prefix}/sample_normalized_mae"] = float(sample_mae.mean()) + metrics[f"{prefix}/sample_joint_mae"] = float(denorm_mae[:, :, :6].mean()) + metrics[f"{prefix}/sample_gripper_mae"] = float(denorm_mae[:, :, 6].mean()) + metrics[f"{prefix}/endpoint_normalized_mse"] = float( + (totals["endpoint_sq"] / totals["endpoint_count"].clamp_min(1)).mean() + ) + metrics[f"{prefix}/normalized_clip_rate"] = float( + totals["rates"][0] / totals["rates"][3].clamp_min(1) + ) + metrics[f"{prefix}/physical_limit_clamp_rate"] = float( + totals["rates"][1] / totals["rates"][3].clamp_min(1) + ) + metrics[f"{prefix}/nonfinite_count"] = float(totals["rates"][2]) + for derivative, label in enumerate(("velocity", "acceleration", "jerk")): + metrics[f"{prefix}/{label}_mae"] = float( + totals["motion_abs"][derivative] + / totals["motion_count"][derivative].clamp_min(1) + ) + metrics[f"{prefix}/predicted_{label}_abs_mean"] = float( + totals["motion_pred_abs"][derivative] + / totals["motion_count"][derivative].clamp_min(1) + ) + metrics[f"{prefix}/target_{label}_abs_mean"] = float( + totals["motion_target_abs"][derivative] + / totals["motion_count"][derivative].clamp_min(1) + ) + metrics[f"{prefix}/first_action_current_mae"] = float( + totals["first_action_current_abs"][0] + / totals["first_action_current_abs"][1].clamp_min(1) + ) + metrics[f"{prefix}/two_arm_sync_error_steps"] = float( + totals["sync"][0] / totals["sync"][1].clamp_min(1) + ) + metrics[f"validation/{branch}/predicted_minus_gt_flow_mse"] = ( + metrics[f"validation/{branch}/predicted/flow_mse"] + - metrics[f"validation/{branch}/gt/flow_mse"] + ) + if full: + metrics[f"validation/{branch}/predicted_minus_gt_sample_mse"] = ( + metrics[f"validation/{branch}/predicted/sample_normalized_mse"] + - metrics[f"validation/{branch}/gt/sample_normalized_mse"] + ) + if branch == "ema" and not quick: + correct = metrics["validation/ema/predicted/sample_normalized_mse"] + for intervention_name, value in intervention_totals.items(): + intervention_mse = float(value[0] / value[1].clamp_min(1)) + metrics[f"validation/ema/intervention/{intervention_name}_mse"] = intervention_mse + metrics[f"validation/ema/intervention/{intervention_name}_margin"] = ( + intervention_mse - correct + ) + if was_training: + stage.train() + return metrics, saved_cases + + +@torch.inference_mode() +def _validate_exact_cold( + stage: BiHubWAMActionStage, + dataset: ExactColdStartDataset, + config: ActionV6RunConfig, + *, + device: torch.device, + rank: int, + world_size: int, + completed: int, + output: Path, +) -> tuple[dict[str, float], list[Path]]: + """Small deterministic deployment-cold panel; no simulator rollout required.""" + was_training = stage.training + stage.eval() + batches = min(4, math.ceil(len(dataset) / (world_size * config.training.micro_batch_per_gpu))) + totals = torch.zeros(10, dtype=torch.float64, device=device) + physical_stats = json.loads(Path(config.data.action_stats).read_text()) + lower = torch.tensor(physical_stats["physical_min"], device=device).reshape(2, 7) + upper = torch.tensor(physical_stats["physical_max"], device=device).reshape(2, 7) + state_stats = json.loads(Path(config.artifacts.state_stats).read_text()) + state_mean = torch.tensor(state_stats["mean"], device=device).reshape(2, 7) + state_std = torch.tensor(state_stats["std"], device=device).clamp_min( + float(state_stats.get("normalization_std_floor", 1.0e-2)) + ).reshape(2, 7) + cases: list[Path] = [] + for batch_index in range(batches): + indices = [ + (batch_index * world_size * config.training.micro_batch_per_gpu + + rank * config.training.micro_batch_per_gpu + offset) % len(dataset) + for offset in range(config.training.micro_batch_per_gpu) + ] + batch, metadata = collate_action_v6([dataset[index] for index in indices]) + batch = batch.to(device) + generator = torch.Generator(device=device).manual_seed( + config.validation.fixed_seed + 700_000 + batch_index * world_size + rank + ) + noise = torch.randn(batch.action_gt.shape, generator=generator, device=device) + tau0 = torch.zeros(len(indices), device=device) + with torch.autocast("cuda", dtype=torch.bfloat16): + condition = stage(batch, noise=noise, tau=tau0, action_tau=noise) + value = noise.float().clone() + for solver_step in range(10): + tau = torch.full((len(indices),), solver_step / 10.0, device=device) + with torch.autocast("cuda", dtype=torch.bfloat16): + result = stage( + batch, + noise=noise, + tau=tau, + action_tau=value, + transitions=condition["transitions"], + state_lgr=condition["state_lgr"], + ) + value += 0.1 * result["velocity_pred"].float() + target = stage.normalize_action(batch.action_gt) + difference = value - target + action = stage.denormalize_action( + value.clamp(-config.action.normalized_action_clip, config.action.normalized_action_clip) + ).clamp(lower, upper) + current = batch.state_history[:, -1] * state_std + state_mean + totals[0] += difference.square().sum().double() + totals[1] += difference.numel() + totals[2] += difference[:, :8].square().sum().double() + totals[3] += difference[:, :8].numel() + totals[4] += (action[:, :8] - batch.action_gt[:, :8]).abs().sum().double() + totals[5] += batch.action_gt[:, :8].numel() + totals[6] += (action[:, 0] - current).abs().sum().double() + totals[7] += current.numel() + totals[8] += (batch.action_gt[:, 0] - current).abs().sum().double() + totals[9] += current.numel() + if rank == 0 and len(cases) < config.validation.quick_save_cases: + path = _save_case_plot( + output, + completed=completed, + branch="ema_exact_cold", + case_index=len(cases), + metadata=metadata[0], + prediction=action[0].cpu(), + target=batch.action_gt[0].cpu(), + ) + if path is not None: + cases.append(path) + dist.all_reduce(totals) + stage.train(was_training) + return { + "validation/ema/exact_cold/sample_normalized_mse": float(totals[0] / totals[1]), + "validation/ema/exact_cold/execute8_normalized_mse": float(totals[2] / totals[3]), + "validation/ema/exact_cold/execute8_physical_mae": float(totals[4] / totals[5]), + "validation/ema/exact_cold/first_action_delta_pred_mae": float(totals[6] / totals[7]), + "validation/ema/exact_cold/first_action_delta_target_mae": float(totals[8] / totals[9]), + }, cases + + +def _write_metric(path: Path, value: dict[str, Any]) -> None: + with path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(value, sort_keys=True, default=float) + "\n") + + +def _fixed_overfit_noise(metadata: list[dict[str, Any]], shape: torch.Size, device: torch.device) -> Tensor: + noises = [] + for row in metadata: + seed = int.from_bytes(hashlib.sha256((row["window_id"] + "action-overfit64").encode()).digest()[:8], "big") % (2**63 - 1) + generator = torch.Generator(device=device).manual_seed(seed) + noises.append(torch.randn(shape[1:], generator=generator, device=device)) + return torch.stack(noises) + + +def _fixed_overfit_tau( + metadata: list[dict[str, Any]], visits: list[int], device: torch.device +) -> Tensor: + """Return a restart-stable, per-window traversal of the deployment Euler grid. + + A single fixed tau per window can drive pointwise flow loss to zero without + exercising the ten points used by the deployed sampler. Each window keeps + its fixed noise and deterministically visits every Euler point once per ten + repeats. This remains a fixed gate dataset and is exactly recoverable from + the sampler cursor. + """ + if len(metadata) != len(visits): + raise ValueError("overfit metadata/visit count mismatch") + values = [] + for row, visit in zip(metadata, visits, strict=True): + offset = int.from_bytes( + hashlib.sha256((row["window_id"] + "action-overfit64-tau").encode()).digest()[:8], + "big", + ) % len(OVERFIT_EULER_TAUS) + values.append(OVERFIT_EULER_TAUS[(offset + int(visit)) % len(OVERFIT_EULER_TAUS)]) + return torch.tensor(values, dtype=torch.float32, device=device) + + +@torch.inference_mode() +def _validate_overfit64( + stage: BiHubWAMActionStage, + dataset: ActionV6Dataset, + *, + device: torch.device, + rank: int, + world_size: int, +) -> dict[str, float]: + indices = overfit64_indices(dataset)[rank::world_size] + total = torch.zeros(3, dtype=torch.float64, device=device) + stage.eval() + for start in range(0, len(indices), 4): + samples = [dataset[(index, 0)] for index in indices[start : start + 4]] + batch, metadata = collate_action_v6(samples) + batch = batch.to(device) + noise = _fixed_overfit_noise(metadata, batch.action_gt.shape, device) + tau0 = torch.zeros(len(samples), dtype=torch.float32, device=device) + with torch.autocast("cuda", dtype=torch.bfloat16): + conditions = stage(batch, noise=noise, tau=tau0, action_tau=noise) + value = noise.clone() + for solver_tau in OVERFIT_EULER_TAUS: + tau = torch.full((len(samples),), solver_tau, device=device) + with torch.autocast("cuda", dtype=torch.bfloat16): + result = stage( + batch, + noise=noise, + tau=tau, + action_tau=value, + transitions=conditions["transitions"], + state_lgr=conditions["state_lgr"], + ) + value += 0.1 * result["velocity_pred"] + target = stage.normalize_action(batch.action_gt) + total[0] += (value - target).square().sum().double() + total[1] += target.numel() + total[2] += (~torch.isfinite(value)).sum() + dist.all_reduce(total) + stage.train() + return { + "normalized_sampled_action_mse": float(total[0] / total[1].clamp_min(1)), + "nonfinite_count": float(total[2]), + } + + +def train(config: ActionV6RunConfig) -> None: + settings = set_up_distributed() + rank, world_size = settings.rank, settings.world_size + if world_size != config.training.expected_world_size: + raise RuntimeError("Action v6 formal/canary requires eight ranks") + device = torch.device("cuda", settings.device) + process_prefix = os.environ.get("MIRA_V6_PROCESS_PREFIX", "syncnet_v6_action") + set_world_v6_process_name(f"{process_prefix}_r{rank}") + logging.basicConfig( + level=logging.INFO if rank == 0 else logging.WARNING, + format="%(asctime)s | %(levelname)s | %(message)s", + ) + effective = world_size * config.training.micro_batch_per_gpu * config.training.grad_accumulation + if effective != config.training.global_batch: + raise RuntimeError(f"effective global batch {effective} != {config.training.global_batch}") + # Every rank must construct the exact same full parameter tensors before + # FSDP shards them. Rank-specific RNG is installed only after construction. + initialization_seed = config.experiment.seed + random.seed(initialization_seed) + np.random.seed(initialization_seed) + torch.manual_seed(initialization_seed) + torch.cuda.manual_seed(initialization_seed) + torch.backends.cuda.matmul.allow_tf32 = True + output = Path(config.experiment.output_root) + if config.runtime.phase == "canary": + output = output.with_name(f"{output.name}_canary") + elif config.runtime.phase == "overfit64": + output = output.with_name(f"{output.name}_overfit64") + output.mkdir(parents=True, exist_ok=True) + if rank == 0: + write_json_atomic(output / "resolved_config.json", config.model_dump(mode="json")) + stage = build_action_stage(config).to(device) + initialization_load = None + if config.checkpoint.initialize_from_online is not None: + expected_initialization_step = ( + 5_754 + if config.training.protocol == "eval_aligned_continue4_world_v12" + else 8_000 + if config.training.protocol == "eval_aligned_epoch_world_v12" + else 12_452 + if config.training.protocol == "h1_50_pred8k_world_v11" + else 74_559 + ) + expected_initialization_architecture = ( + "bihub-wam-v12-action-eval-aligned-epoch" + if config.training.protocol == "eval_aligned_continue4_world_v12" + else "bihub-wam-v11-action-h1-50-pred8k" + if config.training.protocol == "eval_aligned_epoch_world_v12" + else "bihub-wam-v10-action-h1-50" + if config.training.protocol == "h1_50_pred8k_world_v11" + else "bihub-wam-v6-action" + ) + initialization_load = _load_online_action_only( + stage, + Path(config.checkpoint.initialize_from_online).expanduser().resolve(), + expected_step=expected_initialization_step, + expected_architecture=expected_initialization_architecture, + ) + elif config.checkpoint.initialize_from_ema is not None: + initialization_load = _load_model_and_ema( + stage, Path(config.checkpoint.initialize_from_ema).expanduser().resolve() + ) + parameter_report = trainable_parameter_report(stage) + initialization_hash = _trainable_initialization_hash(stage) + initialization_hashes: list[str | None] = [None] * world_size + dist.all_gather_object(initialization_hashes, initialization_hash) + if len(set(initialization_hashes)) != 1: + raise RuntimeError("Action parameter initialization differs across FSDP ranks") + if config.training.activation_checkpointing: + for index in range(config.training.activation_checkpoint_blocks): + block = stage.action_flow.blocks[index] + stage.action_flow.blocks[index] = checkpoint_wrapper( + block, checkpoint_impl=CheckpointImpl.NO_REENTRANT, preserve_rng_state=True + ) + policy = MixedPrecisionPolicy( + param_dtype=torch.bfloat16, reduce_dtype=torch.float32, output_dtype=torch.bfloat16 + ) + for layer in stage.transition_conditioner.qformer.layers: + fully_shard(layer, mp_policy=policy, reshard_after_forward=True) + fully_shard(stage.transition_conditioner.hub, mp_policy=policy, reshard_after_forward=True) + for block in stage.action_flow.blocks: + fully_shard(block, mp_policy=policy, reshard_after_forward=True) + fully_shard(stage, mp_policy=policy, reshard_after_forward=True) + optimizer, parameter_names = _optimizer(stage, config) + scheduler = _scheduler(optimizer, config) + ema = ModelEMA(stage, decay=config.training.ema_decay, unbias=False) + runtime_seed = config.experiment.seed + rank + random.seed(runtime_seed) + np.random.seed(runtime_seed) + torch.manual_seed(runtime_seed) + torch.cuda.manual_seed(runtime_seed) + first_phase_only = ( + config.training.protocol == "h1_50_gt10k_pred20k" + and config.runtime.max_steps is not None + and config.runtime.max_steps <= 10000 + ) + uses_cache = config.runtime.phase != "overfit64" and not first_phase_only + expert_train_dataset = _dataset(config, "train", cache=uses_cache) + train_dataset: Any = expert_train_dataset + cold_train_dataset = None + if config.training.protocol == "corrective_v7_round0": + assert config.corrective is not None + cold_train_dataset = ExactColdStartDataset(config.corrective.exact_cold_train_manifest) + train_dataset = ActionV7MixedDataset( + expert_train_dataset, + cold_train_dataset, + config.corrective.critical_event_index, + ) + validation_requested = config.validation.enabled or config.validation.quick_enabled + val_dataset = _dataset(config, "val", cache=uses_cache) if validation_requested else None + cold_val_dataset = ( + ExactColdStartDataset(config.corrective.exact_cold_val_manifest) + if config.corrective is not None and validation_requested + else None + ) + total = config.training.steps + if config.runtime.max_steps is not None: + total = min(total, config.runtime.max_steps) + curriculum = [ + (segment.start, segment.end, segment.start_p, segment.end_p) + for segment in config.training.predicted_future_curriculum + ] + predicted_start_step = ( + 0 + if config.training.protocol in { + "h1_50_pred8k_world_v11", + "eval_aligned_epoch_world_v12", + "eval_aligned_continue4_world_v12", + } + else config.training.predicted_future_curriculum[1].start + ) + supplemental_expanded_index = None + if config.artifacts.supplemental_case_manifest is not None: + supplemental_payload = json.loads( + Path(config.artifacts.supplemental_case_manifest).read_text(encoding="utf-8") + ) + supplemental_expanded_index = int( + supplemental_payload["sample"]["expanded_index"] + ) + sampler = ( + Overfit64Sampler(expert_train_dataset, rank=rank, world_size=world_size) + if config.runtime.phase == "overfit64" + else ActionV7CorrectiveSampler( + train_dataset, + seed=config.experiment.seed, + rank=rank, + world_size=world_size, + regular_share=config.corrective.regular_expert_share, + cold_share=config.corrective.exact_cold_share, + critical_share=config.corrective.critical_event_share, + regular_predicted_probability=config.corrective.regular_predicted_probability, + clean_probability=config.data.clean_probability, + ) + if config.training.protocol == "corrective_v7_round0" + else ActionV12EpochSampler( + expert_train_dataset, + seed=config.experiment.seed, + rank=rank, + world_size=world_size, + micro_batch=config.training.micro_batch_per_gpu, + accumulation=config.training.grad_accumulation, + curriculum=curriculum, + optimizer_step_offset=config.data.sampler_step_offset, + ) + if config.training.protocol in EVAL_ALIGNED_ACTION_PROTOCOLS + else ActionV10Sampler( + expert_train_dataset, + seed=config.experiment.seed, + rank=rank, + world_size=world_size, + micro_batch=config.training.micro_batch_per_gpu, + accumulation=config.training.grad_accumulation, + predicted_start_step=predicted_start_step, + clean_probability=config.data.clean_probability, + supplemental_expanded_index=supplemental_expanded_index, + ) + if config.training.protocol in SHORT_HISTORY_ACTION_PROTOCOLS + else ActionV6BalancedSampler( + expert_train_dataset, + seed=config.experiment.seed, + rank=rank, + world_size=world_size, + micro_batch=config.training.micro_batch_per_gpu, + accumulation=config.training.grad_accumulation, + clean_probability=config.data.clean_probability, + compressed_curriculum_steps=total if config.runtime.phase == "canary" else None, + curriculum=( + None + if config.runtime.phase == "canary" + else curriculum + ), + ) + ) + loader = DataLoader( + train_dataset, + batch_size=config.training.micro_batch_per_gpu, + sampler=sampler, + num_workers=config.data.num_workers, + prefetch_factor=2 if config.data.num_workers else None, + persistent_workers=config.data.num_workers > 0, + pin_memory=True, + collate_fn=collate_action_v6, + ) + identity = _artifact_identity(config) + start = 0 + if config.checkpoint.auto_resume: + checkpoint = latest_checkpoint(output) + if checkpoint is None and config.checkpoint.resume_from is not None: + checkpoint = Path(config.checkpoint.resume_from).expanduser().resolve() + if checkpoint is not None: + resume_identity = identity + if config.training.protocol == "h1_50_gt10k_pred20k": + checkpoint_metadata = json.loads( + (checkpoint / "trainer_state.json").read_text(encoding="utf-8") + ) + saved_identity = checkpoint_metadata["artifact_identity"] + if saved_identity.get("sha256") != identity.get("sha256"): + immutable_keys = ( + "architecture", + "codec", + "world", + "world_branch", + "state_encoder", + "state_stats", + "action_stats", + "delta_stats", + "train_source", + "validation_source", + "history_lengths", + "history_probabilities", + "h1_episode_start_only", + "ema_enabled", + "predicted_cache_contract", + "action_initialization_online", + ) + changed = [ + key for key in immutable_keys + if saved_identity.get(key) != identity.get(key) + ] + if changed or int(checkpoint_metadata["completed_steps"]) != 4139: + raise ValueError( + f"Action-v10 schedule migration changed immutable lineage: {changed}" + ) + resume_identity = saved_identity + if rank == 0: + write_json_atomic( + output / "schedule_migration_step4139.json", + { + "passed": True, + "resume_checkpoint": str(checkpoint), + "resume_step": 4139, + "old_artifact_identity_sha256": checkpoint_metadata["artifact_identity_sha256"], + "new_artifact_identity_sha256": canonical_sha256(identity), + "change": "stop GT at 4139; train 100% predicted through 14139", + }, + ) + start = load_checkpoint( + checkpoint, + model=stage, + optimizer=optimizer, + scheduler=scheduler, + ema=ema, + sampler=sampler, + expected_artifact_identity=resume_identity, + ) + initial_resume_step = start + recovery_gate_step = min(total, 250) if start < 250 else min(total, start + 1) + iterator = iter(loader) + frozen_initial = _frozen_hash(stage) + frozen_hashes: list[str | None] = [None] * world_size + dist.all_gather_object(frozen_hashes, frozen_initial) + tracker = SwanLabTracker.disabled() + if rank == 0 and config.logging.swanlab_enabled: + tracker = SwanLabTracker.initialize( + { + "project": config.logging.swanlab_project, + "experiment_name": config.logging.swanlab_experiment_name, + "mode": "online", + "token_file": config.logging.swanlab_token_file, + "capture_console": "stderr", + "system_monitor": False, + "upload_hardware": True, + "upload_runtime": True, + "upload_requirements": False, + "upload_git": False, + "resume": "allow", + "public": False, + }, + output_dir=output, + run_config=config.model_dump(mode="json"), + ) + requested_stop = False + + def stop_handler(_signum: int, _frame: Any) -> None: + nonlocal requested_stop + requested_stop = True + + signal.signal(signal.SIGTERM, stop_handler) + signal.signal(signal.SIGINT, stop_handler) + metrics_path = output / "metrics.jsonl" + stage.train() + last_metrics: dict[str, Any] = {} + recovery_round_trip_verified = False + frozen_verified = True + overfit_passed = False + best_metric = math.inf + best_path = output / "best_checkpoint.json" + if best_path.is_file(): + best_value = json.loads(best_path.read_text()) + best_metric = float(best_value["predicted_ema_normalized_mse"]) + interval_start = time.monotonic() + interval_samples = 0 + torch.cuda.reset_peak_memory_stats(device) + try: + for step in range(start, total): + optimizer.zero_grad(set_to_none=True) + loss_sum = torch.zeros((), dtype=torch.float64, device=device) + tau_sum = torch.zeros((), dtype=torch.float64, device=device) + source_counts = torch.zeros(3, dtype=torch.int64, device=device) + history_counts = torch.zeros(4, dtype=torch.int64, device=device) + source_loss_sums = torch.zeros(3, dtype=torch.float64, device=device) + sample_source_counts = torch.zeros(3, dtype=torch.int64, device=device) + uniform_loss_sum = torch.zeros((), dtype=torch.float64, device=device) + deploy_loss_sum = torch.zeros((), dtype=torch.float64, device=device) + for micro in range(config.training.grad_accumulation): + batch, metadata = next(iterator) + batch = batch.to(device, non_blocking=True) + last_backward = micro == config.training.grad_accumulation - 1 + stage.set_requires_gradient_sync(last_backward) + stage.set_is_last_backward(last_backward) + fixed_noise = fixed_tau = None + if config.runtime.phase == "overfit64": + if not isinstance(sampler, Overfit64Sampler): + raise RuntimeError("overfit64 phase requires Overfit64Sampler") + position = int(sampler.state_dict()["consumed"]) + per_rank_windows = len(sampler.indices) // world_size + if per_rank_windows * world_size != len(sampler.indices): + raise RuntimeError("overfit64 windows must divide evenly across ranks") + visits = [ + (position + sample_index) // per_rank_windows + for sample_index in range(len(metadata)) + ] + fixed_noise = _fixed_overfit_noise(metadata, batch.action_gt.shape, device) + fixed_tau = _fixed_overfit_tau(metadata, visits, device) + with torch.autocast("cuda", dtype=torch.bfloat16): + result = stage(batch, noise=fixed_noise, tau=fixed_tau) + loss = result["loss"] / config.training.grad_accumulation + loss.backward() + loss_sum += result["loss"].detach().double() / config.training.grad_accumulation + uniform_loss_sum += result["loss_uniform"].double() / config.training.grad_accumulation + deploy_loss_sum += result["loss_deploy"].double() / config.training.grad_accumulation + tau_sum += result["tau"].detach().double().mean() / config.training.grad_accumulation + assert batch.future_source is not None + source_counts += torch.bincount(batch.future_source, minlength=3) + source_ids = { + "expert_regular": 0, + "exact_cold": 1, + "expert_critical": 2, + } + for item in metadata: + sample_source_counts[source_ids.get(str(item.get("sample_source")), 0)] += 1 + if config.training.protocol in SHORT_HISTORY_ACTION_PROTOCOLS: + history = int(item["history_length"]) + history_counts[(1, 3, 6, 10).index(history)] += 1 + for source_id in (0, 1, 2): + selected_source = batch.future_source == source_id + source_loss_sums[source_id] += ( + result["per_sample_mse"][selected_source].detach().sum().double() + ) + sampler.mark_consumed(config.training.micro_batch_per_gpu) + interval_samples += config.training.micro_batch_per_gpu + grad_groups, missing_grad = _full_grad_report(stage) + if step == start and missing_grad: + # A parameter can be structurally inactive only if the design is wrong; hard fail at the first gate step. + raise RuntimeError(f"trainable parameters without gradients: {missing_grad[:20]}") + grad_norm = torch.nn.utils.clip_grad_norm_(stage.parameters(), config.training.grad_clip) + if not torch.isfinite(grad_norm): + raise FloatingPointError("non-finite Action gradient norm") + optimizer.step() + scheduler.step() + ema.step() + completed = step + 1 + should_log = completed <= 5 or completed % config.training.log_every == 0 or completed == total + if should_log: + dist.all_reduce(loss_sum) + dist.all_reduce(tau_sum) + dist.all_reduce(source_counts) + dist.all_reduce(history_counts) + dist.all_reduce(source_loss_sums) + dist.all_reduce(sample_source_counts) + dist.all_reduce(uniform_loss_sum) + dist.all_reduce(deploy_loss_sum) + elapsed = max(time.monotonic() - interval_start, 1.0e-6) + last_metrics = { + "step": completed, + "phase": config.runtime.phase, + "train/loss_action": float(loss_sum / world_size), + "train/loss_uniform": float(uniform_loss_sum / world_size), + "train/loss_deploy_weighted": float(deploy_loss_sum / world_size), + "train/tau_mean": float(tau_sum / world_size), + "train/grad_norm": float(grad_norm), + "train/grad_norm_transition": grad_groups.get("transition", 0.0), + "train/grad_norm_action": grad_groups.get("action", 0.0), + "train/lr": float(optimizer.param_groups[0]["lr"]), + "train/future_gt_count": int(source_counts[0]), + "train/future_pred_count": int(source_counts[1]), + "train/future_exact_cold_count": int(source_counts[2]), + "train/history_h1_count": int(history_counts[0]), + "train/history_h3_count": int(history_counts[1]), + "train/history_h6_count": int(history_counts[2]), + "train/history_h10_count": int(history_counts[3]), + "train/source_regular_count": int(sample_source_counts[0]), + "train/source_exact_cold_count": int(sample_source_counts[1]), + "train/source_critical_count": int(sample_source_counts[2]), + "train/gt_loss": float( + source_loss_sums[0] / source_counts[0].clamp_min(1) + ), + "train/predicted_loss": float( + source_loss_sums[1] / source_counts[1].clamp_min(1) + ), + "train/exact_cold_loss": float( + source_loss_sums[2] / source_counts[2].clamp_min(1) + ), + "train/future_pred_expected_p": predicted_probability( + step, + compressed_total=total if config.runtime.phase == "canary" else None, + curriculum=None if config.runtime.phase == "canary" else curriculum, + ), + "performance/samples_per_second": interval_samples * world_size / elapsed, + "performance/gpu_peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "parameter_report": parameter_report if completed == 1 else None, + "initialization_sha256": initialization_hash if completed == 1 else None, + "initialization_checkpoint_fingerprint": ( + initialization_load["checkpoint_fingerprint"] + if completed == 1 and initialization_load is not None + else None + ), + } + if config.training.protocol in SHORT_HISTORY_ACTION_PROTOCOLS: + if config.training.protocol in EVAL_ALIGNED_ACTION_PROTOCOLS: + expected_per_history = config.training.global_batch // 4 + if history_counts.tolist() != [expected_per_history] * 4: + raise RuntimeError( + f"Action-v12 history allocation drifted: {history_counts.tolist()}" + ) + else: + short = history_counts[1:].tolist() + if int(history_counts[0]) != 256 or sum(short) != 256 or max(short) - min(short) > 1: + raise RuntimeError(f"Action-v10 history allocation drifted: {history_counts.tolist()}") + if rank == 0: + _write_metric(metrics_path, last_metrics) + LOGGER.info( + "step=%d loss=%.6f grad=%.3f pred=%d/%d samples/s=%.1f peak=%.1fGiB", + completed, + last_metrics["train/loss_action"], + last_metrics["train/grad_norm"], + last_metrics["train/future_pred_count"], + int(source_counts.sum()), + last_metrics["performance/samples_per_second"], + last_metrics["performance/gpu_peak_allocated_gib"], + ) + try: + tracker.log( + {k: v for k, v in last_metrics.items() if isinstance(v, (int, float))}, + step=completed, + ) + except Exception as error: + LOGGER.warning("SwanLab train upload failed: %s", error) + interval_start = time.monotonic() + interval_samples = 0 + if completed % 1000 == 0 or completed == total: + current_frozen = _frozen_hash(stage) + if current_frozen != frozen_initial: + frozen_verified = False + raise RuntimeError("frozen World State Encoder hash changed") + if rank == 0: + write_json_atomic( + output / "frozen_audits" / f"step-{completed:06d}.json", + { + "step": completed, + "passed": True, + "rank_hashes_at_start": frozen_hashes, + "rank0_current_hash": current_frozen, + "source_sha256": config.artifacts.state_encoder_ema_sha256, + }, + ) + light_due = ( + config.validation.enabled + and config.runtime.phase != "overfit64" + and completed % config.training.light_val_every == 0 + ) + full_due = ( + config.validation.enabled + and config.runtime.phase != "overfit64" + and (completed % config.training.full_val_every == 0 or completed == total) + ) + quick_due = ( + config.validation.quick_enabled + and config.runtime.phase != "overfit64" + and (completed % config.validation.quick_every == 0 or completed == total) + ) + if light_due or full_due: + if val_dataset is None: + raise RuntimeError("validation is enabled but the validation dataset is unavailable") + online, online_cases = _validate( + stage, + val_dataset, + config, + device=device, + rank=rank, + world_size=world_size, + completed=completed, + branch="online", + full=full_due, + output=output, + ) + ema_metrics, ema_cases = ({}, []) + if config.training.protocol not in SHORT_HISTORY_ACTION_PROTOCOLS: + with ema.average_parameters(): + ema_metrics, ema_cases = _validate( + stage, + val_dataset, + config, + device=device, + rank=rank, + world_size=world_size, + completed=completed, + branch="ema", + full=full_due, + output=output, + ) + validation = {"step": completed, **online, **ema_metrics} + if rank == 0: + _write_metric(output / "validation_metrics.jsonl", validation) + # Validation is uploaded immediately after evaluation, as required for online monitoring. + try: + tracker.log( + {k: v for k, v in validation.items() if isinstance(v, (int, float))}, + step=completed, + ) + except Exception as error: + LOGGER.warning("SwanLab validation upload failed: %s", error) + if full_due: + try: + media = {} + for media_branch, paths in (("online", online_cases), ("ema", ema_cases)): + for case_index, path in enumerate(paths): + media[f"validation/cases/{media_branch}/case_{case_index:02d}"] = tracker.image( + path, + caption=f"step={completed} branch={media_branch} case={case_index}", + ) + if media: + tracker.log(media, step=completed) + except Exception as error: + LOGGER.warning("SwanLab validation case upload failed: %s", error) + if full_due and config.runtime.phase == "training": + selection_branch = "online" if config.training.protocol in SHORT_HISTORY_ACTION_PROTOCOLS else "ema" + candidate = validation[f"validation/{selection_branch}/predicted/sample_normalized_mse"] + if candidate < best_metric: + best_metric = candidate + write_json_atomic( + best_path, + { + "format_version": 1, + "step": completed, + "branch": selection_branch, + "selection_metric": "predicted_10_step_normalized_action_mse", + "predicted_ema_normalized_mse": candidate, + "checkpoint": f"action-checkpoint-{completed}", + }, + ) + _barrier() + if quick_due: + if val_dataset is None: + raise RuntimeError("quick validation is enabled but validation data is unavailable") + quick_branch = "online" if config.training.protocol in SHORT_HISTORY_ACTION_PROTOCOLS else "ema" + with ema.average_parameters(): + quick_metrics, quick_cases = _validate( + stage, + val_dataset, + config, + device=device, + rank=rank, + world_size=world_size, + completed=completed, + branch=quick_branch, + full=True, + output=output, + quick=True, + ) + cold_metrics, cold_cases = ( + _validate_exact_cold( + stage, + cold_val_dataset, + config, + device=device, + rank=rank, + world_size=world_size, + completed=completed, + output=output, + ) + if cold_val_dataset is not None + else ({}, []) + ) + validation = { + "step": completed, + "validation/mode": f"quick_{quick_branch}_512_plus_exact_cold128", + **quick_metrics, + **cold_metrics, + } + if rank == 0: + _write_metric(output / "validation_metrics.jsonl", validation) + try: + tracker.log( + {k: v for k, v in validation.items() if isinstance(v, (int, float))}, + step=completed, + ) + media = { + f"validation/cases/{quick_branch}/case_{case_index:02d}": tracker.image( + path, + caption=f"step={completed} branch={quick_branch} quick case={case_index}", + ) + for case_index, path in enumerate(quick_cases) + } + media.update( + { + f"validation/cases/ema_exact_cold/case_{case_index:02d}": tracker.image( + path, + caption=f"step={completed} branch=ema exact-cold case={case_index}", + ) + for case_index, path in enumerate(cold_cases) + } + ) + if media: + tracker.log(media, step=completed) + except Exception as error: + LOGGER.warning("SwanLab quick validation upload failed: %s", error) + candidate = validation[f"validation/{quick_branch}/predicted/sample_normalized_mse"] + if config.corrective is None and candidate < best_metric: + best_metric = candidate + write_json_atomic( + best_path, + { + "format_version": 1, + "step": completed, + "branch": quick_branch, + "selection_metric": "predicted_10_step_normalized_action_mse", + "selection_policy": "overall_accuracy_primary_smoothness_guardrails", + "predicted_ema_normalized_mse": candidate, + "checkpoint": f"action-checkpoint-{completed}", + }, + ) + _barrier() + overfit_due = config.runtime.phase == "overfit64" and ( + completed % 250 == 0 or completed == total + ) + if overfit_due: + overfit = _validate_overfit64( + stage, train_dataset, device=device, rank=rank, world_size=world_size + ) + overfit_report = { + "format_version": 1, + "passed": overfit["normalized_sampled_action_mse"] < 1.0e-3 + and overfit["nonfinite_count"] == 0, + "step": completed, + "windows": 64, + **overfit, + "threshold": 1.0e-3, + "initial_resume_step": initial_resume_step, + "recovery_round_trip_verified": recovery_round_trip_verified, + "source_identity": action_source_identity( + Path(__file__).resolve().parents[4] + )["sha256"], + } + if rank == 0: + _write_metric(output / "validation_metrics.jsonl", overfit_report) + try: + tracker.log( + { + "validation/overfit64_sampled_action_mse": overfit[ + "normalized_sampled_action_mse" + ], + "validation/overfit64_nonfinite_count": overfit[ + "nonfinite_count" + ], + }, + step=completed, + ) + except Exception as error: + LOGGER.warning("SwanLab overfit validation upload failed: %s", error) + overfit_passed = bool(overfit_report["passed"]) + if completed == total and not overfit_passed: + raise RuntimeError(f"overfit64 gate failed: {overfit_report}") + recovery_gate_due = ( + config.runtime.phase in {"canary", "overfit64"} + and completed == recovery_gate_step + ) + save_due = ( + completed % config.training.save_every == 0 + or completed in config.checkpoint.preserve_steps + or completed == total + or requested_stop + or overfit_passed + or recovery_gate_due + ) + if config.runtime.phase == "canary": + save_due = completed in {250, total} or requested_stop or recovery_gate_due + if save_due: + saved = save_checkpoint( + output, + completed_steps=completed, + model=stage, + optimizer=optimizer, + scheduler=scheduler, + ema=ema, + sampler=sampler, + resolved_config=config.model_dump(mode="json"), + artifact_identity=identity, + metrics=last_metrics, + keep_recent=config.checkpoint.keep_last_recovery, + ) + if recovery_gate_due and not requested_stop: + # The per-rank RNG snapshot is taken near the end of + # save_checkpoint, so fingerprint the exact post-save state + # that recovery is required to reproduce. + recovery_fingerprint = _runtime_fingerprint( + stage, optimizer, scheduler, ema, sampler + ) + resumed = load_checkpoint( + saved, + model=stage, + optimizer=optimizer, + scheduler=scheduler, + ema=ema, + sampler=sampler, + expected_artifact_identity=identity, + ) + if resumed != completed: + raise RuntimeError("canary in-place recovery returned the wrong next step") + # Discard all prefetched indices and recreate the iterator from the + # restored sampler cursor, exactly as a new process would. + del iterator + iterator = iter(loader) + recovered_fingerprint = _runtime_fingerprint( + stage, optimizer, scheduler, ema, sampler + ) + local_match = torch.tensor( + int(recovery_fingerprint == recovered_fingerprint), + dtype=torch.int64, + device=device, + ) + dist.all_reduce(local_match, op=dist.ReduceOp.MIN) + recovery_round_trip_verified = bool(local_match.item()) + if not recovery_round_trip_verified: + raise RuntimeError("checkpoint recovery round-trip changed runtime state") + if rank == 0: + LOGGER.info("checkpoint recovery round-trip verified at step %d", completed) + if config.runtime.phase == "overfit64" and overfit_passed: + overfit_report["recovery_round_trip_verified"] = recovery_round_trip_verified + overfit_report["passed"] = bool( + overfit_report["passed"] and recovery_round_trip_verified + ) + if rank == 0: + write_json_atomic( + Path(config.experiment.artifact_root) / "reports" / "overfit64.json", + overfit_report, + ) + if not overfit_report["passed"]: + raise RuntimeError(f"overfit64 recovery gate failed: {overfit_report}") + if config.runtime.phase == "canary" and completed == total: + sampler_positions: list[int | None] = [None] * world_size + dist.all_gather_object(sampler_positions, int(sampler.state_dict()["consumed"])) + expected_consumed = completed * config.training.micro_batch_per_gpu * config.training.grad_accumulation + predicted_loss = float(last_metrics.get("train/predicted_loss", 0.0)) + gt_loss = float(last_metrics.get("train/gt_loss", 0.0)) + ratio = predicted_loss / max(gt_loss, 1.0e-12) + canary_report = { + "format_version": 1, + "passed": recovery_round_trip_verified + and frozen_verified + and all(position == expected_consumed for position in sampler_positions) + and math.isfinite(float(last_metrics.get("train/loss_action", math.nan))) + and ratio < 100.0, + "step": completed, + "recovery_round_trip_verified": recovery_round_trip_verified, + "frozen_hash_verified": frozen_verified, + "sampler_positions": sampler_positions, + "expected_sampler_position_per_rank": expected_consumed, + "predicted_to_gt_loss_ratio": ratio, + "samples_per_second": last_metrics.get("performance/samples_per_second"), + "peak_allocated_gib": last_metrics.get("performance/gpu_peak_allocated_gib"), + "source_identity": action_source_identity( + Path(__file__).resolve().parents[4] + )["sha256"], + "initialization_rank_hashes": initialization_hashes, + } + canary_report["identity_sha256"] = canonical_sha256(canary_report) + if rank == 0: + write_json_atomic( + Path(config.experiment.artifact_root) / "reports" / "canary.json", + canary_report, + ) + if not canary_report["passed"]: + raise RuntimeError(f"distributed canary gate failed: {canary_report}") + if overfit_passed: + if rank == 0: + LOGGER.info("overfit64 gate passed at step %d", completed) + break + if requested_stop: + if rank == 0: + LOGGER.warning("graceful stop requested after checkpoint step %d", completed) + break + finally: + try: + tracker.finish() + except Exception as error: + LOGGER.warning("SwanLab finish failed: %s", error) + _barrier() + if dist.is_initialized(): + dist.destroy_process_group() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", required=True) + args = parser.parse_args() + train(load_config(args.config)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/bihub_checkpoint.py b/release-20261107/source/workspace_joint/mira/src/mira/training/bihub_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..8ed72cc2be1a9e8820310ef4550de9ceda628629 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/bihub_checkpoint.py @@ -0,0 +1,159 @@ +"""Atomic FSDP2/DCP checkpoints for the continuous Stage-W lineage.""" + +from __future__ import annotations + +import json +import os +import random +import shutil +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import torch.distributed as dist +import torch.distributed.checkpoint as dcp +from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner +from torch.distributed.checkpoint.state_dict import get_state_dict, set_state_dict + +from mira.training.ema import ModelEMA + + +def latest_checkpoint(output_dir: str | Path) -> Path | None: + candidates = [] + for path in Path(output_dir).glob("checkpoint-*"): + if not path.is_dir() or not (path / "trainer_state.json").is_file(): + continue + try: + step = int(path.name.split("-", 1)[1]) + except ValueError: + continue + candidates.append((step, path)) + return max(candidates, default=(None, None))[1] + + +def _barrier() -> None: + if dist.is_available() and dist.is_initialized(): + dist.barrier() + + +def save_bihub_checkpoint( + output_dir: str | Path, + *, + completed_steps: int, + model: torch.nn.Module, + optimizer: torch.optim.Optimizer, + scheduler: Any, + ema: ModelEMA, + sampler: Any, + resolved_config: dict[str, Any], + metrics: dict[str, Any], + permanent_name: str | None = None, + keep_recent: int = 2, +) -> Path: + """All ranks must call this function.""" + rank = dist.get_rank() if dist.is_initialized() else 0 + root = Path(output_dir) + final = root / (permanent_name or f"checkpoint-{completed_steps}") + temporary = root / f".{final.name}.tmp" + if rank == 0: + root.mkdir(parents=True, exist_ok=True) + if temporary.exists(): + shutil.rmtree(temporary) + temporary.mkdir(parents=True) + _barrier() + + model_state, optimizer_state = get_state_dict(model, optimizer) + distributed_state = { + "model": model_state, + "optimizer": optimizer_state, + "ema": ema.state_dict(), + } + dcp.save(distributed_state, checkpoint_id=temporary / "distributed") + rank_state = { + "scheduler": scheduler.state_dict(), + "sampler": sampler.state_dict(), + "python_rng": random.getstate(), + "numpy_rng": np.random.get_state(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state() if torch.cuda.is_available() else None, + } + torch.save(rank_state, temporary / f"rank-{rank:05d}.pth") + _barrier() + if rank == 0: + state = { + "format_version": 1, + "completed_steps": completed_steps, + "next_step": completed_steps, + "stage": "single_view" if completed_steps < int(resolved_config["training"]["single_view_steps"]) else "full_bihub", + "action_head_instantiated": False, + "resolved_config": resolved_config, + "metrics": metrics, + } + (temporary / "trainer_state.json").write_text( + json.dumps(state, indent=2, default=str) + "\n", encoding="utf-8" + ) + if final.exists(): + shutil.rmtree(final) + os.replace(temporary, final) + if permanent_name is None: + checkpoints = sorted( + ( + (int(path.name.split("-", 1)[1]), path) + for path in root.glob("checkpoint-*") + if path.is_dir() and path.name.split("-", 1)[1].isdigit() + ), + key=lambda item: item[0], + ) + for _, old in checkpoints[:-keep_recent]: + shutil.rmtree(old) + _barrier() + return final + + +def load_bihub_checkpoint( + checkpoint: str | Path, + *, + model: torch.nn.Module, + optimizer: torch.optim.Optimizer, + scheduler: Any, + ema: ModelEMA, + sampler: Any, +) -> int: + rank = dist.get_rank() if dist.is_initialized() else 0 + checkpoint = Path(checkpoint) + metadata = json.loads((checkpoint / "trainer_state.json").read_text(encoding="utf-8")) + model_state, optimizer_state = get_state_dict(model, optimizer) + model_and_ema_state = { + "model": model_state, + "ema": ema.state_dict(), + } + # Model and EMA are a strict lineage contract. Optimizer state is different: AdamW allocates + # moments lazily, so a trainable parameter that was intentionally unused (e.g. action BOS when + # action history is disabled) legitimately has no entry in the checkpoint even though the + # fresh optimizer state template contains a placeholder. Isolate the partial policy to the + # optimizer subtree so it cannot hide missing model/EMA weights. + dcp.load(model_and_ema_state, checkpoint_id=checkpoint / "distributed") + optimizer_only_state = {"optimizer": optimizer_state} + dcp.load( + optimizer_only_state, + checkpoint_id=checkpoint / "distributed", + planner=DefaultLoadPlanner(allow_partial_load=True), + ) + set_state_dict( + model, + optimizer, + model_state_dict=model_and_ema_state["model"], + optim_state_dict=optimizer_only_state["optimizer"], + ) + ema.load_state_dict(model_and_ema_state["ema"]) + rank_state = torch.load(checkpoint / f"rank-{rank:05d}.pth", map_location="cpu", weights_only=False) + scheduler.load_state_dict(rank_state["scheduler"]) + sampler.load_state_dict(rank_state["sampler"]) + random.setstate(rank_state["python_rng"]) + np.random.set_state(rank_state["numpy_rng"]) + torch.set_rng_state(rank_state["torch_rng"]) + if torch.cuda.is_available() and rank_state["cuda_rng"] is not None: + torch.cuda.set_rng_state(rank_state["cuda_rng"]) + _barrier() + return int(metadata["next_step"]) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/checkpoint_manager.py b/release-20261107/source/workspace_joint/mira/src/mira/training/checkpoint_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..e515e8ab202059a60c9ff58affd0c6e8da1c44a9 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/checkpoint_manager.py @@ -0,0 +1,192 @@ +"""Checkpoint saving, retention, EMA-weight swapping, and resume.""" + +from __future__ import annotations + +import logging +import os +import shutil +from pathlib import Path +from typing import Any, Protocol + +import torch +from torch import nn + +from .checkpoints import resolve_checkpoint +from .ema import ModelEMA +from .tracker import periodic_event + +logger = logging.getLogger(__name__) + + +class _StatefulComponent(Protocol): + def state_dict(self) -> dict[str, Any]: ... + # `object` to ignore the return type since nn.Module and optimizers/schedulers return different things. + def load_state_dict(self, state_dict: dict[str, Any]) -> object: ... + + +class CheckpointManager: + """Manages checkpoint saving, retention, EMA weight swapping, and resume. + + The model is saved with EMA weights swapped in (for downstream eval), while ``training_state.pth`` + holds the raw per-component state needed to resume training exactly via :meth:`continue_from`. + """ + + def __init__( + self, + model: nn.Module, + checkpoint_dir: str | Path, + *, + save_every: int | str = -1, + keep_recent: int = 1, + keep_permanent_every: int | str = -1, + total_steps: int | None = None, + model_ema_decay: float = 0.0, # 0.0 for no EMA, otherwise the decay rate for the EMA model + ): + self.checkpoint_dir = Path(checkpoint_dir) + self.checkpoint_dir.mkdir(parents=True, exist_ok=True) + self.save_every = save_every + self.keep_recent = keep_recent + self.keep_permanent_every = keep_permanent_every + self.total_steps = total_steps + + self.model_ema = ModelEMA(model, decay=model_ema_decay) + self._components: dict[str, _StatefulComponent] = {} + self.register({"model": model, "model_ema": self.model_ema}) + + self.recent_checkpoints: list[tuple[int, Path]] = self._discover_existing_checkpoints() + + def register(self, components: dict[str, _StatefulComponent]) -> None: + """Register named stateful components (each with state_dict/load_state_dict). + + These are saved into ``training_state.pth`` and restored on :meth:`continue_from`. + """ + for name, component in components.items(): + if name in self._components: + raise ValueError(f"Component {name!r} already registered") + self._components[name] = component + + def _discover_existing_checkpoints(self) -> list[tuple[int, Path]]: + """Find any checkpoint-* dirs already in checkpoint_dir, sorted by step. + + Lets retention bookkeeping survive a resume into the same directory. + """ + found: list[tuple[int, Path]] = [] + for p in self.checkpoint_dir.glob("checkpoint-*"): + if not p.is_dir(): + continue + try: + step = int(p.name.split("-", 1)[1]) + except (IndexError, ValueError): + continue + found.append((step, p)) + found.sort(key=lambda x: x[0]) + return found + + def _should_save(self, step: int) -> bool: + return self.save_every != -1 and periodic_event(step, self.save_every, self.total_steps) + + def _is_permanent(self, step: int) -> bool: + if self.keep_permanent_every == -1: + return False + return periodic_event(step, self.keep_permanent_every, self.total_steps) + + @property + def latest_checkpoint(self) -> Path | None: + if len(self.recent_checkpoints) == 0: + return None + return self.recent_checkpoints[-1][1] / "checkpoint.pth" + + def finetune_from(self, checkpoint: str | Path) -> dict[str, Any]: + """Load *only* the model weights from a checkpoint, for fine-tuning. + + Unlike :meth:`continue_from`, this restores neither optimizer/scheduler state nor the step + counter: training starts fresh at step 0 from these weights. + + Returns: + The extra data dict saved in the checkpoint (if any), excluding the model weights. + """ + src = resolve_checkpoint(checkpoint) + logger.info(f"Fine-tuning: loading model weights from {src}") + ckpt = torch.load(src, map_location="cpu", weights_only=False) + # Defers to the model's own load_state_dict (strict for the codec). The multiplayer world + # model overrides it to load single-player weights, remapping keys and dropping mismatched + # shapes; that remap lives in the model, not here. + self._components["model"].load_state_dict(ckpt["state_dict"]) + return {k: v for k, v in ckpt.items() if k != "state_dict"} + + def continue_from(self, checkpoint: str | Path) -> int: + """Load every registered component from ``checkpoint`` (transparent crash recovery). + + ``checkpoint`` may point at a ``checkpoint.pth``, a ``checkpoint-{step}/`` dir, an output + dir (latest is picked), or a W&B run URL. Returns the step at which the training loop should + begin (``saved_step + 1``). + """ + src = resolve_checkpoint(checkpoint).parent + + state_path = src / "training_state.pth" + if not state_path.is_file(): + raise FileNotFoundError(f"No training_state.pth in {src}") + logger.info(f"Loading training state from {state_path}") + state = torch.load(state_path, map_location="cpu", weights_only=False) + + for name, comp in self._components.items(): + if name in state: + comp.load_state_dict(state[name]) + else: + logger.warning(f"Component {name!r} missing from checkpoint; using current state") + start_step = int(state["step"]) + 1 + logger.info(f"Continuing from {src} at step {state['step']} (next step {start_step})") + return start_step + + def maybe_save_checkpoint( + self, + step: int, + extra_data: dict[str, Any] | None = None, + final: bool = False, + ) -> None: + """Save a checkpoint and apply the retention policy.""" + if not self._should_save(step) and not final: + return None + + extra_data = dict(extra_data or {}) + ckpt_dir = self.checkpoint_dir / f"checkpoint-{step}" + # Write into a sibling temp dir and atomically rename into place, so a crash mid-save never + # leaves a partial `checkpoint-{step}/` for auto-resume to pick up as the latest checkpoint. + tmp_dir = self.checkpoint_dir / f".checkpoint-{step}.tmp" + if tmp_dir.exists(): + shutil.rmtree(tmp_dir) + tmp_dir.mkdir(parents=True) + logger.info(f"Saving checkpoint {ckpt_dir}") + + # Save model checkpoint (with EMA weights if available, for downstream eval). + model = self._components["model"] + with self.model_ema.average_parameters(): + model.save_checkpoint(tmp_dir / "checkpoint.pth", extra_data) # type: ignore[attr-defined] + + # Save training state: per-component state_dicts, plus the step. + training_state: dict[str, Any] = {name: comp.state_dict() for name, comp in self._components.items()} + training_state["step"] = step + torch.save(training_state, tmp_dir / "training_state.pth") + + if ckpt_dir.exists(): # a re-save at the same step (e.g. final == last periodic step) + shutil.rmtree(ckpt_dir) + os.replace(tmp_dir, ckpt_dir) + + self.recent_checkpoints.append((step, ckpt_dir)) + + # Temporary (non-permanent) checkpoints are eligible for deletion. + temp_checkpoints = [ + idx for idx, (s, _) in enumerate(self.recent_checkpoints) if not self._is_permanent(s) + ] + if final: + # For the final checkpoint, clean up all remaining temporary checkpoints. + for idx in temp_checkpoints: + # Sanity check: don't overwrite the final checkpoint. + if (old_checkpoint := self.recent_checkpoints[idx][1]) != ckpt_dir: + shutil.rmtree(old_checkpoint) + elif len(temp_checkpoints) > self.keep_recent: + # Otherwise retain `keep_recent` temporary checkpoints. + old_idx = temp_checkpoints[0] + old_checkpoint = self.recent_checkpoints[old_idx][1] + self.recent_checkpoints.pop(old_idx) + shutil.rmtree(old_checkpoint) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/checkpoints.py b/release-20261107/source/workspace_joint/mira/src/mira/training/checkpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..535e60deb990bb99777d51e0a0f5fd77c7532882 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/checkpoints.py @@ -0,0 +1,104 @@ +"""Resolving checkpoint paths (local or W&B run URL) and re-attaching W&B runs on resume.""" + +from __future__ import annotations + +import logging +import re +from pathlib import Path + +_WANDB_URL_RE = re.compile(r"https://wandb\.ai/([^/]+)/([^/]+)/runs/([^/]+)") + +logger = logging.getLogger(__name__) + + +def wandb_run_id_from_url(checkpoint: str | Path) -> str | None: + """Return the W&B run id if ``checkpoint`` is a W&B run URL, else None. + + Used to re-attach training to the original W&B run when resuming/continuing from it, so its + history stays in one continuous run. + """ + match = _WANDB_URL_RE.match(str(checkpoint)) + return match.group(3) if match else None + + +def resume_wandb_run_id(continue_from: str | Path | None, output_dir: str | Path) -> str | None: + """W&B run id to re-attach to when resuming into ``output_dir``, or None to start fresh. + + So crash recovery / auto-resume continues the *same* W&B run rather than opening a new one: + - a W&B-URL ``continue_from`` carries the id directly; + - a local ``continue_from`` reads the ``wandb_run_id.txt`` sidecar in the source run's dir; + - otherwise (auto-resume into the same output_dir), read the sidecar there. + + Keying off the sidecar means a *crashed fine-tune* (which wrote one on its first launch) + re-attaches on resubmit, while a brand-new run (no sidecar yet) gets a fresh run. + """ + if continue_from: + run_id = wandb_run_id_from_url(continue_from) + if run_id is not None: + return run_id + try: + source_output_dir = resolve_checkpoint(continue_from).parent.parent + except (FileNotFoundError, ValueError): + source_output_dir = None + if source_output_dir is not None: + sidecar = source_output_dir / "wandb_run_id.txt" + if sidecar.is_file(): + return sidecar.read_text(encoding="utf-8").strip() + + sidecar = Path(output_dir) / "wandb_run_id.txt" + if sidecar.is_file(): + return sidecar.read_text(encoding="utf-8").strip() + return None + + +def _find_latest_checkpoint(output_dir: Path) -> Path: + """Find the latest ``checkpoint-{step}/checkpoint.pth`` in an output directory.""" + checkpoint_dirs = sorted( + output_dir.glob("checkpoint-*/checkpoint.pth"), + key=lambda p: int(p.parent.name.split("-")[1]), + ) + if not checkpoint_dirs: + raise FileNotFoundError(f"No checkpoints found in {output_dir}") + checkpoint_path = checkpoint_dirs[-1] + logger.info(f"Resolved to latest checkpoint: {checkpoint_path}") + return checkpoint_path + + +def resolve_checkpoint(checkpoint: str | Path) -> Path: + """Resolve a checkpoint path from a local path or W&B run URL. + + Accepts: + - A direct path to a ``checkpoint.pth`` file. + - A checkpoint directory (``checkpoint-{step}/``) containing ``checkpoint.pth``. + - An output directory containing ``checkpoint-{step}/`` subdirectories (picks latest). + - A W&B run URL like ``https://wandb.ai/entity/project/runs/run_id/overview``. + """ + if not isinstance(checkpoint, Path): + # First check if it's a W&B URL; if so, resolve to the run's output_dir. + match = _WANDB_URL_RE.match(checkpoint) + if match: + entity, project, run_id = match.groups() + + import wandb # noqa: PLC0415 -- optional dep, used only for W&B-URL checkpoints + + api = wandb.Api() + run = api.run(f"{entity}/{project}/{run_id}") + output_dir = Path(run.config["run"]["output_dir"]) + logger.info(f"W&B run output_dir for {checkpoint}: {output_dir}") + return _find_latest_checkpoint(output_dir) + + path = Path(checkpoint) + else: + # A Path is always local. + path = checkpoint + + # Direct path to a .pth file. + if path.suffix == ".pth": + return path + + # A checkpoint-{step} dir containing checkpoint.pth. + if (path / "checkpoint.pth").is_file(): + return path / "checkpoint.pth" + + # An output dir containing checkpoint-{step}/ subdirectories. + return _find_latest_checkpoint(path) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/distributed.py b/release-20261107/source/workspace_joint/mira/src/mira/training/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..5796ba869580d2551315b1d6e451791fc80aa689 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/distributed.py @@ -0,0 +1,64 @@ +"""Distributed-training setup, single-GPU safe. + +``get_distributed_settings`` reports ``(device, rank, world_size)``, defaulting to the single-process +``(0, 0, 1)`` when ``torch.distributed`` is not initialized. ``set_up_distributed`` initializes the +process group from the ``torchrun`` environment when present, and otherwise no-ops so the +trainers and tests run without ``torchrun``. +""" + +from __future__ import annotations + +import os + +import torch +from pydantic import BaseModel + + +class DistributedSettings(BaseModel): + device: int + rank: int + world_size: int + + @property + def is_main_process(self) -> bool: + return self.rank == 0 + + +def get_distributed_settings() -> DistributedSettings: + """Current ``(device, rank, world_size)``; ``(0, 0, 1)`` when not running distributed.""" + if torch.distributed.is_available() and torch.distributed.is_initialized(): + rank = torch.distributed.get_rank() + world_size = torch.distributed.get_world_size() + else: + rank = 0 + world_size = 1 + + if torch.accelerator.device_count() == 0: + # CPU-only machine - still useful for tests. + device = 0 + else: + assert rank < torch.accelerator.device_count() * world_size + device = rank % torch.accelerator.device_count() + + return DistributedSettings(device=device, rank=rank, world_size=world_size) + + +def set_up_distributed() -> DistributedSettings: + """Initialize the process group from the ``torchrun`` env, or no-op for single-process runs. + + When ``LOCAL_RANK`` is set (i.e. launched under ``torchrun``) and an accelerator is available, + this selects the local device and initializes the default process group. Without ``LOCAL_RANK``, + or with no accelerator, it leaves ``torch.distributed`` uninitialized and just reports the + single-process settings, so scripts run unchanged on a single GPU or on CPU. + """ + local_rank = os.environ.get("LOCAL_RANK") + if local_rank is None or torch.accelerator.device_count() == 0: + return get_distributed_settings() + + torch.accelerator.set_device_index(int(local_rank)) + backend = torch.distributed.get_default_backend_for_device( + torch.accelerator.current_accelerator(), # type: ignore[arg-type] + ) + torch.distributed.init_process_group(backend, device_id=int(local_rank)) + + return get_distributed_settings() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/ema.py b/release-20261107/source/workspace_joint/mira/src/mira/training/ema.py new file mode 100644 index 0000000000000000000000000000000000000000..7187520e95bdebda6c7f1f129d62d60ef2cd38c8 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/ema.py @@ -0,0 +1,116 @@ +"""Exponential moving averages used during training. + +:class:`ModelEMA` tracks an EMA of a model's floating-point parameters and can temporarily swap them +in for evaluation/checkpointing via :meth:`ModelEMA.average_parameters`. :class:`DistributedEMA` +tracks an EMA of a scalar (e.g. the latent mean/std) and averages it across ranks on ``compute``. +""" + +from __future__ import annotations + +from contextlib import contextmanager +from typing import Any, Iterator + +import torch +import torch.distributed as dist +import torch.nn as nn +from torch import Tensor + + +class ModelEMA: + """Exponential moving average over model parameters. + + Only tracks floating-point parameters with ``requires_grad=True``. Supports bias correction + (``unbias=True``) for early-training stability. + + Can be disabled with ``decay=0.0``, which is useful so you don't have to add extra ``if``s in + the training loop when you want to turn off EMA. + """ + + def __init__(self, model: nn.Module, decay: float = 0.9998, unbias: bool = True): + self.decay = decay + self.unbias = unbias + self.model = model + self.state: dict[str, torch.Tensor] = {} + self.count: float = 0.0 + # State tensors are cloned on each parameter's current device; construct this EMA *after* + # moving the model to its training device, or step() will hit a device mismatch. + if decay != 0.0: + for name, param in model.named_parameters(): + if param.requires_grad and param.is_floating_point(): + self.state[name] = param.data.detach().clone() + + @torch.no_grad() + def step(self) -> None: + if self.decay == 0.0: # decay=0.0 disables EMA + return + + if self.unbias: + self.count = self.count * self.decay + 1 + w = 1.0 / self.count + else: + w = 1.0 - self.decay + + for name, param in self.model.named_parameters(): + if name not in self.state: + continue + self.state[name].mul_(1 - w).add_(param.data.detach(), alpha=w) + + @contextmanager + def average_parameters(self) -> Iterator[None]: + """Temporarily swap model parameters with EMA values.""" + if self.decay == 0.0: # decay=0.0 disables EMA + yield + return + + original: dict[str, torch.Tensor] = {} + try: + for name, param in self.model.named_parameters(): + if name in self.state: + original[name] = param.data.detach().clone() + param.data.copy_(self.state[name]) + yield + finally: + for name, param in self.model.named_parameters(): + if name in original: + param.data.copy_(original[name]) + + def state_dict(self) -> dict[str, Any]: + return {"state": self.state, "count": self.count} + + def load_state_dict(self, state_dict: dict[str, Any]) -> None: + self.count = state_dict["count"] + for name, val in state_dict["state"].items(): + if name in self.state: + self.state[name].copy_(val) + + +class DistributedEMA(nn.Module): + """Exponential moving average of a scalar, averaged across distributed ranks on ``compute``.""" + + _ema: Tensor + + def __init__(self, decay: float, initial_value: float = 0.0, device: str | int | torch.device = "cpu"): + super().__init__() + self.decay = decay + # Defaults to CPU; pass the training device when ``update`` will be fed CUDA tensors, else the + # `_ema * decay + batch_mean` below hits a device mismatch. + self.register_buffer("_ema", torch.tensor(initial_value, dtype=torch.double, device=device)) + + def update(self, values: Tensor) -> None: + """Update EMA with the mean of ``values`` (local to this rank).""" + batch_mean = values.detach().to(dtype=torch.double).mean() + self._ema = self.decay * self._ema + (1 - self.decay) * batch_mean + + def all_reduce(self) -> None: + """Average the EMA in-place across ranks.""" + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(self._ema, op=dist.ReduceOp.AVG) + + def compute(self) -> float: + """Average the EMA across ranks and return the value.""" + self.all_reduce() + return self._ema.item() + + @property + def value(self) -> float: + return self._ema.item() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/lr_schedule.py b/release-20261107/source/workspace_joint/mira/src/mira/training/lr_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..c551088c5723397ebb127689e81354a962b673fd --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/lr_schedule.py @@ -0,0 +1,62 @@ +"""Learning-rate schedule used by the trainers.""" + +from __future__ import annotations + +import math + +import torch +from torch.optim.lr_scheduler import LRScheduler + + +class WarmupConstantCosineDecayLR(LRScheduler): + """Linear warmup, then a constant plateau, then optional cosine decay to ``min_lr``. + + Set ``decay_steps=0`` to disable the decay phase (the LR stays at ``base_lr`` after warmup + + constant). After the decay phase completes the LR stays at ``min_lr``. + """ + + def __init__( + self, + optimizer: torch.optim.Optimizer, + warmup_steps: int, + constant_steps: int, + decay_steps: int, # Set to 0 to disable decay phase + min_lr: float, + last_epoch: int = -1, + ): + self.warmup_steps = warmup_steps + self.constant_steps = constant_steps + self.decay_steps = decay_steps + + self.min_lr = min_lr + + assert self.warmup_steps >= 0 + assert self.constant_steps >= 0 + assert self.decay_steps >= 0 + assert self.min_lr >= 0 + + super().__init__(optimizer, last_epoch) + + def get_lr(self): # type: ignore[override] # noqa: ANN201 -- base stub annotates -> float + step = self.last_epoch + + if step < self.warmup_steps: + # Linear warmup + return [base_lr * step / self.warmup_steps for base_lr in self.base_lrs] + elif step >= self.warmup_steps and step < self.warmup_steps + self.constant_steps: + # Constant phase + return self.base_lrs + elif ( + step >= self.warmup_steps + self.constant_steps + and step < self.warmup_steps + self.constant_steps + self.decay_steps + ): + # Cosine decay + decay_step = step - self.warmup_steps - self.constant_steps + cosine_decay = 0.5 * (1 + math.cos(math.pi * decay_step / self.decay_steps)) + return [self.min_lr + (base_lr - self.min_lr) * cosine_decay for base_lr in self.base_lrs] + elif self.decay_steps > 0: + # After decay + return [self.min_lr for _ in self.base_lrs] + else: + # No decay phase + return self.base_lrs diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/metrics/__init__.py b/release-20261107/source/workspace_joint/mira/src/mira/training/metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5c0c3aeb908920a0bdc6d735b0506779a03457c3 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/metrics/__init__.py @@ -0,0 +1,5 @@ +"""Training/validation metrics: distributed accumulators and image-quality metrics.""" + +from .distributed_metric import DistributedMetric + +__all__ = ["DistributedMetric"] diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/metrics/distributed_metric.py b/release-20261107/source/workspace_joint/mira/src/mira/training/metrics/distributed_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..cd10d1baec6ace08fcf6f7c61968882173c107fa --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/metrics/distributed_metric.py @@ -0,0 +1,48 @@ +"""A scalar metric accumulated across steps and averaged across distributed ranks.""" + +from __future__ import annotations + +import torch +import torch.distributed as dist +import torch.nn as nn +from torch import Tensor + + +class DistributedMetric(nn.Module): + """Accumulates a scalar metric (sum / count) across steps and distributed ranks.""" + + _sum: Tensor + _n: Tensor + + def __init__(self, device: str | int | torch.device = "cpu"): + super().__init__() + self.register_buffer("_sum", torch.zeros((), dtype=torch.double, device=device)) + self.register_buffer("_n", torch.zeros((), dtype=torch.long, device=device)) + + def reset(self) -> None: + self._sum.zero_() + self._n.zero_() + + def update(self, values: Tensor) -> None: + """Accumulate all elements of ``values``.""" + self._sum += values.detach().sum().to(dtype=torch.double) + self._n += values.numel() + + def all_reduce(self) -> None: + if not (dist.is_available() and dist.is_initialized()): + return + dist.all_reduce(self._sum, op=dist.ReduceOp.SUM) + dist.all_reduce(self._n, op=dist.ReduceOp.SUM) + + def compute(self) -> Tensor: + """Return mean across all accumulated values (and ranks), or 0 if nothing was accumulated.""" + self.all_reduce() + if self._n == 0: # no update() yet — avoid a 0/0 nan + return torch.zeros_like(self._sum) + return self._sum / self._n + + def compute_and_reset(self) -> Tensor: + """Return mean across all accumulated values (and ranks), then reset.""" + output = self.compute() + self.reset() + return output diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/metrics/frechet.py b/release-20261107/source/workspace_joint/mira/src/mira/training/metrics/frechet.py new file mode 100644 index 0000000000000000000000000000000000000000..97bf42623089d346641f388363a4531c600136bc --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/metrics/frechet.py @@ -0,0 +1,70 @@ +"""Sliced Frechet distance: one Gaussian per unrolled-prediction window plus an aggregate. + +The world-model metrics unroll a prediction over many frames and report the Frechet distance between +the predicted and target feature distributions both per window (a curve over "frames unrolled") and +pooled over all windows. The per-window Gaussians reuse :class:`OnlineGaussian` from +``image_metrics`` so the sufficient-statistics / distributed-reduce logic lives in one place. +""" + +from __future__ import annotations + +from typing import cast + +import torch + +from .image_metrics import OnlineGaussian, frechet_distance + + +def _pool(gaussians: list[OnlineGaussian]) -> OnlineGaussian: + """Sum per-slice sufficient statistics into one Gaussian over all slices' frames.""" + pooled = OnlineGaussian(dim=gaussians[0].sum_x.shape[0]).to(gaussians[0].sum_x.device) + for g in gaussians: + pooled.sum_x += g.sum_x + pooled.sum_xxT += g.sum_xxT + pooled.n += g.n + return pooled + + +def _frechet(target: OnlineGaussian, pred: OnlineGaussian) -> float: + t_mean, t_cov = target.compute() + p_mean, p_cov = pred.compute() + return float(frechet_distance(t_mean, t_cov, p_mean, p_cov).item()) + + +class SlicedFrechetMetric(torch.nn.Module): + """Frechet distance between a target and a predicted feature distribution, split into per-slice + windows of the unrolled prediction plus the aggregate over all slices. + + Holds one :class:`OnlineGaussian` per slice for both target and prediction. :meth:`update` + accumulates one slice's features; :meth:`compute` returns ``(aggregate, per_slice_curve)``. + """ + + def __init__(self, dim: int, num_slices: int): + super().__init__() + # Stored in ModuleLists so .to(device)/state_dict recurse into the per-slice Gaussians. + self.target = torch.nn.ModuleList(OnlineGaussian(dim) for _ in range(num_slices)) + self.pred = torch.nn.ModuleList(OnlineGaussian(dim) for _ in range(num_slices)) + + @staticmethod + def _gaussians(module_list: torch.nn.ModuleList) -> list[OnlineGaussian]: + # nn.ModuleList types its members as Module; the metric only ever stores OnlineGaussians. + return [cast(OnlineGaussian, g) for g in module_list] + + def reset(self) -> None: + for g in self._gaussians(self.target) + self._gaussians(self.pred): + g.reset() + + def update(self, slice_idx: int, target_feats: torch.Tensor, pred_feats: torch.Tensor) -> None: + cast(OnlineGaussian, self.target[slice_idx]).update(target_feats) + cast(OnlineGaussian, self.pred[slice_idx]).update(pred_feats) + + def compute(self) -> tuple[float, list[float]]: + """Return ``(aggregate over all slices, per-slice curve)``. Must run on all ranks. + + Pools the per-slice stats BEFORE the per-slice ``compute()`` calls: ``OnlineGaussian.compute()`` + all_reduces its buffers in place, so pooling afterwards would double-count across ranks. + """ + targets, preds = self._gaussians(self.target), self._gaussians(self.pred) + aggregate = _frechet(_pool(targets), _pool(preds)) + per_slice = [_frechet(t, p) for t, p in zip(targets, preds)] + return aggregate, per_slice diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/metrics/image_metrics.py b/release-20261107/source/workspace_joint/mira/src/mira/training/metrics/image_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..b8ce1cbab54dd5f6b9a473ccbf41abe5011be962 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/metrics/image_metrics.py @@ -0,0 +1,225 @@ +"""Image- and video-quality metrics: PSNR, LPIPS, SSIM, and DINO Frechet distance. + +All metrics accumulate across steps and distributed ranks (via :class:`DistributedMetric` or its own +buffers) so they reduce correctly under ``torchrun`` and run unchanged single-process. The DINO-based +metrics load the DINOv3 backbone through ``torch.hub`` (network / hub cache needed) and the Frechet +distance uses ``scipy`` (imported lazily). +""" + +from __future__ import annotations + +import logging +from typing import Any, Literal + +import numpy as np +import torch +import torch.distributed as dist +import torch.nn as nn +from einops import rearrange +from torch import Tensor +from torchmetrics.functional.image import structural_similarity_index_measure + +from mira.codec.dino import ( + IMAGENET_MEAN, + IMAGENET_STD, + PATCH_SIZE, + resolve_dino_weights, +) + +from .distributed_metric import DistributedMetric + +logger = logging.getLogger(__name__) + + +class PSNRMetric(nn.Module): + """Peak signal-to-noise ratio, accumulated per frame across steps and ranks.""" + + def __init__(self, device: str | int | torch.device = "cpu"): + super().__init__() + self._metric = DistributedMetric(device=device) + + def reset(self) -> None: + self._metric.reset() + + def update(self, pred: Tensor, target: Tensor) -> None: + # pred and target are in [0, 1] and have shape (b, t, c, h, w). + mse = torch.nn.functional.mse_loss(pred, target, reduction="none").mean(dim=(2, 3, 4)) + psnr = -10 * torch.log10(mse) # (b, t) + self._metric.update(psnr) + + def compute_and_reset(self) -> Tensor: + return self._metric.compute_and_reset() + + +class DistributedLPIPS(DistributedMetric): + """Per-frame LPIPS accumulated and averaged across distributed ranks.""" + + def __init__(self, device: str | int | torch.device = "cpu"): + super().__init__(device=device) + import lpips as lpips_lib # noqa: PLC0415 -- optional dep, used only here + + self.lpips_fn = lpips_lib.LPIPS(net="alex").to(device) + self.lpips_fn.requires_grad_(False) + + @torch.no_grad() + def update(self, gen: Tensor, real: Tensor) -> None: # type: ignore[override] + """gen, real: [B, T, C, H, W] in [0, 1].""" + batch = gen.shape[0] + # Do it per-video to not OOM on big inputs. + for b in range(batch): + scores = self.lpips_fn(gen[b] * 2 - 1, real[b] * 2 - 1) + super().update(scores) + + +class DistributedSSIM(DistributedMetric): + """Per-frame SSIM accumulated and averaged across distributed ranks.""" + + @torch.no_grad() + def update(self, gen: Tensor, real: Tensor) -> None: # type: ignore[override] + """gen, real: [B, T, C, H, W] in [0, 1]. + + Processes per-video to stay within CUDA 32-bit index limits at high resolution (B*T frames + concatenated overflows 2^31 elements via torchmetrics' 5-channel cat). + """ + B, T = gen.shape[:2] + for b in range(B): + # structural_similarity_index_measure returns the mean over T frames. + ssim_mean = structural_similarity_index_measure(gen[b], real[b], data_range=1.0) + assert isinstance(ssim_mean, Tensor) + self._sum += ssim_mean.detach().double() * T + self._n += T + + +class DinoForMetrics(nn.Module): + """A frozen DINOv3 backbone exposing last-layer features for the Frechet-distance metric.""" + + dino_model: Any # hub-loaded backbone; typed loosely as its API is dynamic + mean: Tensor + std: Tensor + + def __init__(self, model_size: Literal["large", "base"] = "base"): + super().__init__() + + if model_size == "base": + model_name = "dinov3_vitb16" + self.dino_dim = 768 + elif model_size == "large": + model_name = "dinov3_vitl16" + self.dino_dim = 1024 + else: + raise ValueError(f"Model size {model_size} not supported.") + + logging.getLogger("dinov3").setLevel(logging.WARNING) # suppress noisy dinov3 logging + logger.info(f"Loading DINOv3 model, variant {model_name}") + weights = resolve_dino_weights(model_name) + self.dino_model = torch.hub.load( + repo_or_dir="facebookresearch/dinov3", + model=model_name, + weights=str(weights) if weights is not None else None, + source="github", + verbose=False, # Get rid of "Using cache found in ..." message + ) + + self.register_buffer( + "mean", torch.tensor(IMAGENET_MEAN, dtype=torch.float)[None, :, None, None], persistent=False + ) + self.register_buffer( + "std", torch.tensor(IMAGENET_STD, dtype=torch.float)[None, :, None, None], persistent=False + ) + self.patch_size = PATCH_SIZE + + self.requires_grad_(False) + self.eval() + + def image_normalization(self, x: Tensor) -> Tensor: + return (x - self.mean) / self.std + + @torch.no_grad() + def dino_forward(self, x: Tensor, max_chunk_size: int | None = None) -> Tensor: + """Compute DINO features. If max_chunk_size is set, processes frames in chunks to avoid OOM.""" + b, t, _, h, w = x.shape + x = rearrange(x, "b t c h w -> (b t) c h w") # x must be in [0, 1] + x = self.image_normalization(x) + new_height = self.patch_size * (h // self.patch_size) + new_width = self.patch_size * (w // self.patch_size) + x = torch.nn.functional.interpolate(x, (new_height, new_width), mode="bilinear", antialias=True) + + n = x.shape[0] + if max_chunk_size is not None and n > max_chunk_size: + features = [] + for i in range(0, n, max_chunk_size): + feat = self.dino_model.get_intermediate_layers( + x[i : i + max_chunk_size], n=1, norm=True, reshape=True + )[0] + features.append(feat) + last_dino_feature = torch.cat(features, dim=0) + else: + last_dino_feature = self.dino_model.get_intermediate_layers(x, n=1, norm=True, reshape=True)[0] + + last_dino_feature = rearrange(last_dino_feature, "(b t) c h w -> b t c h w", b=b, t=t) + return last_dino_feature + + +def frechet_distance(mean1: Tensor, cov1: Tensor, mean2: Tensor, cov2: Tensor) -> np.floating: + """Frechet distance between two Gaussians given their means and covariances (returns a scalar).""" + from scipy.linalg import sqrtm # noqa: PLC0415 -- optional dep, used only here + + # Convert to numpy because it's not easy to do sqrtm in Torch. + mean1_np, mean2_np = mean1.cpu().numpy(), mean2.cpu().numpy() + cov1_np, cov2_np = cov1.cpu().numpy(), cov2.cpu().numpy() + + diff = mean1_np - mean2_np + cov_prod = sqrtm(cov1_np.dot(cov2_np)) + cov_prod = np.asarray(cov_prod) + if np.iscomplexobj(cov_prod): + cov_prod = np.real(cov_prod) + + distance = diff.dot(diff) + np.trace(cov1_np + cov2_np - 2 * cov_prod) + return distance + + +class OnlineGaussian(nn.Module): + """Online estimator of a Gaussian's mean and covariance from sufficient statistics.""" + + sum_x: Tensor + sum_xxT: Tensor + n: Tensor + + def __init__(self, dim: int): + super().__init__() + self.register_buffer("sum_x", torch.zeros((dim,), dtype=torch.double)) + self.register_buffer("sum_xxT", torch.zeros((dim, dim), dtype=torch.double)) + self.register_buffer("n", torch.zeros((), dtype=torch.long)) + + def reset(self) -> None: + self.sum_x.zero_() + self.sum_xxT.zero_() + self.n.zero_() + + def update(self, x: Tensor) -> None: + # x must have shape (b, dim). + x = x.to(dtype=torch.double) + b = x.shape[0] + self.n += b + self.sum_x += x.sum(dim=0) + self.sum_xxT += x.T @ x + + def all_reduce(self) -> None: + if not (dist.is_available() and dist.is_initialized()): + return + dist.all_reduce(self.sum_x, op=dist.ReduceOp.SUM) + dist.all_reduce(self.sum_xxT, op=dist.ReduceOp.SUM) + dist.all_reduce(self.n, op=dist.ReduceOp.SUM) + + def compute(self, unbiased: bool = True, eps: float = 1e-6) -> tuple[Tensor, Tensor]: + self.all_reduce() + assert self.n > 1, "Need at least 2 samples to compute statistics." + n = self.n.to(dtype=torch.double) + mean = self.sum_x / n + + cov_num = self.sum_xxT - n * torch.outer(mean, mean) + denom = (n - 1.0) if unbiased else n + cov = cov_num / denom + if eps > 0: + cov = cov + eps * torch.eye(cov.shape[0], dtype=cov.dtype, device=cov.device) + return mean, cov diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/metrics/world_model_metrics.py b/release-20261107/source/workspace_joint/mira/src/mira/training/metrics/world_model_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..0c841f1dfd84964fad104d535c9fded9d72419f4 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/metrics/world_model_metrics.py @@ -0,0 +1,337 @@ +"""World-model rollout metrics: DINO / latent drift and Frechet (DINO / Inception) curves. + +:class:`WorldModelMetrics` unrolls the world model autoregressively over a held-out clip and scores +the prediction against the ground truth: per-frame PSNR / LPIPS / SSIM, DINO cosine and L2 drift, +latent cosine drift, and sliced Frechet DINO / Inception distances (an aggregate plus a per-window +curve over "frames unrolled"). The DINO and Inception backbones load lazily (``torch.hub`` / +``pytorch_fid``), so the metrics object is only constructed where those are available; the rest of +the module imports without them. +""" + +from __future__ import annotations + +import contextlib +import logging +from collections.abc import Iterator +from typing import Any + +import torch +from einops import rearrange +from pydantic import BaseModel, ConfigDict + +from mira.data.batch import VideoActionBatch +from mira.world_model.config import WorldModelInferenceConfig +from mira.world_model.latent_world_model import InferenceOutputs, LatentWorldModel + +from .distributed_metric import DistributedMetric +from .frechet import SlicedFrechetMetric +from .image_metrics import DinoForMetrics, DistributedLPIPS, DistributedSSIM, PSNRMetric + +logger = logging.getLogger(__name__) + +# Standard FID uses the final 2048-dim InceptionV3 pool features. +INCEPTION_FID_DIM = 2048 + + +def _autocast(device: torch.device | int | str): + """bfloat16 autocast on CUDA, a no-op elsewhere (so the metrics run on CPU too).""" + if torch.cuda.is_available(): + return torch.autocast(device_type="cuda", dtype=torch.bfloat16) + return contextlib.nullcontext() + + +class WorldModelMetricsConfig(BaseModel): + """Configuration for :class:`WorldModelMetrics` and the offline eval entry point. + + Frame counts are in LATENT-rate frames; per-frame metrics subsample the decoded video by + ``eval_temporal_downsampling`` so the numbers are comparable across codecs with different + ``temporal_downsampling``. + """ + + # Checkpoint / output paths, filled in by the eval entry point. + checkpoint: str | None = None + output_dir: str | None = None + + per_device_batch_size: int = 1 # eval batch size per GPU + num_samples: int = 0 # limit the number of evaluated samples (0 = whole dataset) + # Context frames the eval rollout conditions on. None keeps the model's own n_context_frames; an + # int overrides it at eval time (see LatentWorldModel.set_inference_context), so the total eval + # clip (n_context_frames + num_unrolled_frames * temporal_downsampling) can be shrunk to fit + # shorter data. It must be a multiple of the codec temporal_downsampling and smaller than the + # model window (video.timesteps). + n_context_frames: int | None = None + num_unrolled_frames: int = 120 + drift_metric_frames: int = 20 + fdd_slice_frames: int = 20 + # None auto-derives from model.temporal_downsampling at eval time; set explicitly to subsample + # to a different rate (e.g. 2 for a td=1 codec running at 20 fps latent). + eval_temporal_downsampling: int | None = None + compile: bool = True # whether to compile the DINO backbone for faster inference + # Max frames per DINO forward pass, reduces peak memory (None = no limit). + dino_max_chunk_size: int | None = None + # How many eval samples to visualize (logged to W&B from the metrics loop). + num_viz_samples: int = 8 + # Inference settings (e.g. n_diffusion_steps, noise_level) used when unrolling the world model. + inference: WorldModelInferenceConfig = WorldModelInferenceConfig() + + +class _MetricTrackers(BaseModel): + dino_cos_drift: DistributedMetric + dino_l2_drift: DistributedMetric + latent_drift: DistributedMetric + dino_frechet: SlicedFrechetMetric + inception_frechet: SlicedFrechetMetric + # FDD decomposition: vs_recon = prediction vs codec reconstruction (world-model error); + # codec_floor = codec reconstruction vs original frames (codec error). + dino_frechet_vs_recon: SlicedFrechetMetric + dino_frechet_codec_floor: SlicedFrechetMetric + psnr: PSNRMetric + lpips: DistributedLPIPS + ssim: DistributedSSIM + + model_config = ConfigDict(arbitrary_types_allowed=True) + + def reset(self) -> None: + for field_name in self.__class__.model_fields: + getattr(self, field_name).reset() + + +class WorldModelMetrics: + """Stateful evaluator for world-model metrics (DINO drift, latent drift, Frechet distances). + + Usage:: + + metrics = WorldModelMetrics(config, iter_dataloader, device) + for _ in range(num_batches): + metrics.process_batch(model) + scalar_result, frechet_curves = metrics.compute() + """ + + def __init__( + self, + config: WorldModelMetricsConfig, + iter_dataloader: Iterator[tuple[VideoActionBatch, list]], + device: torch.device | int | str, + ): + # pytorch_fid is an eval-only optional dep (the `eval` extra); imported lazily so the + # module loads without it and the offline metrics tests skip-gate on its absence. + from pytorch_fid.inception import ( # type: ignore[import-not-found] # noqa: PLC0415 + InceptionV3 as InceptionV3ForFID, + ) + + self.config = config + self.iter_dataloader = iter_dataloader + assert config.num_unrolled_frames % config.fdd_slice_frames == 0, ( + f"num_unrolled_frames ({config.num_unrolled_frames}) must be a multiple of " + f"fdd_slice_frames ({config.fdd_slice_frames})" + ) + self.num_slices = config.num_unrolled_frames // config.fdd_slice_frames + self.dino = DinoForMetrics(model_size="base").to(device) + inception_block_idx = InceptionV3ForFID.BLOCK_INDEX_BY_DIM[INCEPTION_FID_DIM] + self._inception = InceptionV3ForFID([inception_block_idx]).to(device).eval() + self._inception.requires_grad_(False) + self._trackers = _MetricTrackers( + dino_cos_drift=DistributedMetric(device=device), + dino_l2_drift=DistributedMetric(device=device), + latent_drift=DistributedMetric(device=device), + dino_frechet=SlicedFrechetMetric(self.dino.dino_dim, self.num_slices).to(device), + inception_frechet=SlicedFrechetMetric(INCEPTION_FID_DIM, self.num_slices).to(device), + dino_frechet_vs_recon=SlicedFrechetMetric(self.dino.dino_dim, self.num_slices).to(device), + dino_frechet_codec_floor=SlicedFrechetMetric(self.dino.dino_dim, self.num_slices).to(device), + psnr=PSNRMetric(device=device), + lpips=DistributedLPIPS(device=device), + ssim=DistributedSSIM(device=device), + ) + + if self.config.compile: + self.dino.dino_forward = torch.compile(self.dino.dino_forward) + + def process_batch(self, model: LatentWorldModel) -> tuple[InferenceOutputs, list]: + """Get the next batch, unroll the world model, and accumulate metrics.""" + batch, metadata = next(self.iter_dataloader) + batch_size = batch.video.shape[0] + device = model.device + + with torch.no_grad(), _autocast(device): + world_model_outputs = model.inference(batch, config=self.config.inference, progress_bar=False) + + batch = batch.to(device) + _, codec_outputs = model.codec.encode(batch.video, trim_video=False) + # The release codec is the deterministic RAE whose posterior mean equals its sample. + z_for_target = codec_outputs.z + z_mean_target = rearrange(z_for_target, "b t c h w -> b t h w c") + + video = model.decode_to_video(world_model_outputs.z_t) + + # Subsample to the LATENT rate so per-frame metrics are comparable across codecs with + # different temporal_downsampling. For td=1 stride=1 and this is a no-op. + stride = self.config.eval_temporal_downsampling or model.temporal_downsampling + video = video[:, ::stride] + batch_video_eval = batch.video[:, ::stride] + + n = model.config.n_context_frames // stride + df = self.config.drift_metric_frames + w = self.config.fdd_slice_frames + pred_frames = video[:, n : n + df].float() + real_frames = batch_video_eval[:, n : n + df].float() + + self._trackers.psnr.update(pred_frames, real_frames) + self._trackers.lpips.update(pred_frames, real_frames) + self._trackers.ssim.update(pred_frames, real_frames) + + pred_video_full = video[:, n : n + self.num_slices * w].float() + real_video_full = batch_video_eval[:, n : n + self.num_slices * w].float() + for s in range(self.num_slices): + fs = slice(s * w, (s + 1) * w) + pred_slice = pred_video_full[:, fs] + real_slice = real_video_full[:, fs] + bs, ts = pred_slice.shape[:2] + pred_flat = pred_slice.reshape(bs * ts, *pred_slice.shape[2:]) + real_flat = real_slice.reshape(bs * ts, *real_slice.shape[2:]) + with torch.no_grad(): + both_inception = self._inception(torch.cat([pred_flat, real_flat], dim=0))[0] + both_inception = both_inception.squeeze(-1).squeeze(-1) + pred_inception, real_inception = both_inception.chunk(2, dim=0) + self._trackers.inception_frechet.update(s, real_inception, pred_inception) + + all_dino_features = self.dino.dino_forward( + torch.cat([video[:, n:], batch_video_eval[:, n:]], dim=0), + max_chunk_size=self.config.dino_max_chunk_size, + ) + pred_dino_features = all_dino_features[:batch_size] + dino_target_features = all_dino_features[batch_size:] + + dino_similarities = torch.nn.functional.cosine_similarity( + pred_dino_features, dino_target_features, dim=-1 + ) + # Convert cosine similarity to a distance; in practice a value > 1 means worse than chance. + dino_cos_drifts = 1 - dino_similarities + dino_cos_drift = dino_cos_drifts.mean(dim=(2, 3)).cpu()[:, : self.config.drift_metric_frames] + + # DINO L2 distance (MSE over feature dim, averaged over spatial/temporal). + dino_l2_drifts = torch.nn.functional.mse_loss( + pred_dino_features, dino_target_features, reduction="none" + ).mean(dim=-1) + dino_l2_drift = dino_l2_drifts.mean(dim=(2, 3)).cpu()[:, : self.config.drift_metric_frames] + + latent_similarities = torch.nn.functional.cosine_similarity( + z_mean_target.float(), + model.unnormalize_tokens(world_model_outputs.z_t.float()), + dim=-1, + ) + latent_drifts = 1 - latent_similarities + # z_t is in LATENT frames; index by n_context_latents, not n_context_frames. + latent_drifts = latent_drifts[:, model.n_context_latents :][:, : self.config.drift_metric_frames] + latent_drift = latent_drifts.mean(dim=(2, 3)).cpu() + + self._trackers.dino_cos_drift.update(dino_cos_drift) + self._trackers.dino_l2_drift.update(dino_l2_drift) + self._trackers.latent_drift.update(latent_drift) + for s in range(self.num_slices): + fs = slice(s * w, (s + 1) * w) + self._trackers.dino_frechet.update( + s, + dino_target_features[:, fs].mean(dim=(-1, -2)).flatten(0, 1), + pred_dino_features[:, fs].mean(dim=(-1, -2)).flatten(0, 1), + ) + + # FDD decomposition: also compare against the codec's own reconstruction of the GT. + # z_for_target is the raw codec latent, so decode it directly (rather than via + # decode_to_video, which would also unnormalize). Same [-1, 1] -> [0, 1] post-processing. + with torch.no_grad(), _autocast(device): + recon_video = (model.codec.decode(z_for_target) * 0.5 + 0.5).float() + recon_dino_features = self.dino.dino_forward( + recon_video[:, model.config.n_context_frames :], + max_chunk_size=self.config.dino_max_chunk_size, + ) + for s in range(self.num_slices): + fs = slice(s * w, (s + 1) * w) + recon_feats = recon_dino_features[:, fs].mean(dim=(-1, -2)).flatten(0, 1) + pred_feats = pred_dino_features[:, fs].mean(dim=(-1, -2)).flatten(0, 1) + target_feats = dino_target_features[:, fs].mean(dim=(-1, -2)).flatten(0, 1) + # World-model error alone: prediction vs codec reconstruction. + self._trackers.dino_frechet_vs_recon.update(s, recon_feats, pred_feats) + # Codec error alone: codec reconstruction vs original frames. + self._trackers.dino_frechet_codec_floor.update(s, target_feats, recon_feats) + + return world_model_outputs, metadata + + def compute(self) -> tuple[dict[str, torch.Tensor | float], dict[str, list[float]]]: + """Return ``(scalar metrics, per-slice Frechet curves)``, then reset. + + ``OnlineGaussian.compute()`` all_reduces, so this must run on all ranks. + """ + df = self.config.drift_metric_frames + scalar_result: dict[str, torch.Tensor | float] = { + f"dino_cos_drift_{df}": self._trackers.dino_cos_drift.compute(), + f"dino_l2_drift_{df}": self._trackers.dino_l2_drift.compute(), + f"latent_drift_{df}": self._trackers.latent_drift.compute(), + "psnr": self._trackers.psnr.compute_and_reset(), + "lpips": self._trackers.lpips.compute_and_reset(), + "ssim": self._trackers.ssim.compute_and_reset(), + } + + # Each Frechet metric yields an aggregate scalar (pooled over all unrolled frames) plus a + # per-slice curve. + scalar_result["frechet_dino_distance"], fdd_curve = self._trackers.dino_frechet.compute() + scalar_result["frechet_inception_distance"], fid_curve = self._trackers.inception_frechet.compute() + frechet_curves: dict[str, list[float]] = {"fdd_at": fdd_curve, "fid_at": fid_curve} + + scalar_result["frechet_dino_distance_vs_recon"], vr_curve = ( + self._trackers.dino_frechet_vs_recon.compute() + ) + scalar_result["frechet_dino_distance_codec_floor"], cf_curve = ( + self._trackers.dino_frechet_codec_floor.compute() + ) + frechet_curves["fdd_at_vs_recon"] = vr_curve + frechet_curves["fdd_at_codec_floor"] = cf_curve + + # Also expose each per-slice value as a scalar keyed by the number of frames unrolled at the + # end of its slice (fdd_at_20 ... fdd_at_120), so the curves are trackable as W&B line plots + # over training, not just per-step snapshots. + w = self.config.fdd_slice_frames + for name, values in frechet_curves.items(): + for i, v in enumerate(values): + scalar_result[f"{name}_{(i + 1) * w}"] = v + + self._trackers.reset() + return scalar_result, frechet_curves + + +def build_frechet_curve_plots(frechet_curves: dict[str, list[float]], slice_frames: int) -> dict[str, Any]: + """Per-slice Frechet line plots (x = frames unrolled, y = Frechet distance), one per eval step.""" + import plotly.graph_objects as go # noqa: PLC0415 -- optional dep, used only here + import wandb # noqa: PLC0415 -- optional dep, used only here + + metric_labels = { + "fdd_at": "Frechet DINO Distance", + "fid_at": "Frechet Inception Distance", + } + plots: dict[str, Any] = {} + for name, values in frechet_curves.items(): + # x = number of frames unrolled at the end of each slice (20, 40, ..., 120). + xs = [(i + 1) * slice_frames for i in range(len(values))] + frame_ranges = [f"[{i * slice_frames}, {(i + 1) * slice_frames})" for i in range(len(values))] + label = metric_labels.get(name, name) + fig = go.Figure( + data=[ + go.Scatter( + x=xs, + y=[float(v) for v in values], + mode="lines+markers", + customdata=frame_ranges, + hovertemplate=( + "%{x} frames unrolled (slice frames %{customdata})
" + f"{label}=%{{y:.4f}}" + ), + ) + ] + ) + fig.update_layout( + title=f"{label} vs frames unrolled", + xaxis_title="frames unrolled", + yaxis_title=label, + xaxis=dict(tickmode="linear", dtick=slice_frames), + ) + plots[f"viz/{name}"] = wandb.Plotly(fig) + return plots diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/swanlab_tracker.py b/release-20261107/source/workspace_joint/mira/src/mira/training/swanlab_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..03128deca019fb4917b9cd44a90b9aff355e9dcd --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/swanlab_tracker.py @@ -0,0 +1,247 @@ +"""Rank-zero SwanLab experiment tracking for training entry points.""" + +from __future__ import annotations + +import logging +import os +import uuid +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +logger = logging.getLogger(__name__) + +_SECRET_KEY_PARTS = ("api_key", "apikey", "password", "secret", "token") +_TOKEN_LABELS = {"api_key", "swanlab", "swanlab_api_key", "swanlab_token", "token"} +_PROXY_ENDPOINT_VARIABLES = ( + "http_proxy", + "https_proxy", + "all_proxy", + "ftp_proxy", + "HTTP_PROXY", + "HTTPS_PROXY", + "ALL_PROXY", + "FTP_PROXY", +) + + +def _force_direct_connection() -> None: + """Make every HTTP client created by SwanLab bypass environment proxies.""" + for variable in _PROXY_ENDPOINT_VARIABLES: + os.environ.pop(variable, None) + # Requests/httpx honor these variables even if a parent process later injects a proxy endpoint. + os.environ["NO_PROXY"] = "*" + os.environ["no_proxy"] = "*" + + +def _without_secrets(value: Any) -> Any: + """Recursively remove credentials from a configuration before cloud upload.""" + if isinstance(value, Mapping): + return { + str(key): _without_secrets(child) + for key, child in value.items() + if not any(part in str(key).lower() for part in _SECRET_KEY_PARTS) + } + if isinstance(value, (list, tuple)): + return [_without_secrets(child) for child in value] + return value + + +def _scalar(value: Any) -> Any: + """Turn scalar tensors/NumPy values into JSON-friendly Python scalars.""" + numel = getattr(value, "numel", None) + if callable(numel) and numel() == 1: + detach = getattr(value, "detach", None) + if callable(detach): + value = detach() + cpu = getattr(value, "cpu", None) + if callable(cpu): + value = cpu() + item = getattr(value, "item", None) + if callable(item): + return item() + + item = getattr(value, "item", None) + if callable(item): + try: + return item() + except (TypeError, ValueError): + pass + return value + + +def _read_api_key(path: Path) -> str: + """Read a bare token or the SwanLab entry in a multi-service token file.""" + lines = [line.strip() for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() and not line.lstrip().startswith("#")] + if not lines: + raise ValueError(f"SwanLab token file is empty: {path}") + selected = [] + for line in lines: + for separator in ("=", ":"): + if separator not in line: + continue + label, candidate = line.split(separator, 1) + if label.strip().lower().replace("-", "_") in _TOKEN_LABELS: + selected.append(candidate.strip()) + break + if len(selected) == 1: + value = selected[0] + elif len(lines) == 1 and not selected: + value = lines[0] + else: + raise ValueError(f"SwanLab token file has no unique SwanLab credential: {path}") + + if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}: + value = value[1:-1].strip() + if not value or any(character.isspace() for character in value): + raise ValueError(f"SwanLab token file has an unsupported format: {path}") + return value + + +class SwanLabTracker: + """A small SwanLab adapter that is instantiated only by distributed rank zero.""" + + def __init__(self, swanlab_module: Any = None, run: Any = None) -> None: + self._swanlab = swanlab_module + self._run = run + self._finished = False + + @classmethod + def disabled(cls) -> SwanLabTracker: + return cls() + + @classmethod + def initialize( + cls, + tracking_config: Mapping[str, Any], + *, + output_dir: str | Path, + run_config: Mapping[str, Any], + ) -> SwanLabTracker: + """Authenticate without persisting the token and initialize a resumable run.""" + mode = str(tracking_config.get("mode", "disabled")).lower() + if mode == "disabled": + return cls.disabled() + + _force_direct_connection() + import swanlab # noqa: PLC0415 -- optional dependency used only by rank zero + + output_dir = Path(output_dir).expanduser().resolve() + output_dir.mkdir(parents=True, exist_ok=True) + + if mode == "online": + token_file_value = tracking_config.get("token_file") + token = None + if token_file_value: + token_file = Path(str(token_file_value)).expanduser().resolve() + if not token_file.is_file(): + raise FileNotFoundError(f"SwanLab token file not found: {token_file}") + token = _read_api_key(token_file) + else: + token = os.environ.get("SWANLAB_API_KEY", "").strip() + if not token: + raise ValueError( + "SwanLab online mode requires swanlab.token_file or SWANLAB_API_KEY" + ) + + # save=False keeps the credential out of the user's global SwanLab configuration. + if not swanlab.login(api_key=token, save=False): + raise RuntimeError("SwanLab authentication failed") + + run_id_path = output_dir / "swanlab_run_id.txt" + run_id = cls._load_or_create_run_id(run_id_path) + settings = swanlab.Settings( + interactive=False, + terminal=swanlab.Settings.Terminal( + proxy_type=str(tracking_config.get("capture_console", "stderr")) + ), + probe=swanlab.Settings.Probe( + hardware=bool(tracking_config.get("upload_hardware", True)), + runtime=bool(tracking_config.get("upload_runtime", True)), + requirements=bool(tracking_config.get("upload_requirements", False)), + conda=False, + git=bool(tracking_config.get("upload_git", False)), + swanlab=True, + monitor=bool(tracking_config.get("system_monitor", False)), + ), + ) + run = swanlab.init( + project=str(tracking_config.get("project", "Multi_WAM")), + workspace=tracking_config.get("workspace"), + name=str(tracking_config.get("experiment_name", "codec-training")), + description=tracking_config.get("description"), + job_type=str(tracking_config.get("job_type", "codec-training")), + group=tracking_config.get("group"), + tags=list(tracking_config.get("tags", [])), + config=_without_secrets(run_config), + log_dir=str(output_dir / "swanlog"), + mode=mode, + public=bool(tracking_config.get("public", False)), + id=run_id, + resume=str(tracking_config.get("resume", "allow")), + settings=settings, + ) + + actual_run_id = getattr(run, "id", None) or run_id + cls._write_run_id(run_id_path, str(actual_run_id)) + tracker = cls(swanlab_module=swanlab, run=run) + logger.info( + "SwanLab initialized: project=%s, run_id=%s", + tracking_config.get("project", "Multi_WAM"), + actual_run_id, + ) + experiment_url = tracker.experiment_url + if experiment_url: + logger.info("SwanLab experiment: %s", experiment_url) + return tracker + + @staticmethod + def _load_or_create_run_id(path: Path) -> str: + if path.is_file(): + run_id = path.read_text(encoding="utf-8").strip() + if run_id: + return run_id + run_id = uuid.uuid4().hex[:21] + SwanLabTracker._write_run_id(path, run_id) + return run_id + + @staticmethod + def _write_run_id(path: Path, run_id: str) -> None: + temporary = path.with_name(f".{path.name}.tmp") + temporary.write_text(f"{run_id}\n", encoding="utf-8") + temporary.replace(path) + + @property + def enabled(self) -> bool: + return self._run is not None + + @property + def experiment_url(self) -> str | None: + if not self.enabled: + return None + try: + return self._run.url + except (AttributeError, ValueError): + return None + + def log(self, data: Mapping[str, Any], *, step: int) -> None: + if not self.enabled: + return + self._swanlab.log({key: _scalar(value) for key, value in data.items()}, step=step) + + def video(self, path: str | Path, *, caption: str | None = None) -> Any: + if not self.enabled: + raise RuntimeError("Cannot create SwanLab media when tracking is disabled") + return self._swanlab.Video(str(path), caption=caption) + + def image(self, path: str | Path, *, caption: str | None = None) -> Any: + if not self.enabled: + raise RuntimeError("Cannot create SwanLab media when tracking is disabled") + return self._swanlab.Image(str(path), caption=caption) + + def finish(self) -> None: + if not self.enabled or self._finished: + return + self._run.finish() + self._finished = True diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/tracker.py b/release-20261107/source/workspace_joint/mira/src/mira/training/tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..a45849783ec077216adceb00ab05fc8e45a20be7 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/tracker.py @@ -0,0 +1,133 @@ +"""Training-loop bookkeeping: throughput/loss tracking, periodic events, and timing.""" + +from __future__ import annotations + +import logging +import time +from collections import defaultdict + +import torch + +from mira.data.batch import VideoActionBatch + +from .metrics.distributed_metric import DistributedMetric + +logger = logging.getLogger(__name__) + + +class TrainingTracker: + """Tracks training statistics: throughput, losses, and ETA.""" + + def __init__( + self, + world_size: int, + device: str | int | torch.device = "cpu", + total_steps: int | None = None, + ): + self.world_size = world_size + self.device = device + self.total_steps = total_steps + self.training_start_time: float | None = None + self.current_start_time: float | None = time.time() + self.total_n_frames_processed = 0 + + self.cur_n_frames_processed = 0 + self.cur_losses: dict[str, DistributedMetric] = defaultdict( + lambda: DistributedMetric(device=self.device) + ) + + def on_batch_processed(self, batch: VideoActionBatch, losses: dict[str, torch.Tensor]) -> None: + if self.training_start_time is None: + self.training_start_time = time.time() + if self.current_start_time is None: + self.current_start_time = time.time() + + n_frames_in_batch = batch.video.shape[0] * batch.video.shape[1] + + self.total_n_frames_processed += n_frames_in_batch + + self.cur_n_frames_processed += n_frames_in_batch + for k, v in losses.items(): + self.cur_losses[k].update(v) + + def get_stats(self, step: int) -> dict[str, float]: + if self.current_start_time is None: + return {} + + elapsed_time = time.time() - self.current_start_time + if elapsed_time == 0: + return {} + + n_frames_processed_per_sec = self.cur_n_frames_processed / elapsed_time + losses_to_log = { + f"train/{k}": metric.compute_and_reset().item() for k, metric in self.cur_losses.items() + } + + self.current_start_time = time.time() + self.cur_n_frames_processed = 0 + + eta_stats: dict[str, float] = {} + if self.total_steps is not None and step > 0: + if self.training_start_time is not None: + total_elapsed = time.time() - self.training_start_time + steps_remaining = self.total_steps - step + time_per_step = total_elapsed / step + eta_seconds = steps_remaining * time_per_step + eta_stats["System/eta_hours"] = eta_seconds / 3600 + + return { + "System/n_frames_processed": self.total_n_frames_processed * self.world_size, + "System/throughput_fps_total": n_frames_processed_per_sec * self.world_size, + "System/throughput_fps_per_gpu": n_frames_processed_per_sec, + **losses_to_log, + **eta_stats, + } + + +def periodic_event( + step: int, interval: int | str, total_steps: int | None = None, include_0: bool = True +) -> bool: + """Determine if an action should occur at the current step based on interval or percentage.""" + if step == 0: + return include_0 + + if isinstance(interval, int): + return step % interval == 0 + elif isinstance(interval, str) and interval.endswith("%"): + percent = float(interval[:-1]) + if percent <= 0 or percent > 100: + raise ValueError("interval percentage must be between 1 and 100") + + if total_steps is None: + raise ValueError("total_steps must be provided when using percentage intervals") + + steps_interval = max(1, int(total_steps * (percent / 100))) + return step % steps_interval == 0 + else: + raise ValueError(f"Invalid interval: {interval}. Must be int or percentage string (e.g. '10%')") + + +class display_execution_time: + """Context manager that logs the wall-clock time taken by the wrapped block.""" + + def __init__(self, task_name: str, print_output: bool = True): + self.task_name = task_name + self.print_output = print_output + self.start_time: float | None = None + self.elapsed_time_ms: int | None = None + self.logger = logging.getLogger(__name__) + + def __enter__(self) -> display_execution_time: + self.start_time = time.monotonic() + return self + + def __exit__(self, exc_type, exc_val, exc_tb) -> bool: + assert self.start_time is not None + end_time = time.monotonic() + self.elapsed_time_ms = int((end_time - self.start_time) * 1000) + if self.print_output: + if self.elapsed_time_ms < 1000: + self.logger.info("%s took %dms", self.task_name, self.elapsed_time_ms) + else: + self.logger.info("%s took %.2fs", self.task_name, self.elapsed_time_ms / 1000.0) + return False # Don't suppress exceptions diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/visualization.py b/release-20261107/source/workspace_joint/mira/src/mira/training/visualization.py new file mode 100644 index 0000000000000000000000000000000000000000..21a22ad79667dc1541413e80d8a25a2e7698a9b5 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/visualization.py @@ -0,0 +1,541 @@ +"""Video helpers for logging codec/world-model reconstructions. + +These encode batches of ``(B, T, C, H, W)`` videos to mp4 (via a system ``ffmpeg``) and arrange them +into grids. The pipeline is video-only, so no audio track is muxed. +""" + +from __future__ import annotations + +import logging +import subprocess +import tempfile +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path +from typing import TYPE_CHECKING, Literal + +import numpy as np +import torch +import torch.nn.functional as F +from einops import rearrange +from PIL import Image, ImageDraw, ImageFont +from pydantic import BaseModel, ConfigDict +from torch import Tensor + +if TYPE_CHECKING: + from mira.world_model.actions_config import ActionTensors + + +def embeddings_pca_to_rgb( + embeddings: Tensor, + output_height: int, + output_width: int, + n_fit_frames: int | None = None, +) -> Tensor: + """Project high-dimensional embeddings to RGB via PCA for visualization. + + Args: + embeddings: Tensor of shape (B, T, C, H, W). + output_height: Target height for the output RGB images. + output_width: Target width for the output RGB images. + n_fit_frames: Number of frames to use when fitting PCA. None means all frames. Reducing this + speeds up PCA fitting for high-dimensional features (e.g. raw DINO). + + Returns: + Tensor of shape (B, T, 3, output_height, output_width), dtype uint8. + """ + from sklearn.decomposition import PCA # type: ignore[import-not-found] # noqa: PLC0415 -- optional dep + + b, t, _c, h, w = embeddings.shape + + projected_batches = [] + for i in range(b): + feats = embeddings[i] # T, C, H, W + feats_flat = rearrange(feats, "t c h w -> (t h w) c").float().cpu().numpy() + + if n_fit_frames is None or n_fit_frames >= t: + fit_flat = feats_flat + else: + # Evenly sample n_fit_frames across the sequence for a representative fit. + indices = torch.linspace(0, t - 1, n_fit_frames).long() + fit_flat = rearrange(feats[indices], "t c h w -> (t h w) c").float().cpu().numpy() + + pca = PCA(n_components=3, whiten=True) + pca.fit(fit_flat) + + projected = torch.from_numpy(pca.transform(feats_flat)) + projected = rearrange(projected, "(t h w) c -> t c h w", t=t, h=h, w=w) + projected_batches.append(projected) + + projected_images = torch.stack(projected_batches, dim=0) # B, T, 3, H, W + + # Sigmoid color enhancement to spread the PCA components across the RGB range. + projected_images = torch.nn.functional.sigmoid(projected_images.mul(2.0)) + + # Upsample to output resolution. + projected_images = rearrange(projected_images, "b t c h w -> (b t) c h w") + projected_images = F.interpolate( + projected_images, size=(output_height, output_width), mode="bilinear", align_corners=False + ) + projected_images = rearrange(projected_images, "(b t) c h w -> b t c h w", b=b, t=t) + + return (255.0 * projected_images).clamp(0, 255).to(torch.uint8) + + +def video_to_uint8(video: Tensor) -> Tensor: + """Convert a floating-point video in [0, 1] to uint8 in [0, 255] (no-op if already uint8).""" + if video.dtype != torch.uint8: + if not torch.is_floating_point(video): + raise ValueError(f"Expected uint8 or floating point video tensor, got dtype {video.dtype}") + + # Cast to float32 first so that rounding in reduced-precision dtypes (bfloat16 / float16) + # does not push values outside [0, 255]. + video = video.float() + video = torch.clamp(video * 255.0, 0, 255).to(torch.uint8) + return video + + +def draw_text_on_first_frame(video: Tensor, texts: list[str]) -> Tensor: + """Draw text labels on the first frame of each batch item. + + Args: + video: (B, T, C, H, W) uint8 tensor. + texts: list of length B with text to draw on each item's first frame. + """ + video = video.clone() + for i, text in enumerate(texts): + frame = video[i, 0] # (C, H, W) + img = Image.fromarray(rearrange(frame.cpu().numpy(), "c h w -> h w c")) + draw = ImageDraw.Draw(img, "RGBA") + try: + font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 14) + except OSError: + font = ImageFont.load_default() + bbox = draw.textbbox((0, 0), text, font=font) + text_w, text_h = bbox[2] - bbox[0], bbox[3] - bbox[1] + padding = 4 + draw.rectangle([4, 4, 4 + text_w + 2 * padding, 4 + text_h + 2 * padding], fill=(0, 0, 0, 180)) + draw.text((4 + padding, 4 + padding), text, fill="white", font=font) + video[i, 0] = torch.from_numpy(rearrange(np.array(img)[..., :3], "h w c -> c h w")) + return video + + +def write_video_ffmpeg( + filename: str | Path, + video_tensor: Tensor, + fps: float = 10, + video_codec: str = "libx264", + crf: int = 23, + preset: str = "medium", +) -> None: + """Write a ``(T, C, H, W)`` video to ``filename`` using ffmpeg (video-only, no audio).""" + video_np = video_to_uint8(video_tensor).permute(0, 2, 3, 1).detach().cpu().numpy() + _, H, W, _ = video_np.shape + + v_args = [ + "-f", + "rawvideo", + "-vcodec", + "rawvideo", + "-s", + f"{W}x{H}", + "-pix_fmt", + "rgb24", + "-r", + str(fps), + "-i", + "-", + ] + out_args = [ + "-vcodec", + video_codec, + "-preset", + preset, + "-crf", + str(crf), + "-pix_fmt", + "yuv420p", + ] + + cmd = ["ffmpeg", "-y", *v_args, *out_args, str(filename)] + res = subprocess.run(cmd, input=video_np.tobytes(), capture_output=True, timeout=120) + + if res.returncode: + raise RuntimeError(f"ffmpeg failed ({res.returncode}):\n{res.stderr.decode()}") + + +def write_video_gif( + filename: str | Path, + video_tensor: Tensor, + *, + source_fps: float, + target_fps: float = 4, + max_side: int = 640, +) -> None: + """Write a compact GIF for trackers that do not accept MP4 (notably SwanLab). + + The original MP4 remains the archival visualization. This helper temporally subsamples and + spatially downsizes only the cloud copy so periodic uploads stay reasonably small. + """ + if source_fps <= 0 or target_fps <= 0: + raise ValueError("source_fps and target_fps must be positive") + if max_side <= 0: + raise ValueError("max_side must be positive") + + video = video_to_uint8(video_tensor).permute(0, 2, 3, 1).detach().cpu() + frame_count = video.shape[0] + output_frame_count = max(1, round(frame_count * min(1.0, target_fps / source_fps))) + indices = torch.linspace(0, frame_count - 1, output_frame_count).round().long().unique() + + frames: list[Image.Image] = [] + for index in indices: + frame = Image.fromarray(video[index].numpy(), mode="RGB") + if max(frame.size) > max_side: + frame.thumbnail((max_side, max_side), resample=Image.Resampling.LANCZOS) + frames.append(frame) + + effective_fps = min(source_fps, target_fps) + frames[0].save( + filename, + save_all=True, + append_images=frames[1:], + duration=max(1, round(1000 / effective_fps)), + loop=0, + optimize=True, + ) + + +class VideoForWandb(BaseModel): + """A video (with optional caption) to be logged to Weights & Biases.""" + + model_config = ConfigDict(arbitrary_types_allowed=True) + + video: Tensor + caption: str | None = None + + +@contextmanager +def videos_for_wandb(videos: dict[str, VideoForWandb], fps: float = 10) -> Iterator[dict]: + """Encode video tensors to temp mp4 files and yield ``wandb.Video`` objects. + + Creating ``wandb.Video`` from a video Tensor directly can hang in some cases and crash training. + Writing the video to a temporary file first and uploading that works reliably. + """ + import wandb # noqa: PLC0415 -- optional dep, used only here + + tmp_files: list[tempfile._TemporaryFileWrapper] = [] + try: + wandb_videos: dict[str, wandb.Video] = {} + for key, value in videos.items(): + video_tensor = videos_to_grid(value.video) + + f = tempfile.NamedTemporaryFile(suffix=".mp4", delete=True) + tmp_files.append(f) + write_video_ffmpeg(f.name, video_tensor.cpu(), fps=fps) + wandb_videos[key] = wandb.Video(f.name, format="mp4", caption=value.caption) + + yield wandb_videos + finally: + for f in tmp_files: + f.close() + + +def videos_to_grid(video: Tensor) -> Tensor: + """Arrange a batch of videos into a square-ish grid (wandb-style layout).""" + if video.ndim < 4: + raise ValueError("Video must be at least 4 dimensions: time, channels, height, width") + if video.ndim == 4: + video = video.unsqueeze(0) + b, t, c, h, w = video.shape + + if video.dtype != torch.uint8: + logging.warning("Converting video data to uint8") + video = video_to_uint8(video) + + def is_power2(num: int) -> bool: + return num != 0 and ((num & (num - 1)) == 0) + + # Pad to nearest power of 2, all at once. + if not is_power2(video.shape[0]): + len_addition = int(2 ** video.shape[0].bit_length() - video.shape[0]) + video = torch.cat( + (video, torch.zeros(len_addition, t, c, h, w, dtype=video.dtype, device=video.device)), + dim=0, + ) + + n_rows = 2 ** ((b.bit_length() - 1) // 2) + video = rearrange(video, "(n_rows n_cols) t c h w -> t c (n_rows h) (n_cols w)", n_rows=n_rows) + + return video + + +def visualize_batch(videos: Tensor, actions: ActionTensors, action_temporal_downsampling: int = 1) -> Tensor: + """Overlay a per-item keyboard HUD onto a batch of videos. + + Args: + videos: ``(B, T, C, H, W)`` videos (uint8, or floating point in ``[0, 1]``). + actions: Per-row :class:`ActionTensors`; only ``key_presses`` are drawn (RL is keyboard-only). + action_temporal_downsampling: Number of action steps per video frame. When ``> 1`` the action + stream is OR-pooled within each window so it lines up one-to-one with the video frames. + + Returns: + ``(B, T, C, H, W)`` uint8 videos with the keyboard overlay drawn in the top-right corner. + """ + if action_temporal_downsampling > 1: + d = action_temporal_downsampling + n = actions.key_presses.shape[1] // d * d # trim to a multiple of d + actions = actions.slice_time(0, n) + # OR the key presses across each window so a key held for any sub-step shows as pressed. + actions.key_presses = actions.key_presses.unflatten(1, (-1, d)).any(dim=2).int() + assert videos.shape[:2] == actions.key_presses.shape[:2], ( + f"Mismatch: {videos.shape[:2]=}, {actions.key_presses.shape[:2]=}" + ) + visualized_videos = [ + visualize_sample(videos[i], actions.slice_batch(i, i + 1)) for i in range(videos.shape[0]) + ] + return torch.stack(visualized_videos, dim=0) + + +def visualize_sample(video: Tensor, actions: ActionTensors) -> Tensor: + """Overlay a keyboard HUD onto a single ``(T, C, H, W)`` video (``actions`` has batch size 1).""" + video = video.clone().to("cpu") + + if video.dtype != torch.uint8: + video = torch.clamp(video, 0, 1) + video = (video * 255).to(torch.uint8) + + overlay_height = video.shape[2] // 4 + keyboard_overlay = draw_keyboard_video( + actions.key_presses[0].to("cpu"), + valid_keys=actions.config.valid_keys, + width=int(overlay_height * 2.5), + height=overlay_height, + fade_frames=1, + ) + return overlay_video(video, keyboard_overlay, corner="top-right", xpad=10, ypad=10, opacity=0.5) + + +def draw_keyboard_video( + key_presses: Tensor, + valid_keys: list[str], + width: int = 800, + height: int = 300, + background_color: tuple[int, int, int] = (0, 0, 0), + key_color: tuple[int, int, int] = (50, 50, 50), + pressed_color: tuple[int, int, int] = (100, 200, 255), + outline_width: int = 1, + fade_frames: int = 5, +) -> Tensor: + """Render keyboard key presses over time with a fade-out highlight. + + Draws the keyboard layout (:data:`LAYOUT`) and highlights keys when pressed; the highlight fades + out over ``fade_frames`` after release. Keys not in ``valid_keys`` are skipped, so any vocabulary + that is a subset of the layout renders in its natural position. + + Args: + key_presses: ``(T, num_keys)`` tensor of 0/1 press flags, columns aligned to ``valid_keys``. + valid_keys: Key names for the ``key_presses`` columns. + width: Frame width in pixels. + height: Frame height in pixels. + background_color: RGB background colour. + key_color: RGB fill for an unpressed key. + pressed_color: RGB fill for a freshly pressed key. + outline_width: Key outline width in pixels. + fade_frames: Number of frames over which the highlight fades after release. + + Returns: + ``(T, C, H, W)`` uint8 video of the keyboard. + """ + n_steps = key_presses.shape[0] + key_presses_np = key_presses.cpu().numpy() + num_keys = len(valid_keys) + + # Track the last frame each key was pressed for the fade-out effect. + last_pressed_frame = np.full(num_keys, -fade_frames - 1, dtype=np.int32) + + max_row_width_units = max(sum(width_mult for _, width_mult in row) for row in LAYOUT) + num_rows = len(LAYOUT) + + padding = 0.05 + gap_ratio = 0.02 + available_width = width * (1 - 2 * padding) + available_height = height * (1 - 2 * padding) + key_height = available_height / (num_rows + gap_ratio * (num_rows - 1)) + gap_height = key_height * gap_ratio + key_width_unit = available_width / (max_row_width_units + gap_ratio * (max_row_width_units - 1)) + gap_width = key_width_unit * gap_ratio + + # Build key positions from the layout. + key_positions: dict[str, dict[str, float]] = {} + y_pos = height * padding + for row in LAYOUT: + x_pos = width * padding + for key_name, width_mult in row: + key_width = key_width_unit * width_mult + key_positions[key_name] = {"x": x_pos, "y": y_pos, "width": key_width, "height": key_height} + x_pos += key_width + gap_width + y_pos += key_height + gap_height + + key_to_idx = {key: idx for idx, key in enumerate(valid_keys)} + + frames = [] + for t in range(n_steps): + for key_idx in range(num_keys): + if key_presses_np[t, key_idx] > 0: + last_pressed_frame[key_idx] = t + + img = Image.new("RGB", (width, height), background_color) + draw = ImageDraw.Draw(img) + + for key_name, pos in key_positions.items(): + if key_name not in key_to_idx: + continue + x, y = int(pos["x"]), int(pos["y"]) + w, h = int(pos["width"]), int(pos["height"]) + + frames_since_press = t - last_pressed_frame[key_to_idx[key_name]] + alpha = 1.0 - max(0, min(1, frames_since_press / fade_frames)) + faded_color = tuple( + int(bg * (1 - alpha) + pressed * alpha) for bg, pressed in zip(key_color, pressed_color) + ) + draw.rectangle([x, y, x + w, y + h], fill=faded_color, width=outline_width) + + text = DISPLAY_NAMES.get(key_name, key_name) + text_bbox = draw.textbbox((0, 0), text) + text_w, text_h = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1] + draw.text((x + (w - text_w) // 2, y + (h - text_h) // 2), text, fill=(255, 255, 255)) + + frames.append(torch.from_numpy(np.array(img, dtype=np.uint8)).permute(2, 0, 1)) + + return torch.stack(frames, dim=0) + + +def overlay_video( + main_video: Tensor, + overlay: Tensor, + xpad: int = 0, + ypad: int = 0, + corner: Literal["top-left", "top-right", "bottom-left", "bottom-right"] = "top-left", + opacity: float = 0.5, +) -> Tensor: + """Alpha-blend a smaller ``(T, C, h, w)`` overlay onto ``(T, C, H, W)`` at a chosen corner. + + Args: + main_video: The base video tensor ``(T, C, H, W)``. + overlay: The video to overlay ``(T, C, h, w)``. + xpad: Horizontal offset from the chosen corner. + ypad: Vertical offset from the chosen corner. + corner: One of ``"top-left"``, ``"top-right"``, ``"bottom-left"``, ``"bottom-right"``. + opacity: Blending factor (``1.0`` is fully opaque). + + Returns: + A new tensor with the overlay applied. + """ + res = main_video.clone() + _, _, H, W = main_video.shape + _, _, h, w = overlay.shape + + if corner == "top-left": + start_x, start_y = xpad, ypad + elif corner == "top-right": + start_x, start_y = W - w - xpad, ypad + elif corner == "bottom-left": + start_x, start_y = xpad, H - h - ypad + else: # bottom-right + start_x, start_y = W - w - xpad, H - h - ypad + + if opacity >= 1.0: + res[:, :, start_y : start_y + h, start_x : start_x + w] = overlay + else: + region = res[:, :, start_y : start_y + h, start_x : start_x + w] + blended = (1.0 - opacity) * region.float() + opacity * overlay.float() + res[:, :, start_y : start_y + h, start_x : start_x + w] = blended.to(res.dtype) + + return res + + +SPACING_FACTOR = 0.2 + +# Generic keyboard layout: each row is a list of ``[key_name, width_multiplier]`` pairs. Keys not in +# the active vocabulary are skipped at draw time, so the same layout serves any subset of keys. +LAYOUT = [ + [ + ["D1", 1], + ["D2", 1], + ["D3", 1], + ["D4", 1], + ["D5", 1], + ["LButton", 1.5], + ["RButton", 1.5], + ], + [ + ["Q", 1 - SPACING_FACTOR], + ["W", 1], + ["E", 1], + ["R", 1], + ["T", 1], + ], + [ + ["A", 1 + SPACING_FACTOR], + ["S", 1], + ["D", 1], + ["F", 1], + ["G", 1], + ["H", 1], + ], + [ + ["LShiftKey", 2 + SPACING_FACTOR], + ["Z", 1], + ["X", 1], + ["C", 1], + ["V", 1], + ["B", 1], + ], + [ + ["LControlKey", 1.25], + ["LWin", 1.25 + SPACING_FACTOR], + ["Space", 3], + ], +] + +# Short display labels for keys whose internal name is unwieldy. +DISPLAY_NAMES = { + "LShiftKey": "Shift", + "RShiftKey": "Shift", + "LControlKey": "Ctrl", + "RControlKey": "Ctrl", + "LWin": "Win", + "D0": "0", + "D1": "1", + "D2": "2", + "D3": "3", + "D4": "4", + "D5": "5", + "D6": "6", + "D7": "7", + "D8": "8", + "D9": "9", + "LButton": "LMB", + "RButton": "RMB", +} + + +def add_prediction_border( + video: Tensor, + context: int, + color: tuple = (128, 0, 32), + border: int = 4, + clone: bool = True, +) -> Tensor: + """Draw a coloured border around frames at index ``context`` onward (marks predicted frames).""" + video = video_to_uint8(video) + + video_output = video.clone() if clone else video + + c = rearrange(torch.tensor(color, device=video_output.device), "c -> c 1 1") + video_output[:, context:, :, :border, :] = c + video_output[:, context:, :, -border:, :] = c + video_output[:, context:, :, :, :border] = c + video_output[:, context:, :, :, -border:] = c + + return video_output diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/__init__.py b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c4fba3b21c51874be2e05d19938641c1daa59100 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/__init__.py @@ -0,0 +1 @@ +"""Executable training and artifact pipeline for BiHub World v6.""" diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/artifacts.py b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/artifacts.py new file mode 100644 index 0000000000000000000000000000000000000000..5b5867c08d5cd942bf23d6c0ec2ef28e8c86697c --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/artifacts.py @@ -0,0 +1,44 @@ +"""Content identity and atomic artifact helpers.""" + +from __future__ import annotations + +import hashlib +import json +import os +import tempfile +from pathlib import Path +from typing import Any + + +def sha256_file(path: str | Path, chunk_size: int = 16 * 1024 * 1024) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + while chunk := handle.read(chunk_size): + digest.update(chunk) + return digest.hexdigest() + + +def canonical_sha256(value: Any) -> str: + payload = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode() + return hashlib.sha256(payload).hexdigest() + + +def write_json_atomic(path: str | Path, value: Any) -> None: + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent) + try: + with os.fdopen(descriptor, "w", encoding="utf-8") as handle: + json.dump(value, handle, indent=2, ensure_ascii=False, sort_keys=True) + handle.write("\n") + handle.flush() + os.fsync(handle.fileno()) + os.replace(name, path) + finally: + Path(name).unlink(missing_ok=True) + + +def require_sha(path: str | Path, expected: str, label: str) -> None: + actual = sha256_file(path) + if actual != expected: + raise ValueError(f"{label} SHA mismatch: expected {expected}, got {actual}") diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/audit_anchor_cache.py b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/audit_anchor_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..dd9a6717d905fdf9023c02aa3b645f81994c8de7 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/audit_anchor_cache.py @@ -0,0 +1,184 @@ +"""Fail-closed anchor-cache count/hash/finite/join/online-parity audit.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np +import torch +from safetensors.torch import load_file +from torch.utils.data import DataLoader, Subset + +from mira.data.world_v6 import ANCHOR_ELEMENTS, ANCHOR_SHARDS, WorldV6Dataset, collate_world_v6 +from mira.training.world_v6.artifacts import sha256_file, write_json_atomic +from mira.training.world_v6.config import load_config +from mira.world_v6.current_resampler import CurrentQueryResampler +from mira.world_v6.qwen_current_anchor import FrozenQwenCurrentLanes + + +def _audit_shards(root: Path, identity: dict) -> dict: + output = {} + for split in ("train", "val"): + seen: set[str] = set() + finite = 0 + elements = 0 + norm_sum = 0.0 + norm_count = 0 + split_identity = identity["splits"][split] + split_root = root / split + total_rows = 0 + for shard in range(ANCHOR_SHARDS): + metadata = split_identity["shards"][str(shard)] + rows = int(metadata["rows"]) + tensor_path = split_root / f"shard-{shard:02d}.bf16" + index_path = split_root / f"shard-{shard:02d}.index.jsonl" + if tensor_path.stat().st_size != rows * ANCHOR_ELEMENTS * 2: + raise ValueError(f"Anchor shard {split}/{shard} byte count mismatch") + if sha256_file(tensor_path) != metadata["sha256"]: + raise ValueError(f"Anchor shard {split}/{shard} SHA mismatch") + if sha256_file(index_path) != metadata["index_sha256"]: + raise ValueError(f"Anchor index {split}/{shard} SHA mismatch") + with index_path.open(encoding="utf-8") as handle: + for expected_row, line in enumerate(handle): + item = json.loads(line) + if int(item["row"]) != expected_row: + raise ValueError("Anchor index row order is not contiguous") + if item["window_id"] in seen: + raise ValueError("Duplicate window id in anchor cache") + seen.add(item["window_id"]) + if rows: + tensor = torch.from_file( + str(tensor_path), + shared=False, + size=rows * ANCHOR_ELEMENTS, + dtype=torch.bfloat16, + ).reshape(rows, 3, 8, 512) + for chunk in tensor.split(4096): + value = chunk.float() + finite += int(torch.isfinite(value).sum()) + elements += value.numel() + norms = value.norm(dim=-1) + norm_sum += float(norms.sum()) + norm_count += norms.numel() + total_rows += rows + if total_rows != int(split_identity["windows"]) or len(seen) != total_rows: + raise ValueError(f"Anchor cache {split} join is not bijective") + if finite != elements: + raise ValueError(f"Anchor cache {split} contains NaN/Inf") + output[split] = { + "rows": total_rows, + "unique_window_ids": len(seen), + "finite_rate": finite / max(1, elements), + "mean_query_norm": norm_sum / max(1, norm_count), + } + return output + + +@torch.inference_mode() +def _parity(config, device: torch.device) -> dict: + dataset = WorldV6Dataset( + source_manifest=config.artifacts.val_source_manifest, + window_manifest=config.artifacts.val_window_manifest, + window_index=config.artifacts.val_window_index, + dataset_stats=config.artifacts.dataset_stats, + dataset_root=config.artifacts.raw_dataset_root, + anchors_root=config.artifacts.anchor_cache_root, + need_rgb=True, + extracted_episode_root=config.artifacts.extracted_rgb_root, + episode_cache_size=config.data.episode_cache_size, + ) + requested = min(200, len(dataset)) + indices = np.unique(np.linspace(0, len(dataset) - 1, requested, dtype=np.int64)).tolist() + loader = DataLoader( + Subset(dataset, indices), + batch_size=config.distributed.per_device_batch, + shuffle=False, + num_workers=0, + collate_fn=collate_world_v6, + ) + qwen = FrozenQwenCurrentLanes( + config.artifacts.qwen_root, config.artifacts.qwen_identity, device=device + ) + anchor = config.model.anchor + resampler = CurrentQueryResampler( + qwen_hidden_size=anchor.qwen_hidden_size, + queries_per_view=anchor.queries_per_view, + width=anchor.width, + heads=anchor.heads, + ffn_hidden=anchor.ffn_hidden, + gate_init=anchor.gate_init, + ).to(device) + selection = json.loads(Path(config.artifacts.resampler_selection).read_text(encoding="utf-8")) + resampler.load_state_dict(load_file(selection["weights"], device=str(device)), strict=True) + resampler.eval().requires_grad_(False) + cosine_sum = 0.0 + absolute_sum = 0.0 + maximum = 0.0 + values = 0 + repeated_identical = True + for batch, metadata in loader: + assert batch.obs_last_lgr is not None and batch.anchors is not None + hidden, mask = qwen( + batch.obs_last_lgr, [str(item["instruction"]) for item in metadata] + ) + with torch.autocast("cuda", dtype=torch.bfloat16): + online = resampler(hidden, mask).to(torch.bfloat16) + repeated = resampler(hidden, mask).to(torch.bfloat16) + repeated_identical &= bool(torch.equal(online, repeated)) + cached = batch.anchors.to(device) + online_float = online.float() + cached_float = cached.float() + cosine = torch.nn.functional.cosine_similarity(online_float, cached_float, dim=-1) + difference = (online_float - cached_float).abs() + cosine_sum += float(cosine.sum()) + absolute_sum += float(difference.sum()) + maximum = max(maximum, float(difference.max())) + values += online.numel() + mean_cosine = cosine_sum / (values / 512) + mae = absolute_sum / values + if mean_cosine < 0.9999 or mae > 2.0e-3 or not repeated_identical: + raise ValueError( + f"Anchor online/cache parity failed: cosine={mean_cosine}, mae={mae}, " + f"deterministic={repeated_identical}" + ) + return { + "windows": len(indices), + "mean_cosine_similarity": mean_cosine, + "mean_absolute_error": mae, + "max_absolute_error": maximum, + "deterministic_regeneration": repeated_identical, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", required=True) + parser.add_argument("--report") + parser.add_argument("overrides", nargs="*") + args = parser.parse_args() + config = load_config(args.config, args.overrides) + identity_path = Path(config.artifacts.anchor_cache_identity).expanduser().resolve() + identity = json.loads(identity_path.read_text(encoding="utf-8")) + if not identity.get("complete"): + raise ValueError("Anchor cache identity is not complete") + root = Path(config.artifacts.anchor_cache_root).expanduser().resolve() + report = { + "format_version": 1, + "passed": True, + "anchor_cache_identity_sha256": sha256_file(identity_path), + "shards": _audit_shards(root, identity), + "online_parity": _parity(config, torch.device("cuda", 0)), + } + output = ( + Path(args.report) + if args.report + else root / "anchor_cache_audit.json" + ) + write_json_atomic(output, report) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/build_anchor_cache.py b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/build_anchor_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..b83dc1946f958d2afb0f76e84ce23717b073dda6 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/build_anchor_cache.py @@ -0,0 +1,293 @@ +"""Distributed, resumable generation of eight stable BF16 current-anchor shards.""" + +from __future__ import annotations + +import argparse +import json +import os +import shutil +import time +from pathlib import Path +from typing import Any + +import torch +import torch.distributed as dist +from safetensors.torch import load_file +from torch.utils.data import DataLoader, Sampler + +from mira.data.world_v6 import ( + ANCHOR_SHARDS, + RGB_PREPROCESS_IDENTITY, + WorldV6Dataset, + collate_world_v6, + set_world_v6_process_name, +) +from mira.training.distributed import set_up_distributed +from mira.training.world_v6.artifacts import canonical_sha256, sha256_file, write_json_atomic +from mira.training.world_v6.config import load_config +from mira.world_v6.current_resampler import CurrentQueryResampler +from mira.world_v6.qwen_current_anchor import FrozenQwenCurrentLanes + + +class IndexSampler(Sampler[int]): + def __init__(self, values: list[int]) -> None: + self.values = values + + def __iter__(self): + yield from self.values + + def __len__(self) -> int: + return len(self.values) + + +def _assigned_indices(locator_path: str | Path, rank: int, world_size: int) -> list[int]: + path = Path(locator_path) + count = path.stat().st_size // 8 + locators = torch.from_file(str(path), shared=False, size=count, dtype=torch.int64) + return [ + index + for index, locator in enumerate(locators.tolist()) + if ((locator >> 56) % world_size) == rank + ] + + +def _complete_shard(path: Path, expected_rows: int, identity: dict[str, Any]) -> bool: + metadata_path = path.with_suffix(".json") + if not path.is_file() or not metadata_path.is_file(): + return False + metadata = json.loads(metadata_path.read_text(encoding="utf-8")) + return ( + int(metadata.get("rows", -1)) == expected_rows + and metadata.get("bytes") == path.stat().st_size + and metadata.get("sha256") == sha256_file(path) + and metadata.get("build_identity") == identity + ) + + +def _split_paths(config, split: str) -> tuple[str, str, str, str]: + if split == "train": + return ( + config.artifacts.train_source_manifest, + config.artifacts.train_window_manifest, + config.artifacts.train_window_index, + config.artifacts.train_window_locator, + ) + return ( + config.artifacts.val_source_manifest, + config.artifacts.val_window_manifest, + config.artifacts.val_window_index, + config.artifacts.val_window_locator, + ) + + +def _build_split(config, split: str, qwen, resampler, rank: int, world_size: int, device) -> None: + source, manifest, source_index, locator_path = _split_paths(config, split) + summary = json.loads(Path(config.artifacts.window_summary).read_text(encoding="utf-8")) + split_summary = summary["splits"][split] + split_root = Path(config.artifacts.anchor_cache_root).expanduser().resolve() / split + split_root.mkdir(parents=True, exist_ok=True) + selection = json.loads(Path(config.artifacts.resampler_selection).read_text(encoding="utf-8")) + build_identity = { + "window_manifest_sha256": split_summary["manifest_sha256"], + "qwen_identity_sha256": sha256_file(config.artifacts.qwen_identity), + "resampler_sha256": selection["weights_sha256"], + "rgb_preprocess_sha256": canonical_sha256(RGB_PREPROCESS_IDENTITY), + "dtype": "bfloat16", + } + assigned_shards = [shard for shard in range(ANCHOR_SHARDS) if shard % world_size == rank] + pending_shards = [ + shard + for shard in assigned_shards + if not _complete_shard( + split_root / f"shard-{shard:02d}.bf16", + int(split_summary["shard_rows"][str(shard)]), + build_identity, + ) + ] + if not pending_shards: + return + assigned = _assigned_indices(locator_path, rank, world_size) + dataset = WorldV6Dataset( + source_manifest=source, + window_manifest=manifest, + window_index=source_index, + dataset_stats=config.artifacts.dataset_stats, + dataset_root=config.artifacts.raw_dataset_root, + need_rgb=True, + extracted_episode_root=config.artifacts.extracted_rgb_root, + episode_cache_size=config.data.episode_cache_size, + ) + loader = DataLoader( + dataset, + batch_size=config.distributed.per_device_batch, + sampler=IndexSampler(assigned), + num_workers=config.data.num_workers, + prefetch_factor=config.data.prefetch_factor if config.data.num_workers else None, + persistent_workers=config.data.num_workers > 0, + pin_memory=True, + collate_fn=collate_world_v6, + ) + temporary_files: dict[int, tuple[Path, Any, Any]] = {} + for shard in pending_shards: + final = split_root / f"shard-{shard:02d}.bf16" + temporary = final.with_name(f".{final.name}.rank{rank}.tmp") + index_temp = (split_root / f"shard-{shard:02d}.index.jsonl").with_name( + f".shard-{shard:02d}.index.rank{rank}.tmp" + ) + temporary_files[shard] = ( + temporary, + temporary.open("wb"), + index_temp.open("w", encoding="utf-8"), + ) + counts = {shard: 0 for shard in pending_shards} + started = time.monotonic() + processed = 0 + try: + for batch, metadata in loader: + assert batch.obs_last_lgr is not None + hidden, mask = qwen( + batch.obs_last_lgr, [str(item["instruction"]) for item in metadata] + ) + with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16): + anchors = resampler(hidden, mask).to(torch.bfloat16).cpu() + for value, item in zip(anchors, metadata): + identifier = str(item["window_id"]) + shard = int.from_bytes( + __import__("hashlib").sha256(identifier.encode()).digest()[:8], "big" + ) % ANCHOR_SHARDS + if shard not in temporary_files: + if shard in pending_shards: + raise RuntimeError("Assigned cache shard was not opened") + continue + _, tensor_handle, index_handle = temporary_files[shard] + tensor_handle.write(value.contiguous().view(torch.uint16).numpy().tobytes()) + index_handle.write( + json.dumps({"window_id": identifier, "row": counts[shard]}, sort_keys=True) + + "\n" + ) + counts[shard] += 1 + processed += 1 + if processed and processed % 100 == 0 and rank == 0: + elapsed = max(time.monotonic() - started, 1e-6) + print(f"anchor-cache {split}: {processed} rows, {processed / elapsed:.2f} windows/s") + finally: + for _, tensor_handle, index_handle in temporary_files.values(): + tensor_handle.flush() + os.fsync(tensor_handle.fileno()) + tensor_handle.close() + index_handle.flush() + os.fsync(index_handle.fileno()) + index_handle.close() + for shard, (temporary, _, _) in temporary_files.items(): + expected = int(split_summary["shard_rows"][str(shard)]) + if counts[shard] != expected: + raise RuntimeError( + f"Anchor shard {shard} row count {counts[shard]} differs from expected {expected}" + ) + final = split_root / f"shard-{shard:02d}.bf16" + index_temp = split_root / f".shard-{shard:02d}.index.rank{rank}.tmp" + index_final = split_root / f"shard-{shard:02d}.index.jsonl" + os.replace(temporary, final) + os.replace(index_temp, index_final) + metadata = { + "format_version": 1, + "shard": shard, + "rows": counts[shard], + "bytes": final.stat().st_size, + "sha256": sha256_file(final), + "index_sha256": sha256_file(index_final), + "build_identity": build_identity, + } + write_json_atomic(final.with_suffix(".json"), metadata) + if dist.is_initialized(): + dist.barrier() + if rank == 0: + shutil.copyfile(locator_path, split_root / ".locators.i64.tmp") + os.replace(split_root / ".locators.i64.tmp", split_root / "locators.i64") + shards = {} + for shard in range(ANCHOR_SHARDS): + metadata_path = split_root / f"shard-{shard:02d}.json" + if not metadata_path.is_file(): + raise RuntimeError(f"Missing completed cache shard {shard}") + shards[str(shard)] = json.loads(metadata_path.read_text(encoding="utf-8")) + complete = { + "format_version": 1, + "split": split, + "windows": int(split_summary["windows"]), + "window_manifest_sha256": split_summary["manifest_sha256"], + "locator_sha256": sha256_file(split_root / "locators.i64"), + "shards": shards, + } + write_json_atomic(split_root / "COMPLETE.json", complete) + if dist.is_initialized(): + dist.barrier() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", required=True) + parser.add_argument("overrides", nargs="*") + args = parser.parse_args() + config = load_config(args.config, args.overrides) + if config.runtime.phase != "cache": + raise ValueError("Anchor cache builder requires runtime.phase=cache") + settings = set_up_distributed() + rank, world_size = settings.rank, settings.world_size + device = torch.device("cuda", settings.device) + set_world_v6_process_name(f"syncnet_v6_c{rank}") + qwen = FrozenQwenCurrentLanes( + config.artifacts.qwen_root, config.artifacts.qwen_identity, device=device + ) + anchor_config = config.model.anchor + resampler = CurrentQueryResampler( + qwen_hidden_size=anchor_config.qwen_hidden_size, + queries_per_view=anchor_config.queries_per_view, + width=anchor_config.width, + heads=anchor_config.heads, + ffn_hidden=anchor_config.ffn_hidden, + gate_init=anchor_config.gate_init, + ).to(device) + selection = json.loads(Path(config.artifacts.resampler_selection).read_text(encoding="utf-8")) + resampler.load_state_dict(load_file(selection["weights"], device=str(device)), strict=True) + resampler.eval().requires_grad_(False) + for split in ("train", "val"): + _build_split(config, split, qwen, resampler, rank, world_size, device) + if rank == 0: + summary = json.loads(Path(config.artifacts.window_summary).read_text(encoding="utf-8")) + identity = { + "format_version": 1, + "complete": True, + "qwen_identity": config.artifacts.qwen_identity, + "qwen_identity_sha256": sha256_file(config.artifacts.qwen_identity), + "resampler_selection": config.artifacts.resampler_selection, + "resampler_selection_sha256": sha256_file(config.artifacts.resampler_selection), + "resampler_weights_sha256": selection["weights_sha256"], + "codec_sha256": config.artifacts.codec_sha256, + "camera_order": ["left", "global", "right"], + "rgb_preprocess": RGB_PREPROCESS_IDENTITY, + "rgb_preprocess_sha256": canonical_sha256(RGB_PREPROCESS_IDENTITY), + "dtype": "bfloat16", + "shape": [3, 8, 512], + "splits": { + split: json.loads( + ( + Path(config.artifacts.anchor_cache_root) + / split + / "COMPLETE.json" + ).read_text(encoding="utf-8") + ) + for split in ("train", "val") + }, + "window_summary_sha256": sha256_file(config.artifacts.window_summary), + "actual_window_counts": { + split: int(summary["splits"][split]["windows"]) for split in ("train", "val") + }, + } + write_json_atomic(config.artifacts.anchor_cache_identity, identity) + if dist.is_initialized(): + dist.barrier() + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/build_window_manifest.py b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/build_window_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..3f839e9f9d101f5d8fb33f683e67355ede9872be --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/build_window_manifest.py @@ -0,0 +1,187 @@ +"""Build the immutable v6 window join and compact source/cache locator indices.""" + +from __future__ import annotations + +import argparse +import bisect +import json +import os +from collections import Counter +from pathlib import Path + +import numpy as np + +from mira.data.robotwin_wam_schema import read_jsonl +from mira.data.world_v6 import ANCHOR_ELEMENTS, ANCHOR_SHARDS, anchor_shard, qwen_frame_indices, window_id +from mira.training.world_v6.artifacts import sha256_file, write_json_atomic + + +def _selected_indices(total: int, maximum: int | None) -> range | np.ndarray: + if maximum is None or maximum >= total: + return range(total) + if maximum < 1: + raise ValueError("max windows must be positive") + return np.unique(np.linspace(0, total - 1, maximum, dtype=np.int64)) + + +def _build_split(source_manifest: Path, output_root: Path, split: str, maximum: int | None) -> dict: + rows = read_jsonl(source_manifest) + counts = [int(row["n_latents"]) - 19 for row in rows] + cumulative = [0] + for count in counts: + if count <= 0: + raise ValueError("Source latent manifest contains an incomplete v6 window") + cumulative.append(cumulative[-1] + count) + selected = _selected_indices(cumulative[-1], maximum) + manifest = output_root / f"{split}.jsonl" + source_index_path = output_root / f"{split}.source_index.i64" + locator_path = output_root / f"{split}.locators.i64" + temporary_manifest = manifest.with_suffix(".jsonl.tmp") + temporary_source = source_index_path.with_suffix(".tmp") + temporary_locator = locator_path.with_suffix(".tmp") + shard_rows = [0] * ANCHOR_SHARDS + distribution: Counter[str] = Counter() + with ( + temporary_manifest.open("w", encoding="utf-8") as manifest_handle, + temporary_source.open("wb") as source_handle, + temporary_locator.open("wb") as locator_handle, + ): + for global_index_value in selected: + global_index = int(global_index_value) + episode = bisect.bisect_right(cumulative, global_index) - 1 + latent_start = global_index - cumulative[episode] + source = rows[episode] + identifier = window_id(str(source["episode_sha256"]), latent_start) + shard = anchor_shard(identifier) + cache_row = shard_rows[shard] + shard_rows[shard] += 1 + rgb20, source30 = qwen_frame_indices(latent_start) + if source30 >= int(source["n_source_frames"]): + raise RuntimeError("Qwen current source index crosses into an invalid frame") + value = { + "format_version": 1, + "window_id": identifier, + "split": split, + "global_source_index": global_index, + "episode_sha256": source["episode_sha256"], + "task": source["task"], + "domain": source["domain"], + "archive": source["archive"], + "member": source["member"], + "cache_path": source["cache_path"], + "instruction": source["instruction"], + "instruction_sha256": source["instruction_sha256"], + "context_start_latent": latent_start, + "qwen_rgb20_index": rgb20, + "qwen_source_index_30hz": source30, + "latent_history_indices": list(range(latent_start + 6, latent_start + 10)), + "future_latent_indices": list(range(latent_start + 10, latent_start + 20)), + "anchor_cache_shard": shard, + "anchor_cache_row": cache_row, + } + manifest_handle.write(json.dumps(value, sort_keys=True) + "\n") + np.asarray([global_index], dtype=" None: + parser = argparse.ArgumentParser() + parser.add_argument("--train-source-manifest", required=True) + parser.add_argument("--val-source-manifest", required=True) + parser.add_argument("--output-root", required=True) + parser.add_argument("--max-windows-per-split", type=int) + args = parser.parse_args() + output = Path(args.output_root).expanduser().resolve() + output.mkdir(parents=True, exist_ok=True) + summary_path = output / "summary.json" + managed = [ + summary_path, + *(output / f"{split}{suffix}" for split in ("train", "val") for suffix in ( + ".jsonl", ".source_index.i64", ".locators.i64" + )), + ] + if summary_path.is_file(): + existing = json.loads(summary_path.read_text(encoding="utf-8")) + for split, source_name in ( + ("train", args.train_source_manifest), + ("val", args.val_source_manifest), + ): + source = Path(source_name).expanduser().resolve() + info = existing["splits"][split] + expected_windows = int(info["source_total_windows"]) + if args.max_windows_per_split is not None: + expected_windows = min(expected_windows, args.max_windows_per_split) + expected = { + "source_manifest_sha256": sha256_file(source), + "windows": expected_windows, + "bounded": expected_windows != int(info["source_total_windows"]), + } + for key, value in expected.items(): + if info.get(key) != value: + raise RuntimeError( + f"Existing World v6 {split} window identity differs at {key}; " + "refusing to overwrite" + ) + for key in ("manifest", "source_index", "locator"): + path = Path(info[key]).resolve() + if not path.is_file() or path.parent != output: + raise RuntimeError(f"Incomplete World v6 window artifact: {path}") + if sha256_file(path) != info[f"{key}_sha256"]: + raise RuntimeError(f"World v6 window artifact SHA changed: {path}") + print(json.dumps({"status": "already_complete", **existing}, indent=2)) + return + if any(path.exists() for path in managed): + raise RuntimeError("Incomplete World v6 window artifacts exist; refusing to overwrite") + splits = { + split: _build_split(Path(manifest).resolve(), output, split, args.max_windows_per_split) + for split, manifest in ( + ("train", args.train_source_manifest), + ("val", args.val_source_manifest), + ) + } + train_episodes = {row["episode_sha256"] for row in read_jsonl(args.train_source_manifest)} + val_episodes = {row["episode_sha256"] for row in read_jsonl(args.val_source_manifest)} + if train_episodes & val_episodes: + raise RuntimeError("Train/validation episode leakage in source manifests") + summary = { + "format_version": 1, + "view_order": ["left", "global", "right"], + "context_latents": 10, + "future_latents": 10, + "history_latents": 4, + "qwen_current_rgb20_offset": 19, + "anchor_shards": ANCHOR_SHARDS, + "split_overlap": 0, + "splits": splits, + } + write_json_atomic(summary_path, summary) + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/checkpoint.py b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..584a221e07a56759d3ffa63a45e9ae907f67697e --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/checkpoint.py @@ -0,0 +1,198 @@ +"""Atomic FSDP2/DCP World v6 checkpoints with exact sampler and RNG recovery.""" + +from __future__ import annotations + +import json +import os +import random +import shutil +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import torch.distributed as dist +import torch.distributed.checkpoint as dcp +from safetensors.torch import save_file +from torch.distributed.checkpoint.state_dict import ( + StateDictOptions, + get_model_state_dict, + get_state_dict, + set_state_dict, +) +from torch.distributed.tensor import DTensor + +from mira.training.ema import ModelEMA +from mira.training.world_v6.artifacts import canonical_sha256 + + +def _barrier() -> None: + if dist.is_available() and dist.is_initialized(): + dist.barrier() + + +def _complete_checkpoints(root: str | Path, phase: str) -> list[tuple[int, Path]]: + """Return canonical, complete checkpoints without touching named backups. + + Operators may keep manual copies such as ``main-checkpoint-55000_resume`` + beside recovery checkpoints. Only directories whose suffix is entirely + numeric belong to the automatic resume and retention policy. + """ + candidates = [] + for path in Path(root).glob(f"{phase}-checkpoint-*"): + marker = path / "trainer_state.json" + if not marker.is_file(): + continue + suffix = path.name.rsplit("-", 1)[1] + if not suffix.isdecimal(): + continue + step = int(suffix) + candidates.append((step, path)) + return sorted(candidates, key=lambda item: item[0]) + + +def latest_checkpoint(root: str | Path, phase: str) -> Path | None: + candidates = _complete_checkpoints(root, phase) + return candidates[-1][1] if candidates else None + + +def preserved_checkpoint_steps(resolved_config: dict[str, Any], phase: str) -> set[int]: + """Return the phase-specific checkpoints that retention must never prune.""" + section = "bootstrap" if phase == "bootstrap" else "checkpoint" + return {int(step) for step in resolved_config[section].get("preserve_steps", [])} + + +def _full_ema_tensor(value: torch.Tensor) -> torch.Tensor: + if isinstance(value, DTensor): + return value.full_tensor().detach().cpu().contiguous() + return value.detach().cpu().contiguous() + + +def _export_bootstrap_resampler( + temporary: Path, model: torch.nn.Module, ema: ModelEMA, rank: int +) -> None: + full = get_model_state_dict( + model, + options=StateDictOptions(full_state_dict=True, cpu_offload=True), + ) + online = { + name.removeprefix("current_resampler."): value.contiguous() + for name, value in full.items() + if name.startswith("current_resampler.") and isinstance(value, torch.Tensor) + } + ema_values = {} + for name, value in sorted(ema.state.items()): + if name.startswith("current_resampler."): + ema_values[name.removeprefix("current_resampler.")] = _full_ema_tensor(value) + if rank == 0: + save_file(online, temporary / "resampler-online.safetensors") + save_file(ema_values, temporary / "resampler-ema.safetensors") + + +def save_checkpoint( + root: str | Path, + *, + phase: str, + completed_steps: int, + model: torch.nn.Module, + optimizer: torch.optim.Optimizer, + scheduler: Any, + ema: ModelEMA, + sampler: Any, + resolved_config: dict[str, Any], + artifact_identity: dict[str, Any], + metrics: dict[str, Any], + keep_recent: int, +) -> Path: + rank = dist.get_rank() if dist.is_initialized() else 0 + root = Path(root) + final = root / f"{phase}-checkpoint-{completed_steps}" + temporary = root / f".{final.name}.tmp" + if rank == 0: + root.mkdir(parents=True, exist_ok=True) + if temporary.exists(): + shutil.rmtree(temporary) + temporary.mkdir(parents=True) + _barrier() + model_state, optimizer_state = get_state_dict(model, optimizer) + dcp.save( + {"model": model_state, "optimizer": optimizer_state, "ema": ema.state_dict()}, + checkpoint_id=temporary / "distributed", + ) + torch.save( + { + "scheduler": scheduler.state_dict(), + "sampler": sampler.state_dict(), + "python_rng": random.getstate(), + "numpy_rng": np.random.get_state(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state() if torch.cuda.is_available() else None, + }, + temporary / f"rank-{rank:05d}.pth", + ) + if phase == "bootstrap": + _export_bootstrap_resampler(temporary, model, ema, rank) + _barrier() + if rank == 0: + state = { + "format_version": 1, + "phase": phase, + "completed_steps": completed_steps, + "next_step": completed_steps, + "artifact_identity": artifact_identity, + "artifact_identity_sha256": canonical_sha256(artifact_identity), + "resolved_config": resolved_config, + "metrics": metrics, + } + (temporary / "trainer_state.json").write_text( + json.dumps(state, indent=2, default=str) + "\n", encoding="utf-8" + ) + if final.exists(): + shutil.rmtree(final) + os.replace(temporary, final) + checkpoints = _complete_checkpoints(root, phase) + preserved = preserved_checkpoint_steps(resolved_config, phase) + removable = [(step, path) for step, path in checkpoints if step not in preserved] + for _, path in removable[:-keep_recent]: + shutil.rmtree(path) + _barrier() + return final + + +def load_checkpoint( + checkpoint: str | Path, + *, + model: torch.nn.Module, + optimizer: torch.optim.Optimizer, + scheduler: Any, + ema: ModelEMA, + sampler: Any, + expected_artifact_identity: dict[str, Any], +) -> int: + rank = dist.get_rank() if dist.is_initialized() else 0 + checkpoint = Path(checkpoint) + metadata = json.loads((checkpoint / "trainer_state.json").read_text(encoding="utf-8")) + if metadata["artifact_identity_sha256"] != canonical_sha256(expected_artifact_identity): + raise ValueError("World v6 resume artifact identity changed") + model_state, optimizer_state = get_state_dict(model, optimizer) + state = {"model": model_state, "optimizer": optimizer_state, "ema": ema.state_dict()} + dcp.load(state, checkpoint_id=checkpoint / "distributed") + set_state_dict( + model, + optimizer, + model_state_dict=state["model"], + optim_state_dict=state["optimizer"], + ) + ema.load_state_dict(state["ema"]) + rank_state = torch.load( + checkpoint / f"rank-{rank:05d}.pth", map_location="cpu", weights_only=False + ) + scheduler.load_state_dict(rank_state["scheduler"]) + sampler.load_state_dict(rank_state["sampler"]) + random.setstate(rank_state["python_rng"]) + np.random.set_state(rank_state["numpy_rng"]) + torch.set_rng_state(rank_state["torch_rng"]) + if torch.cuda.is_available() and rank_state["cuda_rng"] is not None: + torch.cuda.set_rng_state(rank_state["cuda_rng"]) + _barrier() + return int(metadata["next_step"]) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/config.py b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/config.py new file mode 100644 index 0000000000000000000000000000000000000000..e74bfa010224dfc68d2d1c04b80866001b29c873 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/config.py @@ -0,0 +1,205 @@ +"""Strict phase-aware configuration loader for World v6.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Literal + +from omegaconf import OmegaConf +from pydantic import BaseModel, ConfigDict, model_validator + +from mira.world_v6.config import WorldV6ModelConfig + + +class StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class ExperimentConfig(StrictModel): + name: str = "robotwin_bihub_world_v6" + seed: int = 2026 + output_root: str + artifact_root: str + debug_smoke: bool = False + + +class ArtifactConfig(StrictModel): + codec_checkpoint: str + codec_sha256: str + codec_config_sha256: str + latent_cache_root: str + train_source_manifest: str + val_source_manifest: str + dataset_stats: str + raw_dataset_root: str + extracted_rgb_root: str + train_window_manifest: str + val_window_manifest: str + train_window_index: str + val_window_index: str + train_window_locator: str + val_window_locator: str + window_summary: str + source_checkpoint: str + source_selection_import: str + source_selection: str + migration_weights: str + migration_report: str + qwen_root: str + qwen_identity: str + resampler_selection: str + anchor_cache_root: str + anchor_cache_identity: str + main_checkpoint_root: str + + +class QwenConfig(StrictModel): + repo: str = "Qwen/Qwen3-VL-2B-Instruct" + revision: str + dtype: Literal["bfloat16"] = "bfloat16" + attention_implementation: Literal["sdpa"] = "sdpa" + image_height: int = 288 + image_width: int = 384 + prompt_version: Literal["bihub-v6-role-v1"] = "bihub-v6-role-v1" + add_generation_prompt: Literal[False] = False + frozen: Literal[True] = True + + +class DataConfig(StrictModel): + view_order: list[str] = ["left", "global", "right"] + source_fps: int = 30 + video_fps: int = 20 + latent_fps: int = 10 + clean_probability: float = 0.5 + num_workers: int = 2 + prefetch_factor: int = 2 + episode_cache_size: int = 2 + + +class DistributedConfig(StrictModel): + strategy: Literal["fsdp2_full_shard"] = "fsdp2_full_shard" + per_device_batch: int = 1 + gradient_accumulation_steps: int = 4 + effective_global_batch: int = 32 + precision: Literal["bf16"] = "bf16" + + +class OptimizerConfig(StrictModel): + betas: list[float] = [0.9, 0.99] + eps: float = 1.0e-8 + weight_decay: float = 0.1 + grad_clip: float = 1.0 + ema_decay: float = 0.9999 + + +class BootstrapConfig(StrictModel): + steps: int = 5000 + warmup_steps: int = 500 + lr_resampler: float = 2.0e-4 + lr_hhr_world_cross: float = 1.0e-4 + lr_state_adapter: float = 5.0e-5 + preserve_steps: list[int] = [1000, 3000, 5000] + + +class MainTrainingConfig(StrictModel): + steps: int = 100000 + warmup_steps: int = 2000 + inherited_unfreeze_step: int = 2000 + inherited_unfreeze_ramp: int = 500 + lr_new: float = 1.0e-4 + lr_inherited: float = 2.0e-5 + min_lr_new: float = 1.0e-6 + min_lr_inherited: float = 2.0e-7 + + +class ValidationConfig(StrictModel): + every_steps: int = 1000 + sample_every_steps: int = 5000 + fixed_seed: int = 2026 + batches: int = 16 + interventions: bool = True + + +class CheckpointConfig(StrictModel): + every_steps: int = 5000 + keep_last_recovery: int = 2 + preserve_steps: list[int] = [80000, 90000, 100000] + atomic: Literal[True] = True + auto_resume: bool = True + + +class LoggingConfig(StrictModel): + every_steps: int = 100 + early_steps: int = 10 + swanlab_enabled: bool = True + swanlab_project: str = "Multi_WAM" + swanlab_experiment_name: str = "RoboTwin-BiHub-World-v6" + swanlab_token_file: str + + +class RuntimeConfig(StrictModel): + phase: Literal["bootstrap", "cache", "main", "eval"] + mode: Literal["formal", "smoke", "overfit64", "canary"] = "formal" + max_steps: int | None = None + max_windows_per_split: int | None = None + + +class WorldV6RunConfig(StrictModel): + experiment: ExperimentConfig + artifacts: ArtifactConfig + qwen: QwenConfig + data: DataConfig = DataConfig() + model: WorldV6ModelConfig = WorldV6ModelConfig() + distributed: DistributedConfig = DistributedConfig() + optimizer: OptimizerConfig = OptimizerConfig() + bootstrap: BootstrapConfig = BootstrapConfig() + training: MainTrainingConfig = MainTrainingConfig() + validation: ValidationConfig = ValidationConfig() + checkpoint: CheckpointConfig = CheckpointConfig() + logging: LoggingConfig + runtime: RuntimeConfig + + @model_validator(mode="after") + def validate_formal_contract(self) -> "WorldV6RunConfig": + required_paths = self.artifacts.model_dump().values() + if any(str(value).strip() in {"", "REQUIRED"} for value in required_paths): + raise ValueError("Every artifact path and identity must be resolved before launch") + if self.data.view_order != ["left", "global", "right"]: + raise ValueError("World v6 camera order must be [left,global,right]") + if (self.data.source_fps, self.data.video_fps, self.data.latent_fps) != (30, 20, 10): + raise ValueError("World v6 timebase is locked to 30->20 RGB and 10Hz latent") + if self.optimizer.betas != [0.9, 0.99]: + raise ValueError("The first v6 run locks AdamW betas to (0.9,0.99)") + if not self.experiment.debug_smoke: + geometry = ( + self.model.hidden_size, + self.model.layers, + self.model.query_heads, + self.model.kv_heads, + ) + if geometry != (2048, 16, 16, 4): + raise ValueError(f"Formal v6 geometry must be 2048x16 16/4 GQA, got {geometry}") + if self.distributed.effective_global_batch != 32: + raise ValueError("Formal v6 optimization batch is locked to 32") + if self.bootstrap.steps != 5000 or self.training.steps != 100000: + raise ValueError("Formal v6 stages are locked to 5k bootstrap + 100k main") + if self.runtime.max_windows_per_split is not None: + raise ValueError("Formal v6 refuses a bounded window manifest") + return self + + +def _load_with_extends(path: Path): + value = OmegaConf.load(path) + parent = value.pop("extends", None) + if parent is None: + return value + parent_path = (path.parent / str(parent)).resolve() + return OmegaConf.merge(_load_with_extends(parent_path), value) + + +def load_config(path: str | Path, overrides: list[str] | None = None) -> WorldV6RunConfig: + value = _load_with_extends(Path(path).expanduser().resolve()) + if overrides: + value = OmegaConf.merge(value, OmegaConf.from_dotlist(overrides)) + resolved = OmegaConf.to_container(value, resolve=True) + return WorldV6RunConfig.model_validate(resolved) diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/eval_bootstrap_checkpoint.py b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/eval_bootstrap_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..abc11e3b83e81dc291f6ad78733d7d910b809834 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/eval_bootstrap_checkpoint.py @@ -0,0 +1,178 @@ +"""Read-only, fixed-noise evaluation for a World v6 bootstrap checkpoint.""" + +from __future__ import annotations + +import argparse +import json +import random +from contextlib import nullcontext +from pathlib import Path + +import numpy as np +import torch +import torch.distributed as dist +from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( + CheckpointImpl, + checkpoint_wrapper, +) +from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard + +from mira.data.world_v6 import WorldV6BalancedSampler, set_world_v6_process_name +from mira.training.distributed import set_up_distributed +from mira.training.ema import ModelEMA +from mira.training.world_v6.artifacts import write_json_atomic +from mira.training.world_v6.checkpoint import load_checkpoint +from mira.training.world_v6.config import WorldV6RunConfig, load_config +from mira.training.world_v6.train import ( + _artifact_identity, + _canonical_parameter_name, + _configure_trainable, + _dataset, + _fixed_validation, + _optimizer, + _scheduler, +) +from mira.world_v6.migration import load_migrated_system +from mira.world_v6.qwen_current_anchor import FrozenQwenCurrentLanes + + +def _passes_selection_gates(metrics: dict[str, float]) -> bool: + required = ( + "val/correct_recovered_clean_mse", + "val/null_recovered_clean_mse", + "val/shuffled_recovered_clean_mse", + "val/anchor_effective_rank", + "val/anchor_finite_rate", + ) + return ( + all(np.isfinite(metrics[name]) for name in required) + and metrics["val/correct_recovered_clean_mse"] + < metrics["val/null_recovered_clean_mse"] + and metrics["val/correct_recovered_clean_mse"] + < metrics["val/shuffled_recovered_clean_mse"] + and metrics["val/anchor_effective_rank"] > 1.5 + and metrics["val/anchor_finite_rate"] == 1.0 + ) + + +@torch.inference_mode() +def evaluate( + config: WorldV6RunConfig, + checkpoint: str | Path, + output: str | Path, +) -> None: + if config.runtime.phase != "bootstrap": + raise ValueError("Bootstrap checkpoint evaluation requires runtime.phase=bootstrap") + settings = set_up_distributed() + rank, world_size = settings.rank, settings.world_size + device = torch.device("cuda", settings.device) + set_world_v6_process_name(f"syncnet_v6_e{rank}") + seed = config.experiment.seed + rank + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + torch.backends.cuda.matmul.allow_tf32 = True + + system = load_migrated_system(config.artifacts.migration_weights, config.model) + _configure_trainable(system, "bootstrap") + system = system.to(device) + policy = MixedPrecisionPolicy( + param_dtype=torch.bfloat16, + reduce_dtype=torch.float32, + output_dtype=torch.bfloat16, + ) + if config.model.activation_checkpointing: + system.world_model.external_activation_checkpointing = True + for index, block in enumerate(system.world_model.blocks): + system.world_model.blocks[index] = checkpoint_wrapper( + block, + checkpoint_impl=CheckpointImpl.NO_REENTRANT, + preserve_rng_state=True, + ) + for block in system.world_model.blocks: + fully_shard(block, mp_policy=policy, reshard_after_forward=True) + fully_shard(system, mp_policy=policy, reshard_after_forward=True) + names = { + id(parameter): _canonical_parameter_name(name) + for name, parameter in system.named_parameters() + } + optimizer, _ = _optimizer(system, config, names) + scheduler = _scheduler(optimizer, config) + ema = ModelEMA(system, decay=config.optimizer.ema_decay, unbias=False) + train_dataset = _dataset(config, "train") + val_dataset = _dataset(config, "val") + sampler = WorldV6BalancedSampler( + train_dataset, + seed=config.experiment.seed, + rank=rank, + world_size=world_size, + clean_probability=config.data.clean_probability, + ) + checkpoint_path = Path(checkpoint).expanduser().resolve() + completed = load_checkpoint( + checkpoint_path, + model=system, + optimizer=optimizer, + scheduler=scheduler, + ema=ema, + sampler=sampler, + expected_artifact_identity=_artifact_identity(config), + ) + qwen = FrozenQwenCurrentLanes( + config.artifacts.qwen_root, + config.artifacts.qwen_identity, + device=device, + ) + system.eval() + qwen.eval() + branches: dict[str, dict[str, object]] = {} + for branch in ("online", "ema"): + context = nullcontext() if branch == "online" else ema.average_parameters() + with context: + metrics = _fixed_validation( + system, + qwen, + config, + val_dataset, + device=device, + rank=rank, + world_size=world_size, + completed=completed, + ) + branches[branch] = { + "metrics": metrics, + "passes_selection_gates": _passes_selection_gates(metrics), + } + report = { + "format_version": 1, + "checkpoint": str(checkpoint_path), + "completed_steps": completed, + "fixed_case_policy": "same_validation_indices_and_noise_across_checkpoints", + "fixed_seed": config.validation.fixed_seed, + "branches": branches, + } + if rank == 0: + write_json_atomic(Path(output).expanduser().resolve(), report) + print(json.dumps(report, indent=2)) + if dist.is_initialized(): + dist.barrier() + dist.destroy_process_group() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", required=True) + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("overrides", nargs="*") + args = parser.parse_args() + evaluate( + load_config(args.config, args.overrides), + checkpoint=args.checkpoint, + output=args.output, + ) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/eval_world_v6.py b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/eval_world_v6.py new file mode 100644 index 0000000000000000000000000000000000000000..fed5309e35ff0fd77c34c48e7b451fa886672850 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/eval_world_v6.py @@ -0,0 +1,202 @@ +"""Fixed online/EMA World v6 evaluation from a strict FSDP2 recovery checkpoint.""" + +from __future__ import annotations + +import argparse +import json +from contextlib import nullcontext +from pathlib import Path + +import numpy as np +import torch +import torch.distributed as dist +from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( + CheckpointImpl, + checkpoint_wrapper, +) +from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard +from torch.utils.data import DataLoader, Subset + +from mira.data.world_v6 import WorldV6BalancedSampler, collate_world_v6, set_world_v6_process_name +from mira.training.distributed import set_up_distributed +from mira.training.ema import ModelEMA +from mira.training.world_v6.artifacts import write_json_atomic +from mira.training.world_v6.checkpoint import latest_checkpoint, load_checkpoint +from mira.training.world_v6.config import load_config +from mira.training.world_v6.rollout import save_fixed_rollout +from mira.training.world_v6.train import ( + _artifact_identity, + _canonical_parameter_name, + _configure_trainable, + _dataset, + _fixed_validation, + _fixed_validation_seed, + _load_resampler_selection, + _optimizer, + _scheduler, +) +from mira.world_v6.migration import load_migrated_system + + +@torch.inference_mode() +def _history_interventions(system, config, dataset, device, rank, world_size, step) -> dict[str, float]: + total = min(len(dataset), config.distributed.per_device_batch * world_size) + indices = np.unique(np.linspace(0, len(dataset) - 1, total, dtype=np.int64))[rank::world_size] + loader = DataLoader( + Subset(dataset, indices.tolist()), + batch_size=config.distributed.per_device_batch, + shuffle=False, + num_workers=0, + collate_fn=collate_world_v6, + ) + sums = torch.zeros(5, dtype=torch.float64, device=device) + for batch_index, (batch, _) in enumerate(loader): + batch = batch.to(device) + assert batch.anchors is not None + generator = torch.Generator(device=device).manual_seed( + _fixed_validation_seed(config.validation.fixed_seed, batch_index) + ) + noise = torch.randn(batch.z_future_raw.shape, generator=generator, device=device) + tau = torch.rand((batch.z_future_raw.shape[0], 10, 1, 1, 1), generator=generator, device=device) + + def run(context, anchors): + with torch.autocast("cuda", dtype=torch.bfloat16): + return system( + z_context_raw=context, + z_future_raw=batch.z_future_raw, + anchors=anchors, + state_history=batch.state_history, + history_valid=batch.history_valid, + future_valid=batch.future_valid, + view_valid=batch.view_valid, + noise=noise, + tau_future=tau, + )["recovered_clean_mse"] + + current_repeated = batch.z_context_raw.clone() + current_repeated[:, :, -4:] = batch.z_context_raw[:, :, -1:] + history_reversed = batch.z_context_raw.clone() + history_reversed[:, :, -4:] = history_reversed[:, :, -4:].flip(2) + global_shuffled = batch.anchors.clone() + global_shuffled[:, 1] = ( + global_shuffled[:, 1].roll(1, dims=0) + if global_shuffled.shape[0] > 1 + else torch.zeros_like(global_shuffled[:, 1]) + ) + count = batch.z_context_raw.shape[0] + sums += torch.tensor( + [ + float(run(batch.z_context_raw, batch.anchors)) * count, + float(run(current_repeated, batch.anchors)) * count, + float(run(history_reversed, batch.anchors)) * count, + float(run(batch.z_context_raw, global_shuffled)) * count, + count, + ], + dtype=torch.float64, + device=device, + ) + if dist.is_initialized(): + dist.all_reduce(sums) + count = sums[-1].clamp_min(1) + return { + "correct_recovered_clean_mse": float(sums[0] / count), + "current_repeat_recovered_clean_mse": float(sums[1] / count), + "history_reverse_recovered_clean_mse": float(sums[2] / count), + "global_shuffle_recovered_clean_mse": float(sums[3] / count), + } + + +def evaluate(config, checkpoint_override: str | None = None) -> None: + settings = set_up_distributed() + rank, world_size = settings.rank, settings.world_size + device = torch.device("cuda", settings.device) + set_world_v6_process_name(f"syncnet_v6_e{rank}") + main_config = config.model_copy( + update={"runtime": config.runtime.model_copy(update={"phase": "main"})} + ) + checkpoint = ( + Path(checkpoint_override).expanduser().resolve() + if checkpoint_override + else latest_checkpoint(config.artifacts.main_checkpoint_root, "main") + ) + if checkpoint is None: + raise FileNotFoundError("No complete World v6 main checkpoint") + selection = json.loads(Path(config.artifacts.resampler_selection).read_text()) + system = load_migrated_system(selection["system_weights"], config.model) + _load_resampler_selection(system, config.artifacts.resampler_selection) + _configure_trainable(system, "main") + system = system.to(device) + policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32, output_dtype=torch.bfloat16) + if config.model.activation_checkpointing: + system.world_model.external_activation_checkpointing = True + for index, block in enumerate(system.world_model.blocks): + system.world_model.blocks[index] = checkpoint_wrapper( + block, checkpoint_impl=CheckpointImpl.NO_REENTRANT, preserve_rng_state=True + ) + for block in system.world_model.blocks: + fully_shard(block, mp_policy=policy, reshard_after_forward=True) + fully_shard(system, mp_policy=policy, reshard_after_forward=True) + names = {id(parameter): _canonical_parameter_name(name) for name, parameter in system.named_parameters()} + optimizer, _ = _optimizer(system, main_config, names) + scheduler = _scheduler(optimizer, main_config) + ema = ModelEMA(system, decay=config.optimizer.ema_decay, unbias=False) + dataset = _dataset(main_config, "val") + sampler = WorldV6BalancedSampler(dataset, seed=config.experiment.seed, rank=rank, world_size=world_size) + step = load_checkpoint( + checkpoint, + model=system, + optimizer=optimizer, + scheduler=scheduler, + ema=ema, + sampler=sampler, + expected_artifact_identity=_artifact_identity(main_config), + ) + system.eval() + report = {"format_version": 1, "passed": True, "checkpoint": str(checkpoint), "step": step, "branches": {}} + for branch in ("online", "ema"): + context = nullcontext() if branch == "online" else ema.average_parameters() + with context: + fixed = _fixed_validation( + system, None, main_config, dataset, device=device, rank=rank, + world_size=world_size, completed=step, + ) + interventions = _history_interventions( + system, main_config, dataset, device, rank, world_size, step + ) + rollout = save_fixed_rollout( + system, + dataset, + qwen=None, + output_root=config.experiment.output_root, + branch=branch, + completed=step, + seed=config.validation.fixed_seed, + device=device, + rank=rank, + world_size=world_size, + ) + report["branches"][branch] = { + "fixed": fixed, + "interventions": interventions, + "rollout": rollout, + } + if rank == 0: + output = Path(config.experiment.output_root) / "fixed_evaluation.json" + write_json_atomic(output, report) + print(json.dumps(report, indent=2)) + if dist.is_initialized(): + dist.barrier() + dist.destroy_process_group() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", required=True) + parser.add_argument("--checkpoint") + parser.add_argument("overrides", nargs="*") + args = parser.parse_args() + evaluate(load_config(args.config, args.overrides), args.checkpoint) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/migrate_checkpoint.py b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/migrate_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..e337412a8fa7e59b6b86cc6768d4f8ef5d6bb8a4 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/migrate_checkpoint.py @@ -0,0 +1,30 @@ +"""CLI for the explicit v5-to-v6 migration report and initialized state.""" + +from __future__ import annotations + +import argparse +import json + +from mira.training.world_v6.config import load_config +from mira.world_v6.migration import migrate_v5_checkpoint + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", required=True) + parser.add_argument("overrides", nargs="*") + args = parser.parse_args() + config = load_config(args.config, args.overrides) + artifacts = config.artifacts + report = migrate_v5_checkpoint( + checkpoint=artifacts.source_checkpoint, + source_selection=artifacts.source_selection, + config=config.model, + output_weights=artifacts.migration_weights, + output_report=artifacts.migration_report, + ) + print(json.dumps({"summary": report["summary"], "parameters": report["parameter_report"]}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/preflight.py b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/preflight.py new file mode 100644 index 0000000000000000000000000000000000000000..0a2dfd8c7cd20689cc1dcab7abd9b40017e86dcb --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/preflight.py @@ -0,0 +1,201 @@ +"""Phase-aware fail-closed artifact, environment, and capacity audit.""" + +from __future__ import annotations + +import argparse +import json +import os +import platform +import shutil +import subprocess +import sys +from pathlib import Path +from typing import Any + +import torch +import transformers + +from mira.data.robotwin_wam_schema import read_jsonl +from mira.data.world_v6 import RGB_PREPROCESS_IDENTITY +from mira.training.world_v6.artifacts import canonical_sha256, sha256_file, write_json_atomic +from mira.training.world_v6.config import load_config + + +def _require(path: str | Path, label: str) -> Path: + value = Path(path).expanduser().resolve() + if not value.is_file() and not value.is_dir(): + raise FileNotFoundError(f"Missing {label}: {value}") + return value + + +def _git_state(root: Path) -> dict[str, Any]: + try: + commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=root, text=True).strip() + status = subprocess.check_output(["git", "status", "--short"], cwd=root, text=True) + except (OSError, subprocess.CalledProcessError): + return {"commit": None, "dirty": None} + return {"commit": commit, "dirty": status.splitlines()} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", required=True) + parser.add_argument("--phase", choices=("bootstrap", "cache", "main", "eval")) + parser.add_argument("--report") + parser.add_argument("overrides", nargs="*") + args = parser.parse_args() + config = load_config(args.config, args.overrides) + phase = args.phase or config.runtime.phase + artifacts = config.artifacts + codec = _require(artifacts.codec_checkpoint, "codec checkpoint") + codec_config = codec.parents[1] / "codec_config.yaml" + if sha256_file(codec) != artifacts.codec_sha256: + raise ValueError("Codec checkpoint SHA differs from the frozen v6 contract") + if sha256_file(codec_config) != artifacts.codec_config_sha256: + raise ValueError("Codec resolved config SHA differs from the frozen v6 contract") + train_source = _require(artifacts.train_source_manifest, "train latent manifest") + val_source = _require(artifacts.val_source_manifest, "validation latent manifest") + window_summary_path = _require(artifacts.window_summary, "v6 window summary") + window_summary = json.loads(window_summary_path.read_text(encoding="utf-8")) + if ( + window_summary.get("view_order") != ["left", "global", "right"] + or window_summary.get("context_latents") != 10 + or window_summary.get("future_latents") != 10 + or window_summary.get("history_latents") != 4 + or window_summary.get("qwen_current_rgb20_offset") != 19 + ): + raise ValueError("World v6 window summary violates the frozen time/view contract") + for split, source in (("train", train_source), ("val", val_source)): + split_info = window_summary["splits"][split] + if split_info["source_manifest_sha256"] != sha256_file(source): + raise ValueError(f"{split} v6 join refers to a different latent manifest") + if not config.experiment.debug_smoke and split_info["bounded"]: + raise ValueError("Formal v6 refuses a bounded smoke window join") + if split_info["manifest_sha256"] != sha256_file( + artifacts.train_window_manifest if split == "train" else artifacts.val_window_manifest + ): + raise ValueError(f"{split} v6 window manifest identity changed") + train_rows = read_jsonl(train_source) + val_rows = read_jsonl(val_source) + if any( + row.get("state_semantics") != "simulator_drive_target_not_measured_qpos" + for row in train_rows + val_rows + ): + raise ValueError("Latent source contains ambiguous/non-drive-target state semantics") + train_episodes = {row["episode_sha256"] for row in train_rows} + val_episodes = {row["episode_sha256"] for row in val_rows} + if train_episodes & val_episodes: + raise ValueError("Episode leakage between train and validation") + qwen_identity_path = _require(artifacts.qwen_identity, "Qwen identity") + qwen_identity = json.loads(qwen_identity_path.read_text(encoding="utf-8")) + if qwen_identity["revision"] != config.qwen.revision: + raise ValueError("Qwen config revision differs from downloaded identity") + if qwen_identity["attention_implementation"] != config.qwen.attention_implementation: + raise ValueError("Qwen attention implementation differs from identity") + for relative, item in qwen_identity["files"].items(): + path = Path(artifacts.qwen_root) / relative + if not path.is_file() or path.stat().st_size != int(item["bytes"]): + raise ValueError(f"Qwen file missing/size mismatch: {relative}") + if sha256_file(path) != item["sha256"]: + raise ValueError(f"Qwen file SHA changed: {relative}") + source_selection_path = _require(artifacts.source_selection, "v5 source selection") + source_selection = json.loads(source_selection_path.read_text(encoding="utf-8")) + if Path(source_selection["checkpoint"]).resolve() != Path(artifacts.source_checkpoint).resolve(): + raise ValueError("v5 source selection points to a different checkpoint") + _require(artifacts.migration_weights, "v6 migration weights") + migration_report = json.loads(_require(artifacts.migration_report, "migration report").read_text()) + if migration_report["destination_weights_sha256"] != sha256_file(artifacts.migration_weights): + raise ValueError("Migrated v6 weights changed after the migration report") + if migration_report["required_core_missing"] or migration_report["summary"]["shape_mismatch"]: + raise ValueError("v6 migration has an unresolved core/mismatch entry") + if phase in {"cache", "main", "eval"}: + selection_path = _require(artifacts.resampler_selection, "frozen Resampler selection") + selection = json.loads(selection_path.read_text(encoding="utf-8")) + if selection["qwen_identity_sha256"] != sha256_file(qwen_identity_path): + raise ValueError("Frozen Resampler selection uses a different Qwen identity") + if sha256_file(selection["weights"]) != selection["weights_sha256"]: + raise ValueError("Frozen Resampler weights SHA changed") + if phase in {"main", "eval"}: + if sha256_file(selection["system_weights"]) != selection["system_weights_sha256"]: + raise ValueError("Selected bootstrap system initialization SHA changed") + if phase in {"main", "eval"}: + identity_path = _require(artifacts.anchor_cache_identity, "anchor cache identity") + identity = json.loads(identity_path.read_text(encoding="utf-8")) + if identity.get("complete") is not True: + raise ValueError("Anchor cache identity is not complete") + expected_cache = { + "qwen_identity_sha256": sha256_file(qwen_identity_path), + "resampler_selection_sha256": sha256_file(artifacts.resampler_selection), + "resampler_weights_sha256": selection["weights_sha256"], + "rgb_preprocess_sha256": canonical_sha256(RGB_PREPROCESS_IDENTITY), + } + for key, expected in expected_cache.items(): + if identity.get(key) != expected: + raise ValueError(f"Anchor cache identity differs at {key}") + for split in ("train", "val"): + cached_split = identity["splits"][split] + joined_split = window_summary["splits"][split] + if ( + int(cached_split["windows"]) != int(joined_split["windows"]) + or cached_split["window_manifest_sha256"] != joined_split["manifest_sha256"] + ): + raise ValueError(f"Anchor cache/window join identity changed for {split}") + usage = shutil.disk_usage(Path(config.experiment.artifact_root)) + train_windows = int(window_summary["splits"]["train"]["windows"]) + val_windows = int(window_summary["splits"]["val"]["windows"]) + anchor_bytes = (train_windows + val_windows) * 3 * 8 * 512 * 2 + # Dynamic hard budget: final anchors + 20% temporary + two full migration-sized recoveries +20%. + migration_bytes = Path(artifacts.migration_weights).stat().st_size + hard_required = int((anchor_bytes * 1.2 + 2 * migration_bytes) * 1.2) + if usage.free < hard_required: + raise RuntimeError( + f"Insufficient free storage: {usage.free} bytes free, {hard_required} required" + ) + report = { + "format_version": 1, + "passed": True, + "phase": phase, + "config": config.model_dump(mode="json"), + "identities": { + "codec_sha256": artifacts.codec_sha256, + "codec_config_sha256": artifacts.codec_config_sha256, + "train_source_manifest_sha256": sha256_file(train_source), + "val_source_manifest_sha256": sha256_file(val_source), + "window_summary_sha256": sha256_file(window_summary_path), + "qwen_identity_sha256": sha256_file(qwen_identity_path), + "migration_weights_sha256": sha256_file(artifacts.migration_weights), + }, + "actual_windows": {"train": train_windows, "val": val_windows}, + "anchor_capacity": { + "tensor_bytes": anchor_bytes, + "tensor_gib": anchor_bytes / 2**30, + "hard_required_bytes": hard_required, + "free_bytes": usage.free, + }, + "environment": { + "python": sys.version, + "platform": platform.platform(), + "torch": torch.__version__, + "cuda": torch.version.cuda, + "transformers": transformers.__version__, + "gpu_visible": os.environ.get("CUDA_VISIBLE_DEVICES"), + "flash_attention": None, + "qwen_attention": "sdpa", + }, + "documentation_conflicts": [ + "The two upper-level v6 design documents referenced by handoff are absent on server.", + "2,024,996 is latent-cell count, not legal window count; capacity uses actual joins.", + "The real v5 checkpoint used DDP/global-batch 256; v6 only migrates weights and uses its locked batch 32.", + "FlashAttention is unavailable; SDPA is pinned consistently for bootstrap/cache/deployment.", + "Delivered RoboTwin JPEGs are 240x320 although the plan states retained 288x384; " + "v6 pins one antialiased 4:3 resize to 288x384 before every Qwen path.", + ], + "source": _git_state(Path(__file__).resolve().parents[4]), + } + report_path = Path(args.report) if args.report else Path(config.experiment.artifact_root) / "reports" / f"preflight-{phase}.json" + write_json_atomic(report_path, report) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/prepare_qwen.py b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/prepare_qwen.py new file mode 100644 index 0000000000000000000000000000000000000000..f3f7bfa21cbf5ad63b48ce7187ee441a5426aad2 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/prepare_qwen.py @@ -0,0 +1,95 @@ +"""Direct-download and pin Qwen3-VL-2B into the workspace model directory.""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path + +import huggingface_hub +import torch +import transformers +from huggingface_hub import HfApi, snapshot_download + +from mira.training.world_v6.artifacts import sha256_file, write_json_atomic +from mira.world_v6.prompts import PROMPT_VERSION + +PROXY_NAMES = ( + "http_proxy", + "https_proxy", + "all_proxy", + "ftp_proxy", + "HTTP_PROXY", + "HTTPS_PROXY", + "ALL_PROXY", + "FTP_PROXY", +) + + +def assert_direct_connection() -> None: + configured = {name: os.environ[name] for name in PROXY_NAMES if os.environ.get(name)} + if configured: + raise RuntimeError(f"Proxy variables must be unset for the Qwen download: {sorted(configured)}") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", default="Qwen/Qwen3-VL-2B-Instruct") + parser.add_argument("--revision", default="main") + parser.add_argument("--local-dir", required=True) + parser.add_argument("--identity-file", required=True) + args = parser.parse_args() + assert_direct_connection() + local_root = Path(args.local_dir).expanduser().resolve() + local_root.parent.mkdir(parents=True, exist_ok=True) + info = HfApi().model_info(args.repo, revision=args.revision) + revision = str(info.sha) + snapshot_download( + repo_id=args.repo, + revision=revision, + local_dir=local_root, + resume_download=True, + ) + config = json.loads((local_root / "config.json").read_text(encoding="utf-8")) + architectures = config.get("architectures", []) + text_config = config.get("text_config", {}) + hidden_size = int(text_config.get("hidden_size", config.get("hidden_size", -1))) + if "Qwen3VLForConditionalGeneration" not in architectures or hidden_size != 2048: + raise ValueError( + f"Unexpected Qwen identity: architectures={architectures}, hidden_size={hidden_size}" + ) + files = { + path.relative_to(local_root).as_posix(): { + "bytes": path.stat().st_size, + "sha256": sha256_file(path), + } + for path in sorted(local_root.rglob("*")) + if path.is_file() and ".cache" not in path.parts + } + identity = { + "format_version": 1, + "repo": args.repo, + "revision": revision, + "local_root": str(local_root), + "architectures": architectures, + "text_hidden_size": hidden_size, + "attention_implementation": "sdpa", + "dtype": "bfloat16", + "prompt_version": PROMPT_VERSION, + "image_height": 288, + "image_width": 384, + "min_pixels": 288 * 384, + "max_pixels": 288 * 384, + "add_generation_prompt": False, + "transformers_version": transformers.__version__, + "huggingface_hub_version": huggingface_hub.__version__, + "torch_version": torch.__version__, + "files": files, + } + write_json_atomic(args.identity_file, identity) + print(json.dumps(identity, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/rollout.py b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/rollout.py new file mode 100644 index 0000000000000000000000000000000000000000..d309f49ba41db9a4c5ac48178536e1710e1fb503 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/rollout.py @@ -0,0 +1,101 @@ +"""Deterministic fixed-case latent rollouts shared by training and final evaluation.""" + +from __future__ import annotations + +import os +from pathlib import Path + +import numpy as np +import torch +import torch.distributed as dist +from torch.utils.data import DataLoader, Subset + +from mira.data.world_v6 import WorldV6Dataset, collate_world_v6 +from mira.inference.bihub_world_rollout import latent_rollout_metrics +from mira.world_v6.qwen_current_anchor import FrozenQwenCurrentLanes + + +def _fixed_rollout_seed(seed: int, rank: int) -> int: + """Keep one case's sampling noise fixed across checkpoint steps.""" + return seed + rank + + +@torch.inference_mode() +def save_fixed_rollout( + system: torch.nn.Module, + dataset: WorldV6Dataset, + *, + qwen: FrozenQwenCurrentLanes | None, + output_root: str | Path, + branch: str, + completed: int, + seed: int, + device: torch.device, + rank: int, + world_size: int, +) -> dict[str, float]: + count = min(len(dataset), world_size) + indices = np.unique(np.linspace(0, len(dataset) - 1, count, dtype=np.int64)) + local = indices[rank::world_size].tolist() + if len(local) != 1: + raise RuntimeError("Fixed rollout requires exactly one validation case per active rank") + loader = DataLoader(Subset(dataset, local), batch_size=1, num_workers=0, collate_fn=collate_world_v6) + batch, metadata = next(iter(loader)) + obs_last = batch.obs_last_lgr + batch = batch.to(device) + if qwen is not None: + assert obs_last is not None + hidden, mask = qwen(obs_last, [str(metadata[0]["instruction"])]) + condition = {"qwen_hidden": hidden.detach(), "qwen_mask": mask} + else: + assert batch.anchors is not None + condition = {"anchors": batch.anchors} + case_seed = _fixed_rollout_seed(seed, rank) + generator = torch.Generator(device=device).manual_seed(case_seed) + noise = torch.randn(batch.z_future_raw.shape, generator=generator, device=device) + with torch.autocast("cuda", dtype=torch.bfloat16): + result = system( + z_context_raw=batch.z_context_raw, + z_future_raw=batch.z_future_raw, + state_history=batch.state_history, + history_valid=batch.history_valid, + future_valid=batch.future_valid, + view_valid=batch.view_valid, + sample_steps=10, + sample_noise=noise, + **condition, + ) + prediction = result["sample_future_raw"].float().cpu() + context = batch.z_context_raw.float().cpu() + target = batch.z_future_raw.float().cpu() + metrics = latent_rollout_metrics(context[0], target[0], prediction[0]) + case_root = Path(output_root) / "fixed_cases" / branch / f"case-rank{rank:02d}" + case_root.mkdir(parents=True, exist_ok=True) + final = case_root / f"step-{completed}.pth" + temporary = final.with_name(f".{final.name}.{os.getpid()}.tmp") + torch.save( + { + "format_version": 1, + "branch": branch, + "step": completed, + "seed": case_seed, + "context_raw": context[0], + "target_raw": target[0], + "prediction_raw": prediction[0], + "metadata": metadata[0], + "metrics": metrics, + }, + temporary, + ) + os.replace(temporary, final) + gathered: list[dict[str, float] | None] + if dist.is_initialized(): + gathered = [None] * world_size + dist.all_gather_object(gathered, metrics) + else: + gathered = [metrics] + keys = sorted(metrics) + return { + key: sum(float(row[key]) for row in gathered if row is not None) / len(gathered) + for key in keys + } diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/select_anchor_checkpoint.py b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/select_anchor_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..57c7c1e4f9efbab2cf8bd249fa6a21154695f583 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/select_anchor_checkpoint.py @@ -0,0 +1,157 @@ +"""Select and freeze one bootstrap Resampler before large anchor-cache generation.""" + +from __future__ import annotations + +import argparse +import json +import shutil +from pathlib import Path + +import torch +import torch.distributed.checkpoint as dcp +from safetensors.torch import save_file + +from mira.training.world_v6.artifacts import sha256_file, write_json_atomic +from mira.training.world_v6.checkpoint import latest_checkpoint +from mira.training.world_v6.config import load_config +from mira.world_v6.model import WorldV6System + + +def _export_selected_system(checkpoint: Path, branch: str, config, destination: Path) -> None: + """Materialize the selected bootstrap branch as the exact main-phase initialization.""" + system = WorldV6System(config.model) + model_state = system.state_dict() + metadata = dcp.FileSystemReader(checkpoint / "distributed").read_metadata() + def canonical(name: str) -> str: + return name.replace("._checkpoint_wrapped_module.", ".") + checkpoint_model_names = [ + name.removeprefix("model.") + for name in metadata.state_dict_metadata + if name.startswith("model.") + ] + ema_names = [name.removeprefix("ema.state.") for name in metadata.state_dict_metadata if name.startswith("ema.state.")] + unknown = sorted( + name + for name in checkpoint_model_names + ema_names + if canonical(name) not in model_state + ) + if unknown: + raise RuntimeError(f"Bootstrap checkpoint contains unknown v6 parameters: {unknown[:10]}") + state = { + "model": { + name: torch.empty_like(model_state[canonical(name)]) for name in checkpoint_model_names + }, + "ema": { + "state": {name: torch.empty_like(model_state[canonical(name)]) for name in ema_names}, + "count": 0.0, + }, + } + dcp.load(state, checkpoint_id=checkpoint / "distributed") + selected = dict(model_state) + for name, value in state["model"].items(): + selected[canonical(name)] = value + if branch == "ema": + for name, value in state["ema"]["state"].items(): + selected[canonical(name)] = value + elif branch != "online": + raise ValueError(f"Unsupported bootstrap branch {branch!r}") + temporary = destination.with_name(f".{destination.name}.tmp") + save_file( + {name: value.detach().cpu().contiguous() for name, value in selected.items()}, + temporary, + ) + temporary.replace(destination) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", required=True) + parser.add_argument("--allow-smoke-last", action="store_true") + parser.add_argument("overrides", nargs="*") + args = parser.parse_args() + config = load_config(args.config, args.overrides) + root = Path(config.experiment.output_root).expanduser().resolve() + candidates = [] + for checkpoint in sorted(root.glob("bootstrap-checkpoint-*")): + state_path = checkpoint / "trainer_state.json" + if not state_path.is_file(): + continue + state = json.loads(state_path.read_text(encoding="utf-8")) + metrics = state.get("metrics", {}) + step = int(state["completed_steps"]) + if not config.experiment.debug_smoke and step not in {1000, 3000, 5000}: + continue + candidates.append((step, checkpoint, metrics)) + if not candidates: + checkpoint = latest_checkpoint(root, "bootstrap") + if checkpoint is None: + raise FileNotFoundError("No complete bootstrap checkpoint") + state = json.loads((checkpoint / "trainer_state.json").read_text(encoding="utf-8")) + candidates = [(int(state["completed_steps"]), checkpoint, state.get("metrics", {}))] + if config.experiment.debug_smoke: + if not args.allow_smoke_last: + raise ValueError("Smoke selection requires explicit --allow-smoke-last") + selected = max(candidates, key=lambda item: item[0]) + branch = "online" + reason = "smoke_only_last_checkpoint_no_scientific_selection" + else: + valid = [] + for candidate in candidates: + metrics = candidate[2] + required = ( + "ema/val/correct_recovered_clean_mse", + "ema/val/null_recovered_clean_mse", + "ema/val/shuffled_recovered_clean_mse", + "ema/val/anchor_effective_rank", + ) + if not all(name in metrics for name in required): + continue + if metrics["ema/val/correct_recovered_clean_mse"] >= min( + metrics["ema/val/null_recovered_clean_mse"], + metrics["ema/val/shuffled_recovered_clean_mse"], + ): + continue + if metrics["ema/val/anchor_effective_rank"] <= 1.5: + continue + valid.append(candidate) + if not valid: + raise RuntimeError("No bootstrap candidate passed semantic/non-collapse selection gates") + selected = min( + valid, key=lambda item: item[2]["ema/val/correct_recovered_clean_mse"] + ) + branch = "ema" + reason = "best_fixed_validation_candidate_passing_semantic_and_rank_gates" + step, checkpoint, metrics = selected + source = checkpoint / f"resampler-{branch}.safetensors" + if not source.is_file(): + raise FileNotFoundError(source) + selection_path = Path(config.artifacts.resampler_selection).expanduser().resolve() + frozen = selection_path.parent / "frozen_current_resampler.safetensors" + frozen.parent.mkdir(parents=True, exist_ok=True) + temporary = frozen.with_name(f".{frozen.name}.tmp") + shutil.copyfile(source, temporary) + temporary.replace(frozen) + system_weights = selection_path.parent / f"bootstrap_system_{branch}.safetensors" + _export_selected_system(checkpoint, branch, config, system_weights) + selection = { + "format_version": 1, + "checkpoint": str(checkpoint), + "checkpoint_step": step, + "branch": branch, + "weights": str(frozen), + "weights_sha256": sha256_file(frozen), + "system_weights": str(system_weights), + "system_weights_sha256": sha256_file(system_weights), + "prompt_version": config.qwen.prompt_version, + "qwen_identity_sha256": sha256_file(config.artifacts.qwen_identity), + "model_config": config.model.anchor.model_dump(mode="json"), + "metrics": metrics, + "selection_reason": reason, + "smoke_only": config.experiment.debug_smoke, + } + write_json_atomic(selection_path, selection) + print(json.dumps(selection, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/select_source_world.py b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/select_source_world.py new file mode 100644 index 0000000000000000000000000000000000000000..47107e0deb38cc194e9fd0859e186917579c35c0 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/select_source_world.py @@ -0,0 +1,59 @@ +"""Lock the already audited v5 online/EMA comparison as the v6 migration source.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from mira.training.world_v6.artifacts import sha256_file, write_json_atomic + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--import-selection", required=True) + parser.add_argument("--output", required=True) + args = parser.parse_args() + checkpoint = Path(args.checkpoint).expanduser().resolve() + imported_path = Path(args.import_selection).expanduser().resolve() + imported = json.loads(imported_path.read_text(encoding="utf-8")) + if Path(imported["checkpoint"]).resolve() != checkpoint: + raise ValueError("Imported source selection refers to another World checkpoint") + if imported.get("selected_branch") not in {"online", "ema"}: + raise ValueError("Imported source selection has no valid branch") + selection = imported.get("selection", {}) + if int(selection.get("cases", 0)) < 64 or not selection.get("ema_view_within_2pct"): + raise ValueError("Imported source comparison does not satisfy the fixed 64-case gate") + if selection.get("primary") != "standardized_future_latent_mse": + raise ValueError("Unexpected source-selection primary metric") + trainer_state = checkpoint / "trainer_state.json" + dcp_metadata = checkpoint / "distributed" / ".metadata" + if not trainer_state.is_file() or not dcp_metadata.is_file(): + raise FileNotFoundError("Incomplete v5 source checkpoint") + output = { + "format_version": 1, + "purpose": "world_v6_weight_migration_source", + "checkpoint": str(checkpoint), + "checkpoint_step": int(imported["checkpoint_step"]), + "selected_branch": imported["selected_branch"], + "selected_state_dict_sha256": imported["selected_state_dict_sha256"], + "online_state_dict_sha256": imported["online_state_dict_sha256"], + "ema_state_dict_sha256": imported["ema_state_dict_sha256"], + "selection": selection, + "trainer_state_sha256": sha256_file(trainer_state), + "dcp_metadata_sha256": sha256_file(dcp_metadata), + "imported_audit": str(imported_path), + "imported_audit_sha256": sha256_file(imported_path), + "reuse_reason": ( + "The prior audit compared this exact World checkpoint's online/EMA branches on " + "64 fixed validation windows with identical 10-step solver noise. Repeating it " + "would not add information, so v6 pins the audited result instead." + ), + } + write_json_atomic(args.output, output) + print(json.dumps(output, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/train.py b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/train.py new file mode 100644 index 0000000000000000000000000000000000000000..b7c9af0b8651f7a35cb102610ebdc193fabdd644 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/train.py @@ -0,0 +1,975 @@ +"""FSDP2 trainer for online-Qwen bootstrap and cached-anchor World v6 main phases.""" + +from __future__ import annotations + +import argparse +import json +import logging +import math +import random +import signal +import time +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import torch.distributed as dist +from safetensors.torch import load_file +from torch import Tensor +from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( + CheckpointImpl, + checkpoint_wrapper, +) +from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard +from torch.distributed.tensor import DTensor +from torch.utils.data import DataLoader, Subset + +from mira.data.world_v6 import ( + WorldV6BalancedSampler, + WorldV6Dataset, + collate_world_v6, + set_world_v6_process_name, +) +from mira.training.distributed import set_up_distributed +from mira.training.ema import ModelEMA +from mira.training.swanlab_tracker import SwanLabTracker +from mira.training.world_v6.artifacts import canonical_sha256, sha256_file +from mira.training.world_v6.checkpoint import ( + latest_checkpoint, + load_checkpoint, + save_checkpoint, +) +from mira.training.world_v6.config import WorldV6RunConfig, load_config +from mira.training.world_v6.rollout import save_fixed_rollout +from mira.world_v6.migration import load_migrated_system +from mira.world_v6.qwen_current_anchor import FrozenQwenCurrentLanes + +logger = logging.getLogger(__name__) + + +def _all_reduce_mean(value: Tensor) -> Tensor: + output = value.detach().float().clone() + if dist.is_initialized(): + dist.all_reduce(output, op=dist.ReduceOp.SUM) + output /= dist.get_world_size() + return output + + +def _rank_merged_counts(values: list[str]) -> dict[str, int]: + local: dict[str, int] = {} + for value in values: + local[value] = local.get(value, 0) + 1 + if not dist.is_initialized(): + return dict(sorted(local.items())) + gathered: list[dict[str, int] | None] = [None] * dist.get_world_size() + dist.all_gather_object(gathered, local) + merged: dict[str, int] = {} + for counts in gathered: + assert counts is not None + for name, count in counts.items(): + merged[name] = merged.get(name, 0) + count + return dict(sorted(merged.items())) + + +def _rank_merged_group_losses( + rows: list[tuple[str, str, float]], +) -> tuple[dict[str, float], dict[str, float]]: + gathered: list[list[tuple[str, str, float]] | None] + if dist.is_initialized(): + gathered = [None] * dist.get_world_size() + dist.all_gather_object(gathered, rows) + else: + gathered = [rows] + task_values: dict[str, list[float]] = {} + domain_values: dict[str, list[float]] = {} + for rank_rows in gathered: + assert rank_rows is not None + for task, domain, value in rank_rows: + task_values.setdefault(task, []).append(value) + domain_values.setdefault(domain, []).append(value) + return ( + {name: sum(values) / len(values) for name, values in sorted(task_values.items())}, + {name: sum(values) / len(values) for name, values in sorted(domain_values.items())}, + ) + + +def _distributed_parameter_mean(parameters: list[Tensor], device: torch.device) -> float: + total = torch.zeros(2, dtype=torch.float64, device=device) + for parameter in parameters: + local = parameter.to_local() if isinstance(parameter, DTensor) else parameter + total[0] += local.detach().double().sum() + total[1] += local.numel() + if dist.is_initialized(): + dist.all_reduce(total) + return float(total[0] / total[1].clamp_min(1)) + + +def _cloud_train_metrics(metrics: dict[str, Any]) -> dict[str, float]: + scalar_names = ( + "loss_world", + "loss_left", + "loss_global", + "loss_right", + "recovered_clean_mse", + "anchor_norm", + "condition_norm", + "anchor_finite_rate", + "condition_finite_rate", + "global_left_history_mass", + "global_own_history_mass", + "global_right_history_mass", + "local_history_mass", + "local_global_relay_mass", + "grad_norm", + "resampler_attention_gate", + "resampler_ffn_gate", + "world_condition_gate_mean", + ) + output = {f"train/{name}": float(metrics[name]) for name in scalar_names} + output.update( + { + "performance/windows_per_second": float(metrics["windows_per_second"]), + "performance/data_seconds": float(metrics["data_seconds"]), + "performance/gpu_peak_allocated_gib": float(metrics["gpu_peak_allocated_gib"]), + } + ) + for name in ("horizon_loss", "tau_bucket_loss"): + output.update( + {f"train/{name}/{index}": float(value) for index, value in enumerate(metrics[name])} + ) + for group, value in metrics["group_grad_norm"].items(): + output[f"train/grad_norm/{group}"] = float(value) + for name, value in metrics.items(): + if name.startswith("lr_"): + output[f"train/{name}"] = float(value) + for domain, value in metrics["domain_loss"].items(): + output[f"train/domain_loss/{domain}"] = float(value) + return output + + +def _decode_fixed_cases( + decoder: torch.nn.Module | None, + *, + codec_checkpoint: str, + output_root: Path, + completed: int, + world_size: int, + device: torch.device, +) -> torch.nn.Module: + from mira.codec.codec_model import VideoCodec + from mira.inference.bihub_world_rollout import decode_comparison_video + from mira.training.visualization import write_video_ffmpeg + + if decoder is None: + codec = VideoCodec.load_from_checkpoint(codec_checkpoint, device="cpu") + decoder = codec.decoder.eval().requires_grad_(False).to(device) + del codec + for branch in ("online", "ema"): + video_root = output_root / "fixed_videos" / branch + video_root.mkdir(parents=True, exist_ok=True) + for case_rank in range(min(4, world_size)): + artifact = ( + output_root + / "fixed_cases" + / branch + / f"case-rank{case_rank:02d}" + / f"step-{completed}.pth" + ) + value = torch.load(artifact, map_location="cpu", weights_only=False) + video = decode_comparison_video( + decoder, + value["context_raw"], + value["target_raw"], + value["prediction_raw"], + device=device, + ) + final = video_root / f"case-rank{case_rank:02d}-step-{completed}.mp4" + temporary = final.with_name(f".{final.name}.tmp.mp4") + write_video_ffmpeg(temporary, video, fps=20, preset="fast") + temporary.replace(final) + return decoder + + +def _configure_trainable(model: torch.nn.Module, phase: str) -> None: + for parameter in model.parameters(): + parameter.requires_grad_(phase == "main") + if phase == "main": + for parameter in model.current_resampler.parameters(): + parameter.requires_grad_(False) + else: + prefixes = ( + "current_resampler.", + "history_builder.", + "history_hub.", + "state_encoder.", + ) + for name, parameter in model.named_parameters(): + enabled = name.startswith(prefixes) or any( + token in name + for token in (".condition.", ".state_projections.", ".modulation.") + ) + parameter.requires_grad_(enabled) + + +def _canonical_parameter_name(name: str) -> str: + return name.replace("._checkpoint_wrapped_module.", ".") + + +def _decay(name: str, parameter: Tensor) -> bool: + excluded = ("bias", "norm", "embedding", "gate", "query_bank", "qk_scale") + return parameter.ndim >= 2 and not any(token in name.lower() for token in excluded) + + +def _optimizer( + model: torch.nn.Module, + config: WorldV6RunConfig, + names: dict[int, str], +) -> tuple[torch.optim.Optimizer, dict[int, str]]: + groups: dict[tuple[str, bool], list[Tensor]] = {} + parameter_kind: dict[int, str] = {} + migration = json.loads(Path(config.artifacts.migration_report).read_text(encoding="utf-8")) + inherited_names = {item["key"] for item in migration["loaded"]} + for parameter in model.parameters(): + if not parameter.requires_grad: + continue + name = names[id(parameter)] + if config.runtime.phase == "bootstrap": + if name.startswith("current_resampler."): + kind = "resampler" + lr = config.bootstrap.lr_resampler + elif name.startswith("state_encoder.") or any( + token in name for token in (".state_projections.", ".modulation.") + ): + kind = "state_adapter" + lr = config.bootstrap.lr_state_adapter + else: + kind = "interface" + lr = config.bootstrap.lr_hhr_world_cross + else: + kind = "inherited" if name in inherited_names else "new" + lr = config.training.lr_inherited if kind == "inherited" else config.training.lr_new + groups.setdefault((kind, _decay(name, parameter)), []).append(parameter) + parameter_kind[id(parameter)] = kind + optimizer_groups = [] + for (kind, decay), parameters in sorted(groups.items()): + if config.runtime.phase == "bootstrap": + lr = { + "resampler": config.bootstrap.lr_resampler, + "interface": config.bootstrap.lr_hhr_world_cross, + "state_adapter": config.bootstrap.lr_state_adapter, + }[kind] + else: + lr = config.training.lr_inherited if kind == "inherited" else config.training.lr_new + optimizer_groups.append( + { + "params": parameters, + "lr": lr, + "initial_lr": lr, + "weight_decay": config.optimizer.weight_decay if decay else 0.0, + "kind": kind, + } + ) + optimizer = torch.optim.AdamW( + optimizer_groups, + betas=tuple(config.optimizer.betas), + eps=config.optimizer.eps, + ) + return optimizer, parameter_kind + + +def _scheduler(optimizer: torch.optim.Optimizer, config: WorldV6RunConfig): + phase = config.runtime.phase + total = config.bootstrap.steps if phase == "bootstrap" else config.training.steps + warmup = config.bootstrap.warmup_steps if phase == "bootstrap" else config.training.warmup_steps + + def schedule(kind: str): + def value(step: int) -> float: + completed = step + 1 + if phase == "main" and kind == "inherited": + start = config.training.inherited_unfreeze_step + ramp = config.training.inherited_unfreeze_ramp + if completed <= start: + return 0.0 + if completed <= start + ramp: + return (completed - start) / ramp + if completed <= warmup: + return completed / max(1, warmup) + progress = min(1.0, (completed - warmup) / max(1, total - warmup)) + cosine = 0.5 * (1 + math.cos(math.pi * progress)) + if phase == "bootstrap": + floor = 0.1 + elif kind == "inherited": + floor = config.training.min_lr_inherited / config.training.lr_inherited + else: + floor = config.training.min_lr_new / config.training.lr_new + return floor + (1 - floor) * cosine + + return value + + return torch.optim.lr_scheduler.LambdaLR( + optimizer, [schedule(str(group["kind"])) for group in optimizer.param_groups] + ) + + +def _artifact_identity(config: WorldV6RunConfig) -> dict[str, Any]: + values = { + "codec": config.artifacts.codec_sha256, + "train_window_manifest": sha256_file(config.artifacts.train_window_manifest), + "val_window_manifest": sha256_file(config.artifacts.val_window_manifest), + "qwen_identity": sha256_file(config.artifacts.qwen_identity), + "migration": sha256_file(config.artifacts.migration_report), + "phase": config.runtime.phase, + } + if config.runtime.phase == "main": + values["anchor_cache"] = sha256_file(config.artifacts.anchor_cache_identity) + values["resampler_selection"] = sha256_file(config.artifacts.resampler_selection) + values["sha256"] = canonical_sha256(values) + return values + + +def _dataset(config: WorldV6RunConfig, split: str) -> WorldV6Dataset: + source = ( + config.artifacts.train_source_manifest + if split == "train" + else config.artifacts.val_source_manifest + ) + manifest = ( + config.artifacts.train_window_manifest + if split == "train" + else config.artifacts.val_window_manifest + ) + index = ( + config.artifacts.train_window_index if split == "train" else config.artifacts.val_window_index + ) + return WorldV6Dataset( + source_manifest=source, + window_manifest=manifest, + window_index=index, + dataset_stats=config.artifacts.dataset_stats, + dataset_root=config.artifacts.raw_dataset_root, + anchors_root=( + config.artifacts.anchor_cache_root if config.runtime.phase == "main" else None + ), + need_rgb=config.runtime.phase == "bootstrap", + extracted_episode_root=config.artifacts.extracted_rgb_root, + episode_cache_size=config.data.episode_cache_size, + ) + + +def _load_resampler_selection(model: torch.nn.Module, path: str | Path) -> None: + selection = json.loads(Path(path).read_text(encoding="utf-8")) + state = load_file(selection["weights"], device="cpu") + model.current_resampler.load_state_dict(state, strict=True) + + +def _group_grad_norm(model: torch.nn.Module, parameter_kind: dict[int, str]) -> dict[str, float]: + sums: dict[str, Tensor] = {} + for parameter in model.parameters(): + if parameter.grad is None: + continue + kind = parameter_kind[id(parameter)] + value = parameter.grad.detach().float().norm().square() + sums[kind] = sums.get(kind, torch.zeros_like(value)) + value + return {kind: float(value.sqrt()) for kind, value in sums.items()} + + +def _cross_rank_roll(value: Tensor, rank: int, world_size: int) -> Tensor: + if world_size == 1: + return value.roll(1, dims=0) if value.shape[0] > 1 else value.flip(2) + gathered = [torch.empty_like(value) for _ in range(world_size)] + dist.all_gather(gathered, value.contiguous()) + return gathered[(rank + 1) % world_size] + + +def _fixed_validation_seed(fixed_seed: int, batch_index: int) -> int: + """Keep validation noise identical when comparing different checkpoints.""" + return fixed_seed + batch_index + + +@torch.inference_mode() +def _fixed_validation( + system: torch.nn.Module, + qwen: FrozenQwenCurrentLanes | None, + config: WorldV6RunConfig, + dataset: WorldV6Dataset, + *, + device: torch.device, + rank: int, + world_size: int, + completed: int, +) -> dict[str, float]: + total_cases = min( + len(dataset), + config.validation.batches * config.distributed.per_device_batch * world_size, + ) + all_indices = np.unique(np.linspace(0, len(dataset) - 1, total_cases, dtype=np.int64)) + local_indices = all_indices[rank::world_size].tolist() + loader = DataLoader( + Subset(dataset, local_indices), + batch_size=config.distributed.per_device_batch, + shuffle=False, + num_workers=0, + collate_fn=collate_world_v6, + ) + was_training = system.training + system.eval() + totals = torch.zeros(8, device=device, dtype=torch.float64) + anchor_rows = [] + for batch_index, (batch, metadata) in enumerate(loader): + obs_last = batch.obs_last_lgr + batch = batch.to(device) + if qwen is not None: + assert obs_last is not None + hidden, mask = qwen(obs_last, [str(item["instruction"]) for item in metadata]) + qwen.assert_frozen() + forward_condition = {"qwen_hidden": hidden.detach(), "qwen_mask": mask} + anchor_for_diagnostics = None + else: + assert batch.anchors is not None + forward_condition = {"anchors": batch.anchors} + anchor_for_diagnostics = batch.anchors + generator = torch.Generator(device=device).manual_seed( + _fixed_validation_seed(config.validation.fixed_seed, batch_index) + ) + noise = torch.randn( + batch.z_future_raw.shape, generator=generator, device=device, dtype=torch.float32 + ) + tau = torch.rand( + (batch.z_future_raw.shape[0], 10, 1, 1, 1), + generator=generator, + device=device, + dtype=torch.float32, + ) + with torch.autocast("cuda", dtype=torch.bfloat16): + correct = system( + z_context_raw=batch.z_context_raw, + z_future_raw=batch.z_future_raw, + state_history=batch.state_history, + history_valid=batch.history_valid, + future_valid=batch.future_valid, + view_valid=batch.view_valid, + noise=noise, + tau_future=tau, + **forward_condition, + ) + if anchor_for_diagnostics is None: + anchor_for_diagnostics = correct["anchors_out"] + anchors = anchor_for_diagnostics + null = system( + z_context_raw=batch.z_context_raw, + z_future_raw=batch.z_future_raw, + anchors=torch.zeros_like(anchors), + state_history=batch.state_history, + history_valid=batch.history_valid, + future_valid=batch.future_valid, + view_valid=batch.view_valid, + noise=noise, + tau_future=tau, + ) + shuffled_anchors = _cross_rank_roll(anchors, rank, world_size) + shuffled = system( + z_context_raw=batch.z_context_raw, + z_future_raw=batch.z_future_raw, + anchors=shuffled_anchors, + state_history=batch.state_history, + history_valid=batch.history_valid, + future_valid=batch.future_valid, + view_valid=batch.view_valid, + noise=noise, + tau_future=tau, + ) + role_swapped = anchors[:, [2, 1, 0]] + swapped = system( + z_context_raw=batch.z_context_raw, + z_future_raw=batch.z_future_raw, + anchors=role_swapped, + state_history=batch.state_history, + history_valid=batch.history_valid, + future_valid=batch.future_valid, + view_valid=batch.view_valid, + noise=noise, + tau_future=tau, + ) + count = batch.z_context_raw.shape[0] + totals += torch.tensor( + [ + float(correct["loss_world"]) * count, + float(correct["recovered_clean_mse"]) * count, + float(null["recovered_clean_mse"]) * count, + float(shuffled["recovered_clean_mse"]) * count, + float(swapped["recovered_clean_mse"]) * count, + float(anchors.float().std()) * count, + float(torch.isfinite(anchors).float().mean()) * count, + count, + ], + device=device, + dtype=torch.float64, + ) + anchor_rows.append(anchors.detach().float().reshape(-1, anchors.shape[-1])) + if dist.is_initialized(): + dist.all_reduce(totals, op=dist.ReduceOp.SUM) + count = totals[-1].clamp_min(1) + local_anchor = torch.cat(anchor_rows, dim=0) + if world_size > 1: + gathered = [torch.empty_like(local_anchor) for _ in range(world_size)] + dist.all_gather(gathered, local_anchor.contiguous()) + anchor_matrix = torch.cat(gathered, dim=0) + else: + anchor_matrix = local_anchor + singular = torch.linalg.svdvals(anchor_matrix.float()) + probability = singular / singular.sum().clamp_min(1.0e-12) + effective_rank = torch.exp(-(probability * probability.clamp_min(1e-12).log()).sum()) + metrics = { + "val/correct_flow_mse": float(totals[0] / count), + "val/correct_recovered_clean_mse": float(totals[1] / count), + "val/null_recovered_clean_mse": float(totals[2] / count), + "val/shuffled_recovered_clean_mse": float(totals[3] / count), + "val/role_swap_recovered_clean_mse": float(totals[4] / count), + "val/anchor_std": float(totals[5] / count), + "val/anchor_finite_rate": float(totals[6] / count), + "val/anchor_effective_rank": float(effective_rank), + } + if was_training: + system.train() + if qwen is not None: + qwen.eval() + return metrics + + +def train(config: WorldV6RunConfig) -> None: + settings = set_up_distributed() + rank, world_size = settings.rank, settings.world_size + device = torch.device("cuda", settings.device) + set_world_v6_process_name( + f"syncnet_v6_b{rank}" if config.runtime.phase == "bootstrap" else f"syncnet_v6_r{rank}" + ) + logging.basicConfig( + level=logging.INFO if rank == 0 else logging.WARNING, + format="%(asctime)s | %(levelname)s | %(message)s", + ) + effective = ( + world_size + * config.distributed.per_device_batch + * config.distributed.gradient_accumulation_steps + ) + if effective != config.distributed.effective_global_batch: + raise ValueError( + f"Effective global batch is {effective}, expected {config.distributed.effective_global_batch}" + ) + seed = config.experiment.seed + rank + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + torch.backends.cuda.matmul.allow_tf32 = True + output = Path(config.experiment.output_root).expanduser().resolve() + output.mkdir(parents=True, exist_ok=True) + if rank == 0: + (output / "resolved_config.json").write_text( + json.dumps(config.model_dump(mode="json"), indent=2) + "\n", encoding="utf-8" + ) + initialization = config.artifacts.migration_weights + if config.runtime.phase == "main": + selection = json.loads( + Path(config.artifacts.resampler_selection).read_text(encoding="utf-8") + ) + initialization = selection["system_weights"] + system = load_migrated_system(initialization, config.model) + if config.runtime.phase == "main": + _load_resampler_selection(system, config.artifacts.resampler_selection) + _configure_trainable(system, config.runtime.phase) + parameter_report = system.parameter_report() + system = system.to(device) + policy = MixedPrecisionPolicy( + param_dtype=torch.bfloat16, + reduce_dtype=torch.float32, + output_dtype=torch.bfloat16, + ) + if config.model.activation_checkpointing: + system.world_model.external_activation_checkpointing = True + for index, block in enumerate(system.world_model.blocks): + system.world_model.blocks[index] = checkpoint_wrapper( + block, + checkpoint_impl=CheckpointImpl.NO_REENTRANT, + preserve_rng_state=True, + ) + for block in system.world_model.blocks: + fully_shard(block, mp_policy=policy, reshard_after_forward=True) + fully_shard(system, mp_policy=policy, reshard_after_forward=True) + names = { + id(parameter): _canonical_parameter_name(name) + for name, parameter in system.named_parameters() + } + optimizer, parameter_kind = _optimizer(system, config, names) + scheduler = _scheduler(optimizer, config) + ema = ModelEMA(system, decay=config.optimizer.ema_decay, unbias=False) + train_dataset = _dataset(config, "train") + val_dataset = _dataset(config, "val") + sampler = WorldV6BalancedSampler( + train_dataset, + seed=config.experiment.seed, + rank=rank, + world_size=world_size, + clean_probability=config.data.clean_probability, + ) + loader = DataLoader( + train_dataset, + batch_size=config.distributed.per_device_batch, + sampler=sampler, + num_workers=config.data.num_workers, + prefetch_factor=config.data.prefetch_factor if config.data.num_workers else None, + persistent_workers=config.data.num_workers > 0, + pin_memory=True, + collate_fn=collate_world_v6, + ) + qwen = None + if config.runtime.phase == "bootstrap": + qwen = FrozenQwenCurrentLanes( + config.artifacts.qwen_root, config.artifacts.qwen_identity, device=device + ) + identity = _artifact_identity(config) + start = 0 + if config.checkpoint.auto_resume: + checkpoint = latest_checkpoint(output, config.runtime.phase) + if checkpoint is not None: + start = load_checkpoint( + checkpoint, + model=system, + optimizer=optimizer, + scheduler=scheduler, + ema=ema, + sampler=sampler, + expected_artifact_identity=identity, + ) + # A multiprocessing DataLoader prefetches sampler indices as soon as its + # iterator is created. Construct it only after restoring the sampler + # cursor, otherwise a resumed run silently starts again at cursor zero. + iterator = iter(loader) + total = config.bootstrap.steps if config.runtime.phase == "bootstrap" else config.training.steps + if config.runtime.max_steps is not None: + total = min(total, config.runtime.max_steps) + tracker = SwanLabTracker.disabled() + if rank == 0 and config.logging.swanlab_enabled: + tracker = SwanLabTracker.initialize( + { + "project": config.logging.swanlab_project, + "experiment_name": config.logging.swanlab_experiment_name, + "mode": "online", + "token_file": config.logging.swanlab_token_file, + "capture_console": "stderr", + "system_monitor": False, + "upload_hardware": True, + "upload_runtime": True, + "upload_requirements": False, + "upload_git": False, + "resume": "allow", + "public": False, + }, + output_dir=output, + run_config=config.model_dump(mode="json"), + ) + requested_stop = False + + def stop_handler(_signum: int, _frame: Any) -> None: + nonlocal requested_stop + requested_stop = True + + signal.signal(signal.SIGTERM, stop_handler) + signal.signal(signal.SIGINT, stop_handler) + system.train() + if qwen is not None: + qwen.eval() + metrics_path = output / "metrics.jsonl" + last_metrics: dict[str, Any] = {} + visualization_decoder: torch.nn.Module | None = None + torch.cuda.reset_peak_memory_stats(device) + interval_start = time.monotonic() + interval_windows = 0 + try: + for step in range(start, total): + optimizer.zero_grad(set_to_none=True) + accumulated: dict[str, Tensor] = {} + accumulated_vectors: dict[str, Tensor] = {} + domains: list[str] = [] + tasks: list[str] = [] + grouped_losses: list[tuple[str, str, float]] = [] + for micro in range(config.distributed.gradient_accumulation_steps): + data_start = time.monotonic() + batch, metadata = next(iterator) + data_seconds = time.monotonic() - data_start + obs_last_cpu = batch.obs_last_lgr + batch = batch.to(device, non_blocking=True) + domains.extend(str(item["domain"]) for item in metadata) + tasks.extend(str(item["task"]) for item in metadata) + if qwen is not None: + assert obs_last_cpu is not None + hidden, mask = qwen( + obs_last_cpu, [str(item["instruction"]) for item in metadata] + ) + qwen.assert_frozen() + forward_condition = { + "qwen_hidden": hidden.detach(), + "qwen_mask": mask, + } + else: + if batch.anchors is None: + raise RuntimeError("Main phase requires frozen cached anchors") + forward_condition = {"anchors": batch.anchors} + last_backward = micro == config.distributed.gradient_accumulation_steps - 1 + system.set_requires_gradient_sync(last_backward) + system.set_is_last_backward(last_backward) + with torch.autocast("cuda", dtype=torch.bfloat16): + result = system( + z_context_raw=batch.z_context_raw, + z_future_raw=batch.z_future_raw, + state_history=batch.state_history, + history_valid=batch.history_valid, + future_valid=batch.future_valid, + view_valid=batch.view_valid, + **forward_condition, + ) + loss = result["loss_total"] / config.distributed.gradient_accumulation_steps + loss.backward() + for name, value in result.items(): + if value.ndim == 0: + accumulated[name] = accumulated.get(name, torch.zeros_like(value)) + ( + value.detach() / config.distributed.gradient_accumulation_steps + ) + elif name in {"horizon_loss", "tau_bucket_loss"}: + accumulated_vectors[name] = accumulated_vectors.get( + name, torch.zeros_like(value) + ) + value.detach() / config.distributed.gradient_accumulation_steps + grouped_losses.extend( + ( + str(item["task"]), + str(item["domain"]), + float(sample_loss), + ) + for item, sample_loss in zip(metadata, result["per_sample_loss"]) + ) + accumulated["data_seconds"] = accumulated.get( + "data_seconds", torch.zeros((), device=device) + ) + torch.tensor(data_seconds, device=device) + sampler.mark_consumed(config.distributed.per_device_batch) + interval_windows += config.distributed.per_device_batch + group_norms = _group_grad_norm(system, parameter_kind) + grad_norm = torch.nn.utils.clip_grad_norm_(system.parameters(), config.optimizer.grad_clip) + optimizer.step() + scheduler.step() + ema.step() + completed = step + 1 + should_log = completed <= config.logging.early_steps or completed % config.logging.every_steps == 0 + if should_log or completed == total: + elapsed = max(time.monotonic() - interval_start, 1.0e-6) + values = {name: float(_all_reduce_mean(value)) for name, value in accumulated.items()} + vector_values = { + name: _all_reduce_mean(value).cpu().tolist() + for name, value in accumulated_vectors.items() + } + task_losses, domain_losses = _rank_merged_group_losses(grouped_losses) + lr_by_kind = { + f"lr_{group['kind']}": float(group["lr"]) for group in optimizer.param_groups + } + last_metrics = { + "step": completed, + "phase": config.runtime.phase, + "loss_world": values["loss_world"], + "loss_left": values["loss_left"], + "loss_global": values["loss_global"], + "loss_right": values["loss_right"], + "recovered_clean_mse": values["recovered_clean_mse"], + "anchor_norm": values["anchor_norm"], + "condition_norm": values["condition_norm"], + "anchor_finite_rate": values["anchor_finite_rate"], + "condition_finite_rate": values["condition_finite_rate"], + "global_left_history_mass": values["global_left_history_mass"], + "global_own_history_mass": values["global_own_history_mass"], + "global_right_history_mass": values["global_right_history_mass"], + "local_history_mass": values["local_history_mass"], + "local_global_relay_mass": values["local_global_relay_mass"], + "horizon_loss": vector_values["horizon_loss"], + "tau_bucket_loss": vector_values["tau_bucket_loss"], + "grad_norm": float(grad_norm), + "group_grad_norm": group_norms, + **lr_by_kind, + "windows_per_second": interval_windows * world_size / elapsed, + "data_seconds": values["data_seconds"], + "gpu_peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "domain_counts": _rank_merged_counts(domains), + "task_counts": _rank_merged_counts(tasks), + "domain_loss": domain_losses, + "task_loss": task_losses, + "resampler_attention_gate": _distributed_parameter_mean( + [system.current_resampler.attention_gate], device + ), + "resampler_ffn_gate": _distributed_parameter_mean( + [system.current_resampler.ffn_gate], device + ), + "world_condition_gate_mean": _distributed_parameter_mean( + [block.condition.residual_gate for block in system.world_model.blocks], + device, + ), + "parameter_report": parameter_report if completed == 1 else None, + } + if rank == 0: + with metrics_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(last_metrics, default=float) + "\n") + logger.info( + "step=%d phase=%s loss=%.6f grad=%.3f windows/s=%.2f peak=%.2fGiB", + completed, + config.runtime.phase, + last_metrics["loss_world"], + last_metrics["grad_norm"], + last_metrics["windows_per_second"], + last_metrics["gpu_peak_allocated_gib"], + ) + try: + tracker.log(_cloud_train_metrics(last_metrics), step=completed) + except Exception as exc: + logger.warning("SwanLab logging failed and was skipped: %s", exc) + interval_start = time.monotonic() + interval_windows = 0 + validation_due = ( + not config.experiment.debug_smoke + and (completed % config.validation.every_steps == 0 or completed == total) + ) + if validation_due: + online_validation = _fixed_validation( + system, + qwen, + config, + val_dataset, + device=device, + rank=rank, + world_size=world_size, + completed=completed, + ) + with ema.average_parameters(): + ema_validation = _fixed_validation( + system, + qwen, + config, + val_dataset, + device=device, + rank=rank, + world_size=world_size, + completed=completed, + ) + validation = { + **{f"online/{name}": value for name, value in online_validation.items()}, + **{f"ema/{name}": value for name, value in ema_validation.items()}, + } + last_metrics.update(validation) + if rank == 0: + with metrics_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps({"step": completed, **validation}) + "\n") + try: + tracker.log(validation, step=completed) + except Exception as exc: + logger.warning("SwanLab validation logging failed and was skipped: %s", exc) + sample_due = ( + not config.experiment.debug_smoke + and ( + completed % config.validation.sample_every_steps == 0 + or completed == total + ) + ) + if sample_due: + system.eval() + online_rollout = save_fixed_rollout( + system, + val_dataset, + qwen=qwen, + output_root=output, + branch="online", + completed=completed, + seed=config.validation.fixed_seed, + device=device, + rank=rank, + world_size=world_size, + ) + with ema.average_parameters(): + ema_rollout = save_fixed_rollout( + system, + val_dataset, + qwen=qwen, + output_root=output, + branch="ema", + completed=completed, + seed=config.validation.fixed_seed, + device=device, + rank=rank, + world_size=world_size, + ) + system.train() + if qwen is not None: + qwen.eval() + rollout_metrics = { + **{f"online/rollout/{name}": value for name, value in online_rollout.items()}, + **{f"ema/rollout/{name}": value for name, value in ema_rollout.items()}, + } + last_metrics.update(rollout_metrics) + if rank == 0: + with metrics_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps({"step": completed, **rollout_metrics}) + "\n") + try: + tracker.log(rollout_metrics, step=completed) + except Exception as exc: + logger.warning("SwanLab rollout logging failed and was skipped: %s", exc) + visualization_decoder = _decode_fixed_cases( + visualization_decoder, + codec_checkpoint=config.artifacts.codec_checkpoint, + output_root=output, + completed=completed, + world_size=world_size, + device=device, + ) + if dist.is_initialized(): + dist.barrier() + preserve = ( + config.bootstrap.preserve_steps + if config.runtime.phase == "bootstrap" + else config.checkpoint.preserve_steps + ) + checkpoint_due = ( + completed % config.checkpoint.every_steps == 0 + or completed in preserve + or completed == total + or requested_stop + ) + if checkpoint_due: + save_checkpoint( + output, + phase=config.runtime.phase, + completed_steps=completed, + model=system, + optimizer=optimizer, + scheduler=scheduler, + ema=ema, + sampler=sampler, + resolved_config=config.model_dump(mode="json"), + artifact_identity=identity, + metrics=last_metrics, + keep_recent=config.checkpoint.keep_last_recovery, + ) + if requested_stop: + break + finally: + if rank == 0: + tracker.finish() + if dist.is_initialized(): + dist.barrier() + dist.destroy_process_group() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", required=True) + parser.add_argument("overrides", nargs="*") + args = parser.parse_args() + train(load_config(args.config, args.overrides)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/validate_qwen_contract.py b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/validate_qwen_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..658343be1d06214db3acd63f17407a4b927bbd46 --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v6/validate_qwen_contract.py @@ -0,0 +1,110 @@ +"""Validate the real RoboTwin -> frozen-Qwen current-lane contract on one GPU.""" + +from __future__ import annotations + +import argparse +import json + +import torch + +from mira.data.world_v6 import RGB_PREPROCESS_IDENTITY, WorldV6Dataset +from mira.training.world_v6.artifacts import canonical_sha256, sha256_file, write_json_atomic +from mira.training.world_v6.config import load_config +from mira.world_v6.prompts import VIEW_NAMES, lane_text +from mira.world_v6.qwen_current_anchor import FrozenQwenCurrentLanes + + +@torch.inference_mode() +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", required=True) + parser.add_argument("--report", required=True) + parser.add_argument("overrides", nargs="*") + args = parser.parse_args() + config = load_config(args.config, args.overrides) + if not torch.cuda.is_available(): + raise RuntimeError("The real Qwen contract audit requires one CUDA GPU") + dataset = WorldV6Dataset( + source_manifest=config.artifacts.val_source_manifest, + window_manifest=config.artifacts.val_window_manifest, + window_index=config.artifacts.val_window_index, + dataset_stats=config.artifacts.dataset_stats, + dataset_root=config.artifacts.raw_dataset_root, + need_rgb=True, + extracted_episode_root=config.artifacts.extracted_rgb_root, + episode_cache_size=1, + ) + sample = dataset[0] + rgb = sample["obs_last_lgr"].unsqueeze(0) + instruction = str(sample["metadata"]["instruction"]) + qwen = FrozenQwenCurrentLanes( + config.artifacts.qwen_root, + config.artifacts.qwen_identity, + device=torch.device("cuda", 0), + ) + inputs = qwen.prepare_inputs(rgb, [instruction]) + hidden, mask = qwen(rgb, [instruction]) + qwen.assert_frozen() + input_ids = inputs["input_ids"] + image_token_id = int(qwen.model.config.image_token_id) + prompt_token_ids = { + view: qwen.processor.tokenizer(lane_text(instruction, view), add_special_tokens=False)[ + "input_ids" + ] + for view in VIEW_NAMES + } + pixel_grid = inputs.get("image_grid_thw") + if pixel_grid is None or tuple(pixel_grid.shape) != (3, 3): + raise RuntimeError(f"Unexpected Qwen image grid {None if pixel_grid is None else pixel_grid.shape}") + if hidden.shape[:2] != (1, 3) or hidden.shape[-1] != 2048: + raise RuntimeError(f"Unexpected Qwen hidden shape {tuple(hidden.shape)}") + if mask.shape != hidden.shape[:3] or not bool(mask.any(dim=-1).all()): + raise RuntimeError("Qwen lane attention mask is invalid") + report = { + "format_version": 1, + "passed": True, + "sample": { + key: sample["metadata"][key] + for key in ("window_id", "episode_sha256", "latent_start", "task", "domain") + }, + "rgb": { + "shape": list(rgb.shape), + "dtype": str(rgb.dtype), + "preprocess": RGB_PREPROCESS_IDENTITY, + "preprocess_sha256": canonical_sha256(RGB_PREPROCESS_IDENTITY), + }, + "inputs": { + "input_ids_shape": list(input_ids.shape), + "attention_valid_per_lane": mask.sum(dim=-1).cpu().tolist(), + "pixel_values_shape": list(inputs["pixel_values"].shape), + "image_grid_thw": pixel_grid.cpu().tolist(), + "image_token_id": image_token_id, + "image_tokens_per_lane": (input_ids == image_token_id).sum(dim=-1).cpu().tolist(), + "prompt_token_ids": prompt_token_ids, + }, + "outputs": { + "hidden_shape": list(hidden.shape), + "hidden_dtype": str(hidden.dtype), + "finite_rate": float(torch.isfinite(hidden).double().mean()), + }, + "frozen": { + "eval": not qwen.model.training, + "requires_grad_parameters": sum(p.numel() for p in qwen.model.parameters() if p.requires_grad), + "parameters_with_grad": sum(p.numel() for p in qwen.model.parameters() if p.grad is not None), + }, + "identity": { + "path": config.artifacts.qwen_identity, + "sha256": sha256_file(config.artifacts.qwen_identity), + "revision": qwen.identity["revision"], + "attention_implementation": qwen.identity["attention_implementation"], + }, + "gpu_peak_allocated_gib": torch.cuda.max_memory_allocated() / 2**30, + } + if not bool(torch.isfinite(hidden).all()): + raise RuntimeError("Qwen hidden state contains NaN/Inf") + write_json_atomic(args.report, report) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/world_v7/__init__.py b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v7/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6707c93f9f3117bf5277c852b375916574a0e65e --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v7/__init__.py @@ -0,0 +1 @@ +"""Short-history World v7 fine-tuning and immutable cache tooling.""" diff --git a/release-20261107/source/workspace_joint/mira/src/mira/training/world_v7/build_qwen_hidden_cache.py b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v7/build_qwen_hidden_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..5b1944c36de20dc8565b762da4507e5c79905f9c --- /dev/null +++ b/release-20261107/source/workspace_joint/mira/src/mira/training/world_v7/build_qwen_hidden_cache.py @@ -0,0 +1,523 @@ +"""Build a resumable, lossless cache of frozen-Qwen valid hidden tokens. + +The World v7 supervision expands every old 10+10 window into history lengths +``{1, 3, 6, 10}``. Many expanded rows share the same last real context frame, +so this cache is keyed by ``(episode, current_latent)`` rather than by expanded +training row. The train dataset can derive the cache locator deterministically: + +``unique_global = episode_unique_offset + current_latent`` +``shard = unique_global % cache_world_size`` +``shard_row = unique_global // cache_world_size`` + +Only Qwen tokens whose attention mask is true are persisted. Removing Qwen's +batch-padding tokens is exact for the trainable CurrentQueryResampler because it +has no positional encoding of its own and receives the matching attention mask. +""" + +from __future__ import annotations + +import argparse +import bisect +import ctypes +import json +import os +import time +from collections import OrderedDict +from pathlib import Path +from typing import Any, Iterator, Sequence + +import torch +from safetensors.torch import load_file +from torch import Tensor +from torch.utils.data import DataLoader, Dataset + +from mira.data.robotwin_wam_schema import read_jsonl +from mira.data.world_v6 import RGB_PREPROCESS_IDENTITY, RGBCurrentFrameReader +from mira.training.world_v6.artifacts import canonical_sha256, sha256_file, write_json_atomic +from mira.world_v6.prompts import PROMPT_VERSION, VIEW_NAMES +from mira.world_v6.qwen_current_anchor import FrozenQwenCurrentLanes + +HISTORY_LENGTHS = (1, 3, 6, 10) +HIDDEN_WIDTH = 2048 +VIEWS = 3 +FORMAT_VERSION = 1 + + +def cache_worker_settings() -> tuple[int, int, int]: + """Return ``(rank, world_size, local_rank)`` without creating a process group. + + Cache shards are independent and synchronize through atomic files. Creating + a NCCL process group here is actively harmful: complete shards can differ by + many minutes, so a collective barrier hits NCCL's watchdog even though every + worker is healthy. + """ + rank = int(os.environ.get("RANK", "0")) + world_size = int(os.environ.get("WORLD_SIZE", "1")) + local_rank = int(os.environ.get("LOCAL_RANK", "0")) + if world_size < 1 or not 0 <= rank < world_size: + raise ValueError(f"Invalid cache worker settings rank={rank} world_size={world_size}") + if not torch.cuda.is_available(): + raise RuntimeError("World v7 Qwen cache construction requires CUDA") + torch.cuda.set_device(local_rank) + return rank, world_size, local_rank + + +def current_qwen_indices(current_latent: int) -> tuple[int, int]: + """Map a 10 Hz current latent to its last constituent 20/30 Hz RGB frame.""" + if current_latent < 0: + raise ValueError("current_latent must be non-negative") + rgb20 = 2 * current_latent + 1 + source30 = int(rgb20 * 30 / 20 + 0.5) + return rgb20, source30 + + +def set_process_name(value: str) -> None: + try: + import setproctitle + + setproctitle.setproctitle(value) + except ImportError: + pass + try: + ctypes.CDLL(None).prctl(15, value.encode()[:15], 0, 0, 0) + except (AttributeError, OSError): + pass + + +class UniqueCurrentDataset(Dataset[dict[str, Any]]): + """Compact random access over every unique current latent in a split.""" + + def __init__( + self, + source_manifest: str | Path, + *, + dataset_root: str | Path, + extracted_rgb_root: str | Path, + payload_cache_size: int, + max_unique_rows: int | None = None, + ) -> None: + self.source_manifest = Path(source_manifest).expanduser().resolve() + self.rows = read_jsonl(self.source_manifest) + if not self.rows: + raise ValueError("Qwen hidden cache source manifest is empty") + self.unique_counts = [int(row["n_latents"]) - 10 for row in self.rows] + self.old_window_counts = [int(row["n_latents"]) - 19 for row in self.rows] + if any(value <= 0 for value in self.old_window_counts): + raise ValueError("Source episode cannot provide a 10+10 World target") + self.cumulative = [0] + for value in self.unique_counts: + self.cumulative.append(self.cumulative[-1] + value) + self.total_unique_rows = self.cumulative[-1] + if max_unique_rows is not None and max_unique_rows < 1: + raise ValueError("max_unique_rows must be positive") + self.maximum = ( + self.total_unique_rows + if max_unique_rows is None + else min(self.total_unique_rows, max_unique_rows) + ) + self.reader = RGBCurrentFrameReader( + dataset_root, + extracted_episode_root=extracted_rgb_root, + payload_cache_size=payload_cache_size, + ) + self._index_cache: OrderedDict[str, Tensor] = OrderedDict() + self._index_cache_size = max(1, payload_cache_size) + + def __len__(self) -> int: + return self.maximum + + @property + def expanded_rows(self) -> int: + return sum(self.old_window_counts) * len(HISTORY_LENGTHS) + + def locate(self, unique_global: int) -> tuple[int, int]: + if not 0 <= unique_global < len(self): + raise IndexError(unique_global) + episode = bisect.bisect_right(self.cumulative, unique_global) - 1 + return episode, unique_global - self.cumulative[episode] + + def _source_indices(self, path: str) -> Tensor: + if path in self._index_cache: + value = self._index_cache.pop(path) + self._index_cache[path] = value + return value + value = load_file(path, device="cpu")["source_index_i32"] + self._index_cache[path] = value + while len(self._index_cache) > self._index_cache_size: + self._index_cache.popitem(last=False) + return value + + def __getitem__(self, unique_global: int) -> dict[str, Any]: + episode_index, current_latent = self.locate(unique_global) + row = self.rows[episode_index] + rgb20, source30 = current_qwen_indices(current_latent) + indices = self._source_indices(str(row["cache_path"])) + if rgb20 >= len(indices): + raise RuntimeError("Latent cache lacks the v7 current-frame source index") + cached_source30 = int(indices[rgb20]) + if cached_source30 != source30: + raise RuntimeError( + "Latent cache and v7 half-up current-frame mappings disagree: " + f"{cached_source30} != {source30}" + ) + return { + "obs_last_lgr": self.reader.read_source_frame(row, cached_source30), + "instruction": str(row["instruction"]), + "unique_global": unique_global, + "episode_index": episode_index, + "episode_sha256": str(row["episode_sha256"]), + "current_latent": current_latent, + "qwen_rgb20_index": rgb20, + "qwen_source_index_30hz": cached_source30, + } + + +def collate_unique(samples: list[dict[str, Any]]) -> dict[str, Any]: + return { + "obs_last_lgr": torch.stack([sample["obs_last_lgr"] for sample in samples]), + "instructions": [sample["instruction"] for sample in samples], + "metadata": [ + {key: value for key, value in sample.items() if key not in {"obs_last_lgr", "instruction"}} + for sample in samples + ], + } + + +def chunk_global_indices( + total_rows: int, + *, + rank: int, + world_size: int, + chunk_index: int, + chunk_rows: int, +) -> range: + shard_rows = (total_rows + world_size - 1 - rank) // world_size + first_row = chunk_index * chunk_rows + last_row = min(shard_rows, first_row + chunk_rows) + return range(rank + first_row * world_size, rank + last_row * world_size, world_size) + + +def _chunk_stem(split_root: Path, rank: int, chunk_index: int) -> Path: + return split_root / f"shard-{rank:02d}" / f"chunk-{chunk_index:06d}" + + +def _complete_chunk( + stem: Path, + *, + expected_rows: int, + expected_identity: dict[str, Any], + expected_first_global: int, + expected_last_global: int, +) -> bool: + hidden_path = stem.with_suffix(".bf16") + lengths_path = stem.with_suffix(".lengths.i16") + metadata_path = stem.with_suffix(".json") + if not all(path.is_file() for path in (hidden_path, lengths_path, metadata_path)): + return False + metadata = json.loads(metadata_path.read_text(encoding="utf-8")) + expected = { + "rows": expected_rows, + "first_unique_global": expected_first_global, + "last_unique_global": expected_last_global, + "build_identity": expected_identity, + "hidden_bytes": hidden_path.stat().st_size, + "lengths_bytes": lengths_path.stat().st_size, + } + if any(metadata.get(key) != value for key, value in expected.items()): + return False + return ( + metadata.get("hidden_sha256") == sha256_file(hidden_path) + and metadata.get("lengths_sha256") == sha256_file(lengths_path) + ) + + +def _write_chunk( + *, + dataset: UniqueCurrentDataset, + qwen: FrozenQwenCurrentLanes, + indices: Sequence[int], + stem: Path, + build_identity: dict[str, Any], + batch_size: int, + num_workers: int, + prefetch_factor: int, + rank: int, + split: str, +) -> dict[str, Any]: + stem.parent.mkdir(parents=True, exist_ok=True) + hidden_path = stem.with_suffix(".bf16") + lengths_path = stem.with_suffix(".lengths.i16") + metadata_path = stem.with_suffix(".json") + hidden_temp = hidden_path.with_name(f".{hidden_path.name}.rank{rank}.tmp") + lengths_temp = lengths_path.with_name(f".{lengths_path.name}.rank{rank}.tmp") + metadata_temp = metadata_path.with_name(f".{metadata_path.name}.rank{rank}.tmp") + for path in (hidden_temp, lengths_temp, metadata_temp): + path.unlink(missing_ok=True) + + loader = DataLoader( + dataset, + batch_size=batch_size, + sampler=list(indices), + num_workers=num_workers, + prefetch_factor=prefetch_factor if num_workers else None, + persistent_workers=False, + pin_memory=True, + collate_fn=collate_unique, + ) + rows = 0 + tokens = 0 + first_metadata: dict[str, Any] | None = None + last_metadata: dict[str, Any] | None = None + with hidden_temp.open("wb") as hidden_handle, lengths_temp.open("wb") as lengths_handle: + for batch in loader: + hidden, mask = qwen(batch["obs_last_lgr"], batch["instructions"]) + hidden = hidden.to(torch.bfloat16).cpu() + mask = mask.cpu() + for sample_hidden, sample_mask, item in zip(hidden, mask, batch["metadata"]): + lengths = sample_mask.sum(dim=-1).to(torch.int16) + if torch.any(lengths <= 0): + raise RuntimeError("Qwen produced an empty valid-token lane") + if torch.any(lengths > torch.iinfo(torch.int16).max): + raise RuntimeError("Qwen lane length exceeds the cache integer format") + lengths_handle.write(lengths.contiguous().numpy().astype("